Java Forum / General / June 2006
download a file from jsp
prado - 15 Jun 2006 11:55 GMT Hi,
I have a jsp where I show a table. I am trying to download this jsp like excel file. To do this I put this code in my jsp: <% response.setBufferSize(65536);
response.setHeader("Content-type","application/vnd.ms-excel");
String nombre = "fichero_excel.xls";
response.setHeader("Content-Disposition","attachment; filename=\"" + nombre + "\"");
response.setHeader("Pragma","no-cache"); %>
It works fine if I use only one browser.
The problem is when I try to do this but from 2 browsers at the same time. From each browser I can download a part of the file but not the complete file. It seems the browsers are sharing the bandwidth and when it starts to download a file the other stops.
Can you help me please?
Thanks.
Andrea Desole - 15 Jun 2006 12:37 GMT > Hi, > [quoted text clipped - 12 lines] > response.setHeader("Pragma","no-cache"); > %> this code is not complete. How do you write into the jsp? I appreciate the shortness, but try to post a complete example Also, if the only purpose of the jsp is to download a file, you should use a servlet
> It works fine if I use only one browser. > [quoted text clipped - 3 lines] > It seems the browsers are sharing the bandwidth and when it starts to > download a file the other stops. they are not sharing bandwidth, they are sharing your jsp, or better, the servlet generated from your jsp. Try to put some log messages in your jsp at the begin and the end, to see how it goes
prado - 15 Jun 2006 13:27 GMT the jsp code is the next:
<HTML> <HEAD>
<TITLE>Analyzed File</TITLE>
<BODY BACKGROUND="images/blanco51.gif" leftmargin=40 rightmargin=40 >
<form name="analyzedfile" method="POST" action="" >
<%@ page language="java" import="java.io.*"%>
<% response.setBufferSize(65536);
response.setHeader("Content-type","application/vnd.ms-excel");
String nombre = "fichero_excel33.xls";
response.setHeader("Content-Disposition","attachment; filename=\"" + nombre + "\"");
response.setHeader("Pragma","no-cache"); %>
<TABLE width="850" BORDER="5" CELLSPACING="1" CELLPADING="1" > <THEAD> <TR>
<TH class="letracabeceraetiqueta2"> <font class="letracabeceraetiqueta2"> Name</font></TH> <TH class="letracabeceraetiqueta2"> <font class="letracabeceraetiqueta2"> Type </font></TH> <TH class="letracabeceraetiqueta2"> <font class="letracabeceraetiqueta2"> Polymorphism </font></TH> <TH class="letracabeceraetiqueta2"> <font class="letracabeceraetiqueta2"> Out of Rank </font></TH> <TH class="letracabeceraetiqueta2"> <font class="letracabeceraetiqueta2"> X </font></TH> <TH class="letracabeceraetiqueta2"> <font class="letracabeceraetiqueta2"> Y </font></TH> <TH class="letracabeceraetiqueta2"> <font class="letracabeceraetiqueta2"> I/B </font></TH> <TH class="letracabeceraetiqueta2"> <font class="letracabeceraetiqueta2"> Not Valid </font></TH> <TH class="letracabeceraetiqueta2"> <font class="letracabeceraetiqueta2"> CV </font></TH> <TH class="letracabeceraetiqueta2"> <font class="letracabeceraetiqueta2"> Dist X </font></TH> <TH class="letracabeceraetiqueta2"> <font class="letracabeceraetiqueta2"> Dist Y </font></TH> </TR>
</THEAD> <TBODY>
<%
/* This array have 300 rows */
String[][] astrRdoAnalisis = (String[][]) request.getAttribute("astrRdoAnalisis");
for (int i=0; i<astrRdoAnalisis.length; i++) {
%>
<TR valign="top">
<TD class="letracabeceravalor2" align="left"> <font class="letracabeceravalor2"> <b> <% out.print(astrRdoAnalisis[i][0]); %> </b> <BR> </font> </TD> <TD class="letracabeceravalor2" align="center"> <font class="letracabeceravalor2"> <b> <% out.print(astrRdoAnalisis[i][1]); %> </b> <BR> </font> </TD> <TD class="letracabeceravalor2" align="center"> <font class="letracabeceravalor2"> <b> <% out.print(astrRdoAnalisis[i][2]); %> </b> <BR> </font> </TD> <TD class="letracabeceravalor2" align="center"> <font class="letracabeceravalor2"> <b> <% out.print(astrRdoAnalisis[i][3]); %> </b> <BR> </font> </TD> <TD class="letracabeceravalor2" align="right"> <font class="letracabeceravalor2"> <b> <% out.print(astrRdoAnalisis[i][4]); %> </b> <BR> </font> </TD> <TD class="letracabeceravalor2" align="right"> <font class="letracabeceravalor2"> <b> <% out.print(astrRdoAnalisis[i][5]); %> </b> <BR> </font> </TD> <TD class="letracabeceravalor2" align="right"> <font class="letracabeceravalor2"> <b> <% out.print(astrRdoAnalisis[i][6]); %> </b> <BR> </font> </TD> <TD class="letracabeceravalor2" align="center"> <font class="letracabeceravalor2"> <b> <% out.print(astrRdoAnalisis[i][7]); %> </b> <BR> </font> </TD> <TD class="letracabeceravalor2" align="right"> <font class="letracabeceravalor2"> <b> <% out.print(astrRdoAnalisis[i][8]); %> </b> <BR> </font> </TD> <TD class="letracabeceravalor2" align="right"> <font class="letracabeceravalor2"> <b> <% out.print(astrRdoAnalisis[i][9]); %> </b> <BR> </font> </TD> <TD class="letracabeceravalor2" align="right"> <font class="letracabeceravalor2"> <b> <% out.print(astrRdoAnalisis[i][10]); %> </b> <BR> </font> </TD>
</TR>
<% } %> </TBODY>
<tfoot></tfoot>
</TABLE>
</form>
</BODY> </HTML>
Andrea Desole - 15 Jun 2006 13:57 GMT > the jsp code is the next: > [quoted text clipped - 6 lines] > > <form name="analyzedfile" method="POST" action="" > no need to use a form
> <%@ page language="java" import="java.io.*"%> > [quoted text clipped - 10 lines] > response.setHeader("Pragma","no-cache"); > %> you are downlading an html as xls? And that works? Wow This looks a bit confusing. If you use a jsp with html then don't set the content-type. If you need an excel file I don't see how you can write html in it. Again, you should use a servlet Are you by chance trying to open an HTML file with Excel?
> <TABLE width="850" BORDER="5" CELLSPACING="1" CELLPADING="1" > > <THEAD> [quoted text clipped - 33 lines] > String[][] astrRdoAnalisis = (String[][]) > request.getAttribute("astrRdoAnalisis"); are you sure the values you get in this attribute are correct? How about logging them?
> for (int i=0; i<astrRdoAnalisis.length; i++) { > [quoted text clipped - 41 lines] > } > %> this looks kind of ok.
prado - 15 Jun 2006 15:19 GMT Hi,
Yes I am downloading the html as xls and it works.
You ask me if this attribute are corect, the answer is yes, i have to checked with the database and the attribute is correct. is not correct for you?
String[][] astrRdoAnalisis = (String[][]) request.getAttribute("astrRdoAnalisis");
Andrea Desole - 15 Jun 2006 15:49 GMT > Hi, > > Yes I am downloading the html as xls and it works. interesting
> You ask me if this attribute are corect, the answer is yes, i have to > checked with the database and the attribute is correct. is not correct > for you? what I meant is: are you sure that the value of the attribute is correct when the page is loaded? In othe words: maybe the page is working correctly, it simply gets the wrong values. For the rest it look basically okay, except the strange html/xls mix. I just wouldn't mix html and java code like that, but that's a minor problem. Even if you have more threads accessing the page that shouldn't bother you.
prado - 15 Jun 2006 16:31 GMT I send the array from a servlet to the jsp.
I am going to make a file and download from a servlet. I believe you have reason. It is better.
have you an example of a servlet that it makes the download?
Thanks.
Andrea Desole - 15 Jun 2006 17:14 GMT > I send the array from a servlet to the jsp. Right. But how do you make it? Is it possible that, when I download the second time, the application modifies the same attribute that is used to download the first time?
> I am going to make a file and download from a servlet. I believe you > have reason. It is better. You want to write the html to a file? To download a file a servlet is usually the solution (unless of course you have a static file somewhere on the server). In this case, however, you have a special situation where you want to open with Excel a file with html content. Quite unusual. In this situation your solution, although a bit weird, might be not so bad. Also, I'm afraid that a servlet won't solve your problem. Besides, if you really want to do it there is no point in writing everything to a file first.
What I would suggest is to try with only that jsp, no servlet before it and no fancy request attributes. Just take the content for your table from a static file, or make it directly in the JSP. And then see what happens
By the way: what application server are you using?
> have you an example of a servlet that it makes the download? It's not very different from what you put in the JSP: set the content type, add the disposition header, and write to the writer. Loads of examples on the internet. Just google it. For example
http://jspwiki.org/wiki/MakingADownloadServlet
Luke Webber - 16 Jun 2006 00:07 GMT > I send the array from a servlet to the jsp. > > I am going to make a file and download from a servlet. I believe you > have reason. It is better. > > have you an example of a servlet that it makes the download? I have a sneaking suspicion that I know what's wrong here. Is it possible that the array you're sending from the servlet is an instance variable? If so, you need to be aware that multiple requests to the servlet will all share the same array. You need to make it a method-local variable, and pass it as an argument if you need to access it in more than one method of the servlet, or possibly to instantiate a new array for each request and place it in the session to share it.
Just a quick note to Andrea: The HTML/XLS thing is actually quite useful. Google 'excel "web connectivity kit"' if you want to know more about this.
Luke
Andrea Desole - 16 Jun 2006 09:18 GMT > I have a sneaking suspicion that I know what's wrong here. Is it > possible that the array you're sending from the servlet is an instance [quoted text clipped - 3 lines] > it in more than one method of the servlet, or possibly to instantiate a > new array for each request and place it in the session to share it. this is an option. But it's also possible that, without using instance variables in the servlet, this attribute is made in a way (via session/static variables, for example) such that different calls to the servlet actually put the same object (intended as reference) in the request. We cannot know if we don't know how this attribute is built.
> Just a quick note to Andrea: The HTML/XLS thing is actually quite > useful. Google 'excel "web connectivity kit"' if you want to know more > about this. has been a while since I made my last MS application :-) I can imagine that someone wants to open a page directly with Excel. I actually have never thought of it. This must be the reason why I think that changing the content type of an HTML page looks a bit strange.
Luke Webber - 16 Jun 2006 14:39 GMT [snip]
> this is an option. But it's also possible that, without using instance > variables in the servlet, this attribute is made in a way (via > session/static variables, for example) such that different calls to the > servlet actually put the same object (intended as reference) in the > request. We cannot know if we don't know how this attribute is built. Too true, but my money is on the instance variable. It's one of those mistakes that's just too easy to make, forgetting that you don't get an instance per request.
>> Just a quick note to Andrea: The HTML/XLS thing is actually quite >> useful. Google 'excel "web connectivity kit"' if you want to know more >> about this. > > has been a while since I made my last MS application :-) Yeah, yeah. Showoff. ;^)
> I can imagine that someone wants to open a page directly with Excel. I > actually have never thought of it. This must be the reason why I think > that changing the content type of an HTML page looks a bit strange. If you think that's strange, you should see the CSS extensions for handling dates and numbers. <g>
Luke
Andrea Desole - 16 Jun 2006 14:48 GMT > Yeah, yeah. Showoff. ;^) who? Me? Never :-)
> If you think that's strange, you should see the CSS extensions for > handling dates and numbers. <g> CSS? As in Cascading Style Sheets? I think I'll trust you :-)
prado - 16 Jun 2006 15:52 GMT Hi Like,
Can you help me? I have tried to do it with a servlet and the result is the same. I think that the variables are shared. I explain my method.
the servlet with the array calls to the jsp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// the SERVLET has the next code: /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// import java.io.*; import java.sql.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class ViewRdoAnalyzedFile extends HttpServlet{ public boolean fncVerFicheroAnalizado ( HttpServletRequest request, HttpServletResponse response) {
public boolean fncVerFicheroAnalizado ( HttpServletRequest request, HttpServletResponse response) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection(url,usuario,password);
String strCod_analisis = (String) request.getAttribute("analisis");
int intCod_analisis = Integer.parseInt(strCod_analisis);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rsRdosAnalisis = stmt.executeQuery ("SELECT NUM_MUTA, CAL_MUTA, CAL_NOMBRE, POLI, OUT, ROUND(X,2) X, ROUND(Y,2) Y FROM tablasfg WHERE codigo = " + intCod_analisis );
boolean blnUltimoRdos = rsRdosAnalisis.last();
int intContadorRegistrosRdos = rsRdosAnalisis.getRow(); rsRdosAnalisis.beforeFirst();
String [][] astrRdoAnalisis = new String[intContadorRegistrosRdos][11];
String strNumMutation; String strCalMutNombre; String strCalMutado; String strPolimorfismo; String strOutRank; String strX; String strY;
while(rsRdosAnalisis.next()){ strNumMutation = rsRdosAnalisis.getString("NUM_MUTA"); strCalMutado = rsRdosAnalisis.getString("CAL_MUTA"); strCalMutNombre = rsRdosAnalisis.getString("CAL_NOMBRE"); strPolimorfismo = rsRdosAnalisis.getString("POLI"); strOutRank = rsRdosAnalisis.getString("OUT"); strX = rsRdosAnalisis.getString("X"); strY = rsRdosAnalisis.getString("Y"); astrRdoAnalisis[i][0] = strCalMutNombre; astrRdoAnalisis[i][1] = strCalMutado; astrRdoAnalisis[i][2] = strPolimorfismo; astrRdoAnalisis[i][3] = strOutRank; astrRdoAnalisis[i][4] = strX; astrRdoAnalisis[i][5] = strY; i++; }
rsRdosAnalisis.close(); conn.close();
request.setAttribute("astrRdoAnalisis", astrRdoAnalisis); RequestDispatcher rd = request.getRequestDispatcher("/analyz.jsp"); rd.forward(request,response); return true;
} // end try
catch(Exception ex) { return false; }
} //end de la funcion
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
boolean blnMostrar = fncVerFicheroAnalizado( request, response); } }
//////////////////////////////////////////////////////////////////////////////////////////////////////// the JSP (analyz.jsp) has the next code::
////////////////////////////////////////////////////////////////////////////////////////////////
<%@page contentType="application/vnd.ms-excel"%>
<%@ page language="java" import="java.io.*"%>
THE RESULT ARE:
<% String[][] astrRdoAnalisis = (String[][]) request.getAttribute("astrRdoAnalisis");
for (int i=0; i<astrRdoAnalisis.length; i++) { out.write(astrRdoAnalisis[i][0] + "\t" ); out.write(astrRdoAnalisis[i][1] + "\t" ); out.write(astrRdoAnalisis[i][2] + "\t" ); out.write(astrRdoAnalisis[i][3] + "\t" ); out.write(astrRdoAnalisis[i][4] + "\t" ); out.write(astrRdoAnalisis[i][5] + "\t" ); out.write("\n"); }
%>
Why are they sharing the variables? can you help me?
Luke Webber - 17 Jun 2006 01:29 GMT > Hi Like, > [quoted text clipped - 3 lines] > > the servlet with the array calls to the jsp [snip]
Does that compile? I can't see where you've declared your variable "conn". If you're sharing a single connection between requests, that could well be your problem.
Luke
prado - 19 Jun 2006 08:14 GMT Hi,
Yes, the servlet calls to jsp. The servlet read the database and it stores the information in astrRdoAnalisis variable and then send this variable to the jsp. is correct?
the connection declaration is before the try.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
the SERVLET has the next code: ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import java.io.*; import java.sql.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class ViewRdoAnalyzedFile extends HttpServlet{
public boolean fncVerFicheroAnalizado ( HttpServletRequest request, HttpServletResponse response) {
String bd = "orcl"; String usuario = "alex14"; String password = "alex14"; String url = "jdbc:oracle:thin:@196.154.4.189:1521:"+bd;
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection(url,usuario,password);
String strCod_analisis = (String) request.getAttribute("analisis");
int intCod_analisis = Integer.parseInt(strCod_analisis);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rsRdosAnalisis = stmt.executeQuery ("SELECT NUM_MUTA, CAL_MUTA, CAL_NOMBRE, POLI, OUT, ROUND(X,2) X, ROUND(Y,2) Y FROM tablasfg WHERE codigo = " + intCod_analisis );
boolean blnUltimoRdos = rsRdosAnalisis.last();
int intContadorRegistrosRdos = rsRdosAnalisis.getRow(); rsRdosAnalisis.beforeFirst();
String [][] astrRdoAnalisis = new String[intContadorRegistrosRdos][11];
String strNumMutation; String strCalMutNombre; String strCalMutado; String strPolimorfismo; String strOutRank; String strX; String strY;
while(rsRdosAnalisis.next()){ strNumMutation = rsRdosAnalisis.getString("NUM_MUTA"); strCalMutado = rsRdosAnalisis.getString("CAL_MUTA"); strCalMutNombre = rsRdosAnalisis.getString("CAL_NOMBRE");
strPolimorfismo = rsRdosAnalisis.getString("POLI"); strOutRank = rsRdosAnalisis.getString("OUT"); strX = rsRdosAnalisis.getString("X"); strY = rsRdosAnalisis.getString("Y"); astrRdoAnalisis[i][0] = strCalMutNombre; astrRdoAnalisis[i][1] = strCalMutado; astrRdoAnalisis[i][2] = strPolimorfismo; astrRdoAnalisis[i][3] = strOutRank; astrRdoAnalisis[i][4] = strX; astrRdoAnalisis[i][5] = strY; i++; }
rsRdosAnalisis.close(); conn.close();
request.setAttribute("astrRdoAnalisis", astrRdoAnalisis);
RequestDispatcher rd = request.getRequestDispatcher("/analyz.jsp"); rd.forward(request,response); return true;
} // end try
catch(Exception ex) { return false; }
} //end de la funcion
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
boolean blnMostrar = fncVerFicheroAnalizado( request, response);
} }
////////////////////////////////////////////////////////////////////////////////////////////////////////
the JSP (analyz.jsp) has the next code::
////////////////////////////////////////////////////////////////////////////////////////////////
<%@page contentType="application/vnd.ms-excel"%>
<%@ page language="java" import="java.io.*"%>
THE RESULT ARE:
<% String[][] astrRdoAnalisis = (String[][]) request.getAttribute("astrRdoAnalisis");
for (int i=0; i<astrRdoAnalisis.length; i++) { out.write(astrRdoAnalisis[i][0] + "\t" ); out.write(astrRdoAnalisis[i][1] + "\t" ); out.write(astrRdoAnalisis[i][2] + "\t" ); out.write(astrRdoAnalisis[i][3] + "\t" ); out.write(astrRdoAnalisis[i][4] + "\t" ); out.write(astrRdoAnalisis[i][5] + "\t" ); out.write("\n"); }
%>
prado - 19 Jun 2006 13:32 GMT Please, I need help. I am with this problem a lot and I don't know how solve it. I have to trace the file and apparently it send the paremeter well but the files are incorrects. The files are incomplets.
Can anybody help me please?
Andrea Desole - 19 Jun 2006 14:43 GMT > Please, I need help. I am with this problem a lot and I don't know how > solve it. It does look a bit strange. I can't see anything bad in the code. I have one more question. I can see there is another request attribute, analysis, that you read in your servlet. Do you have another servlet that is called?
> I have to trace the file and apparently it send the paremeter well but > the files are incorrects. The files are incomplets. What do you mean? The results from the database are incorrect?
prado - 19 Jun 2006 15:46 GMT > It does look a bit strange. I can't see anything bad in the code. > I have one more question. I can see there is another request attribute, > analysis, that you read in your servlet. Do you have another servlet > that is called? the steps is the next: JSP --> Servlet(ViewRdoAnalyzedFile) ---------------> JSP (analyz.jsp)
I have look the logs and the file has downloaded to the computer and while the the jsp is working. I don't undestand why the file has finished to download and while the jsp is still executing.
prado - 19 Jun 2006 15:46 GMT > It does look a bit strange. I can't see anything bad in the code. > I have one more question. I can see there is another request attribute, > analysis, that you read in your servlet. Do you have another servlet > that is called? the steps is the next: JSP --> Servlet(ViewRdoAnalyzedFile) ---------------> JSP (analyz.jsp)
I have look the logs and the file has downloaded to the computer and while the the jsp is working. I don't undestand why the file has finished to download and while the jsp is still executing.
Andrea Desole - 19 Jun 2006 17:37 GMT > the steps is the next: > JSP --> Servlet(ViewRdoAnalyzedFile) ---------------> JSP > (analyz.jsp) okay. So I think you posted the servlet and the second jsp. Can you post the first jsp, so the picture is complete?
> I have look the logs and the file has downloaded to the computer and > while the the jsp is working. I don't undestand why the file has > finished to download and while the jsp is still executing. this is not clear. What do you mean?
prado - 19 Jun 2006 17:47 GMT Can anybody try this JSP from 2 browsers at the time? So you can see the problem.
You can see the log
--------------------------JSP------------------------------------------------------
<%@page contentType="application/vnd.ms-excel"%>
<%@ page language="java" import="java.io.*"%> <%@ page language="java" import="java.util.*"%>
<%
Date fecha = new Date();
java.sql.Date fechaSQL = new java.sql.Date(fecha.getTime());
Calendar calendario = Calendar.getInstance(); calendario.setTime(fecha); // fecha es el Date de antes. String strHour = String.valueOf( calendario.get(Calendar.HOUR) ); String strMinute = String.valueOf( calendario.get(Calendar.MINUTE) ); String strSecond = String.valueOf( calendario.get(Calendar.SECOND) );
String nombre = "FILE" + strHour + strMinute + strSecond + ".xls";
System.out.println( " IN OF " + nombre );
response.setContentType( "application/x-download" );
response.setHeader("Content-type","application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment; filename=\"" + nombre + "\"");
System.out.println( nombre + " START" );
for (int l=0;l<15000;l++){ System.out.println( nombre + " " + l );
for (int k=0;k<250;k++){
out.write(nombre + " : ("+ l + "," + k + ")" + "\t" );
} out.write("\n");
}
System.out.println( nombre + " END" );
%>
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|