How to make the Open/Save dialogue download the text file instead of JSP

I am currently coding on a JSP program, which searches the database and writes the resultset into a file on the server, and then allows the client to download this tab delimited text file onto their local machine. But I met a problem, when the default Open or Save dialogue appears, it shows that it's trying to download the running JSP file from my local host instead of the newly-created text file. Despite this, when I click OK to either Open or Save the file, a warning dialogue will appear saying: The explorer cann't download this file, it's unable to find this internet site or something like that. I get no error message from the server but I was always told that Javax.servlet.ServletException: getWriter() was already called. What does this mean?

I guess maybe this is caused by the mix use of outputStreams in my program. I don't know if there is a way to directly read the resultset from the database and then send it through outputStream to the client. My solution is: first create a file on the server to hold the resultset, and then output this file to the client. I did all these in one JSP program: Create file on the server, search database, and then read file and output the contents to client. Is this correct? I attached my code, please feel free to correct any of my mistake? Thanks!

//global.class is a class dealing with database connection

<%@ page language="java" import="java.sql.*,java.util.*,java.math.*,java.io.*,ises.*,frmselection.*" %>

<jsp:useBean id="global" scope="session" class="ises.Global" />

/>

<!--start to process data-->

<%

//get query statement from the session

String sQuery = "";

if (session.getAttribute("sQuery")!=null && !(session.getAttribute("sQuery").toString()).equals(""))

{

sQuery = session.getAttribute("sQuery").toString();

}

String path = "c:/temp";

String fileName = "temp.TXT";

File file= null;

FileOutputStream fo = null;

PrintStream ps = null;

try {

file = new File(path,fileName);

if(file.exists()) {

file.delete();

file.createNewFile();

}

fo = new FileOutputStream(file);

ps = new PrintStream(fo);

}catch(IOException exp){

System.out.println("IO Exception: " +exp.toString() );

}

java.sql.ResultSet recResults= null;

java.sql.Statement STrecResults = null;

STrecResults = global.getConnection().createStatement();

recResults= STrecResults.executeQuery(sQuery);

ResultSetMetaData meta = recResults.getMetaData();

int columns = meta.getColumnCount();

String [] tempColumnName = new String[columns];

String [] ColumnName =null;

int DisColumns = 0;

int unDisCol = 0;

String sLine = "";

if(recResults.next()) {//if_1

for(int n=0;n<columns;n++) {

String temp = meta.getColumnName(n+1);

if(!temp.equals("PROJECTID")&&!temp.equals("BUILDINGID")&&!temp.equals("HAZMATPROFILEID")) {

sLine = sLine + "'" + temp + "'" + " ";

tempColumnName[DisColumns] = temp;

DisColumns ++;

ColumnName = new String[DisColumns];

}else {

unDisCol ++;

}

}//end for

for(int i=0;i<(columns-unDisCol);i++) {

ColumnName = tempColumnName;

}

ps.println(sLine);

do{

sLine = "";

for(int n=0;n<(columns-unDisCol);n++) {

String tempColName = recResults.getString(ColumnName[n]);

if(tempColName==null) {

sLine = sLine + "" + " ";

} else {

sLine = sLine + "'"+tempColName+"'" + " ";

}

}

ps.println(sLine);

}while(recResults.next());

}//end if_1

recResults.close();

recResults = null;

STrecResults.close();

STrecResults = null;

%>

<!--end of processing data-->

<!--start of download.jsp-->

<%

//set the content type to text

response.setContentType ("plain/text");

//set the header and also the Name by which user will be prompted to save

response.setHeader ("Content-Disposition", "attachment;filename=temp.TXT");

//Open an input stream to the file and post the file contents thru the servlet output stream to the client

InputStream in = new FileInputStream(file);

ServletOutputStream outs = response.getOutputStream();

int bit = 256;

try {

while ((bit) >= 0) {

bit = in.read();

outs.write(bit);

}

} catch (IOException ioe) {

ioe.printStackTrace(System.out);

}

outs.flush();

outs.close();

in.close();

%>

<!--end of download -->

[4872 byte] By [huangjjing] at [2007-9-26 2:30:39]
# 1

You have two ways to do it because i was also facing the same problem. U cannot use send redirect or forward. Because u r generating HTML content before downloding. second dialog box because ur path is incorrect. Rest of the things i am finializing i will tell you tomarrow after finishing it

priviet at 2007-6-29 9:49:48 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

Thanks. I believe something wrong with this statement in my program:

ServletOutputStream outs = response.getOutputStream();

because I put a lot of printout statement within my code, and the program stops to print out exactly before the above statement. And then I get the following message, which repeats several times:

ServletExec: caught exception - javax.servlet.ServletException: getWriter() was already called.

I guess maybe I can't use printStream and ServletOutputStream together within one program. I also tried to use Output stream instead of ServletOutputStream, it works the same way. Hope you can figure this out. Thanks again.

huangjjing at 2007-6-29 9:49:49 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

when ever u want to download file use this only this will work

after writing all the HTML contents use but in my case it was working only for 2 files if in folder more then 2 files it was not setting header (Even i think this is a bug)

res.setHeader("Refresh","1;URL=/servlet/DownloadServlet?folder="+folder+"&fname="+fname);

Then i have used this it is working fine

out.println("<meta http-equiv=\"refresh\" content=\"0; URL=/servlet/DownloadServlet?folder="+folder+"&fname="+fname+"\">");

if you will find some other solution let me know

priviet at 2007-6-29 9:49:49 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4

then code in download servlet

String fname=req.getParameter("fname");

String folder1=req.getParameter("folder");

String folder=folder1+"/"+fname+".pdf";

res.setContentType("application/pdf");

res.setHeader("Content-Disposition","attachment;filename="+fname+".pdf;");

ServletOutputStream stream = res.getOutputStream();

BufferedInputStream fif =

new BufferedInputStream(new FileInputStream(folder));

int data;

while((data = fif.read()) != -1) {

stream.write(data);

}PrintWriter out = res.getWriter();

fif.close();

stream.close();

priviet at 2007-6-29 9:49:49 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5

> Thanks. I believe something wrong with this statement

> in my program:

>

You are correct there is something wrong with this statement. Seeing how you are doing this in a jsp, not really what they're made for but thats another topic, the output stream has already been called. When a jsp gets compiled it creates a few implicit objects, one of them being the outputstream out, and it does this by calling the response.getWriter().getWriter or getOutputStream can only be called once, other wise you will get the exception you are experiencing. This is for both methods as well, seeing how the jsp compiles and calls getWriter means that you cannot call getOutputStream. Calling one makes the other throw the exception if called as well. As far as the filename problem in the browser goes I'm guessing that it's in IE. I've had some problems before when I had to send files to the browser through a servlet and remember having to set an inline attribute of some sort in the content-dis header inorder to get IE to see the real filename. The best way to solve this is to get the orielly file package and use that. It is very easy to use and understand and does all of this for you already. Plus it's free. Cant beat that.

> ServletOutputStream outs =

> response.getOutputStream();

>

> because I put a lot of printout statement within my

> code, and the program stops to print out exactly

> before the above statement. And then I get the

> following message, which repeats several times:

>

> ServletExec: caught exception -

> javax.servlet.ServletException: getWriter() was

> already called.

>

bobd3 at 2007-6-29 9:49:49 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 6
setting inline will directory open file without showing save /open dialogsame problem i was facing i have used html refresh header and call fileiopen servet it will not move open new page ( will not refresh current page) it will just open save/open dialog try it it works better
priviet at 2007-6-29 9:49:49 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...