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[i] = 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 -->

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.

Similar Messages

  • Firefox open images in a new tab upon clicking the link,how to make firefox to save images in the folder upon clicking the link

    firefox open images in a new tab upon clicking the link,how to make firefox to save images in the folder upon clicking the link.

    You can right-click the image and use "Save Image As" to save that image.

  • Can't tab into file list when using column view in the open/save dialogue boxes

    Hi,
    When in Open/Save Dialog Boxes I can't use tab to select the file/folder list in Column View. Tab will only cycle through Save As, Tags, Search, and the Sidebar. In all the other views (Icon, List, Cover) I can tab into the file list. Is this a bug?
    I know that enabling Full Keyboard Access will make this work, but I'd rather not do that since it increases the number of buttons you must tab through to get to the file list.
    I'm using the latest version of Yosemite on a 2014 Macbook Air. Thanks.

    Hi,
    Did you found the solution to this? I'm also trying to do something like you , but I got stuck up in a very primitive stage than you. I'm not getting how I can make that File Download window to appear. Can you help me please.
    Thanks.

  • How to make attachment opening preferences stay with the document through distribution.

    I have a PDF that has links to other PDF's as attachments. I want these attachments to be opened in a new window on the target computer that I am sending this document to, despite what the target computer has it's preference set as. I don't want them to open in the same window as is the default option. Is there any way to do this?

    You can edit the link and specify that it opens the target document in a new window. This will override whatever the user preference is set to.

  • How to get Open/Save Dialogue box

    Hi,
    I need to get open/save dialogue box while downloading a file (from JSP).
    One way which I am currently using is on click of the button pass control to servlet and in servlet using the following code:
    /**.....Some Code */
    response.setContentType("application/csv");
    response.setHeader("Content-Disposition", "attachment; filename=" + filename);
    /**.....Some Code */But I am wondering is there any way I can do the same without passing the control to Servlet? On clicking the button in JSP, is there is any possibilty to get the Open/Save dialogue box directly.
    Thanks
    Arun

    without passing the control to Servlet?Why?
    In HTTP you can send the response only once.The application where i have this requirement is an old one. In the application, I have there are some screens, whose control never goes to Servlet.
    TO be more precise, 2 pages one HTML and another JSP. And the file to be downloaded is created when JSP is called from HTML page. And there is no interaction with Servlet. The JSP inturn calls a method in Java file (which is not a Servlet) and gets all the details including the file to be downloaded.
    I have used window.open() to download the file(in JSP) in order to have Open/Save dialogue box.
    But the approach is working fine in Windows XP systems but not in Windows2000. In Win00 machines it is directly opening the file in popup without giving the user any option for Open/Save.
    Please let me know your suggestion on this.
    Thanks

  • How to make movies open in the center of my screen.

    Does anyone know how to make Quicktime open up videos in the center of a screen? When I double click any movie file it pops open in the uppermost far left corner, and I have to drag it down into a more comfortable area. It's annoying with a large monitor.
    Thanks
    noodle--head

    The script writing lobe of my brain was damaged by years of drug abuse, years ago. Try as I might, I can't seem to get it right.
    The most common error I get is:
    Expected end of line, etc. but found “end tell”.
    I tried modeling one of any number of existing scripts but still no dice.
    I tried this:
    tell application "QuickTime Player"
    activate
    set the bounds of window 1 to {235, 58, 944, 590}
    end tell
    And got this error message: QuickTime Player got an error: NSReceiverEvaluationScriptError: 4
    I know this is simple but, like I said...
    nnooo-dlehead ssslowto catchon

  • Open/Save Dialogue appears twice in Download

    Hi all,
    I am trying to write a text file to the client when the client clicks on some download link.... this is what I am doing.....
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    bout.write('A');
    response.setContentType("application/text");
    response.setHeader("Content-Disposition", "attachment;filename=AuditTrial.txt");
    response.setContentLength(bout.size());
    ServletOutputStream strp = response.getOutputStream();
    bout.writeTo(strp);     
    bout.close();
    when I run this.... Im getting the Open/Save dialog.....
    When I choose "Save".... its working fine.....
    and when I choose "Open".... it is prompting me the Open/Save dialog again.... and then it is opening.... so the client is getting the dialog twice when chooses "Open" option...... but there is no problem in the output as such... its working fine... its just that Im getting the Dialog twice when i choose "Open".
    Can someone help me out in this regard....
    ThanX in Adv,
    Kiran,
    [email protected]

    If you use html form to submit download request, it will give you twice dialog. Use hyperlink to download, there will be only one dialog.

  • How do i disable the open/save image dialog box in firefox? I want to directly save the image file to the drive.

    How do i disable the open/save image dialog box in firefox? I want to directly save the image file to the drive without clicking on save option everytime when saving an image. I'm using firefox ver 35.0.1 for windows 7.

    Click on the Firefox menu. Then click "Options". Go to "Applications" tab. Search for jpg and png file type. You will find they have "Always ask" action attribute. Change it to "Save file".
    Hope it will work fine for you.

  • How can I use terminal to make links open in same window the default behaviour, as it was in Safari 5.0, How can I use terminal to make links open in same window the default behaviour, as it was in Safari 5.0

    In Lion, the default of pressing a link on a web page, is to open the page in a new tab. In itself, I do like this because this is what I did for 19 out of any 20 links, which I command+clicked in previous Safari versions.
    However, there is a snag to this behaviour. Most (all?) secure site do not like links to be opened in a new tab. For example, when I am doing Web banking, The the linked page doesn’t open in new tab. Rather I get a page telling me my login session is expired. Probably a security measure instituted by my bank.
    I since found out, that a command-click opens lings in the same window. Theoretically that solves the problem, if I would think about this all the time. I don't. Old habits die slowly.
    Is there a terminal command to make links open in same window the default behaviour, as it was in Safari 5.0.

    Hi Eric,
    I got it figured out today, basically you have to load the Parallel Flash Loader first into FPGA ram. It is a special .sof file (pfl_epXXXX.sof) based on your FPGA. Code is actually pretty straight forward, using the Sys Exec VI. Use the windows based programmer to generate the .cdf file that identifies your FPGA, attached Flash and .pof file .
    Syntax was odd going into Sys Exec. Note the extra "C" in in front of the "quartus_prm.exe" I have no idea why that was needed, but I was getting an error until I just happened to put it in there (Blind Luck :-))
    I used a 2 element array going into a four loop
    cmd /cquartus_pgm.exe -c USB-BLASTER -m JTAG -o P;pfl_epXXXX.sof
    cmd /cquartus_pgm.exe -c USB-BLASTER -m JTAG S_FPGA.cdf
    Defining the working director C:\altera\12.1sp1\qprogrammer\bin
    And added match string with "Successfully performed operation" on the output in the loop to make sure everything loaded correctly then adding the array to give me a overall P/F
    To anyone doing this same thing Altera's documentation is poor to say the least. It took most of a week to figure this out Not allowed to upload code, so anyone wanting details just post here and I will try to help. This was painful, with lots of lessons learned.
    Thanks for the interest though
    Best regards John

  • Codesigned Projector and BuddyAPI (or other File Open/Save Dialogue)

    I noticed that with the Buddy Xtra, if baGetFilename call is made when an application is Codesigned, it will crash.
    Actually ANY attempt to use any file open/save dialogue attempt in a Codesigned application will not work.
    Has anybody found a work around for this?

    Hi,
    Did you found the solution to this? I'm also trying to do something like you , but I got stuck up in a very primitive stage than you. I'm not getting how I can make that File Download window to appear. Can you help me please.
    Thanks.

  • Open save dialogue box wehn run servlet program

    hi,
    i m having one servlet file(Write_File.java).. in this prog i retrive some data form one table and write into one file(c:\\write.be).. its automatically stored tat file in server machine.. now what my issue is when i run Write_File.java, it sholud have to shows save dialogue box..
    file name : Write_File.java
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class Write_File extends HttpServlet
         public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
              PrintWriter out = response.getWriter();
              //boolean header = true;
    FileOutputStream fos = new FileOutputStream("c:\\write.be");
              try
                   Class.forName("com.mysql.jdbc.Driver");
                   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cha_db","root","user");
                   Statement stat = con.createStatement();
                   ResultSet rs = stat.executeQuery("Select * from acc_ledger");
                   ResultSetMetaData rs_meta = rs.getMetaData();
                        out.println(rs_meta.getColumnName(1)+"\t"+rs_meta.getColumnName(2));
                        fos.write((rs_meta.getColumnName(1)+"\t\t"+rs_meta.getColumnName(2)+"\r\n").getBytes());
                        fos.write(("--------------\t\t--------------\r\n").getBytes());
                   while(rs.next())
                        fos.write((rs.getString(2)+"\t\t"+rs.getString(3)+"\r\n").getBytes());
                   fos.write(("========\t\t========\r\n").getBytes());               
              catch(Exception e)
                   out.println(e);
              fos.flush();
              fos.close();
    pls solve this problem
    by
    senthilkumar
    thnks in advance
    Edited by: vishruta on Nov 16, 2007 3:02 AM

    without passing the control to Servlet?Why?
    In HTTP you can send the response only once.The application where i have this requirement is an old one. In the application, I have there are some screens, whose control never goes to Servlet.
    TO be more precise, 2 pages one HTML and another JSP. And the file to be downloaded is created when JSP is called from HTML page. And there is no interaction with Servlet. The JSP inturn calls a method in Java file (which is not a Servlet) and gets all the details including the file to be downloaded.
    I have used window.open() to download the file(in JSP) in order to have Open/Save dialogue box.
    But the approach is working fine in Windows XP systems but not in Windows2000. In Win00 machines it is directly opening the file in popup without giving the user any option for Open/Save.
    Please let me know your suggestion on this.
    Thanks

  • How to make a physical standby database in the read_only state in 11g?

    In 10g, we can make a physical standby database in the read_only state. But in 11g, no a read_only state for a physical standby database. How to make a physical standby database in the read_only state in 11g?

    Hi
    read-only mode (for 11g physical standby)
    A mode in which a database can be opened that allows queries, but disallows modifications.
    A physical standby database can be opened read-only so that queries may be performed. If a license for the Oracle Active Data Guard option has been purchased, a physical satndby database can be open while redo apply is active. This capability is known as Real-time Query.
    For more details have a look at:
    http://download.oracle.com/docs/cd/B28359_01/server.111/b28294/manage_ps.htm#SBYDB00706
    Hipe this Helps
    Regards

  • Display corruption in open/save dialogue window

    Anyone noticed this one - When opening or saving files in applications, if I drag the sidebar edge in the open/save window to make the column wider or narrower, then scroll any column to the right of the sidebar, the folders/files in that column blur and distort. This happens in most 3rd party apps - eg Word, Quark, Dreamweaver, also iTunes but not in Safari or Extensis Suitcase (which seem to use a slightly different type of dialogue window.
    If I use the sidebar default width (where it 'clicks' to a set width), move the sidebar to it's furthest width possible, or close the sidebar altogether, the problem disappears.
    I've only just noticed this issue, but I may just have never tried to alter the sidebar width in combination with scrolling before now - it may be an OSX10.4.5 issue which I've only updated to recently. The standard finder window behaves normally, it only goes weird when trying to open or save from an app.
    Seems like Quartz is having problems somewhere.
    I've trashed the sidebar preferences, removed and restored the sidebar items/aliases, repaired privileges but no difference.
    I've tested this on a recent Hard drive/system backup and the problem appears there too. I've yet to test it on my old G4 as I can't get access to that today.
    I've got a new G5 with a GeForce 6600 card with 256MB VRam so there shouldn't be a memory problem.
    Any thoughts anyone?
    G5 2.5 Dual Core 2Gb RAM   Mac OS X (10.4.4)  

    Just found out it's a problem with the Wacom Intuos3 tablet pen - the symptom doesn't occur using the apple mouse (or the Intuos mouse either). Have reinstalled the Intuos driver, repaired permissions etc but problem persists. Sounds like an issue for the Wacom techies.

  • How to make Firefox open automatically a new, empty tab in each start, but keep last sessions?

    How to make Firefox open automatically a new, empty tab in each start? (keep last sessions as well) It will be good, because Firefox wont load the previous sessions last watched tab after start straight away, but keep my previous sessions tab as well in the browser.

    Hello,
    You can change your home page settings to open a blank tab:
    * Tools (or [[Image: New Fx Menu]]) > Options > General
    * Beside "Startup", change to "Show a blank tab"
    * See the article [[Startup, home page and download settings]] for more information
    To retrieve your previous browsing session, first make sure that you are not running in [[Private Browsing - Browse the web without saving information about the sites you visit|Private Browsing mode]]. When you start Firefox, to recover your previous session, you can go to:
    * History (or [[Image: New Fx Menu]] > History) > Restore Previous Session
    * Please see [[Restore previous session - Configure when Firefox shows your most recent tabs and windows]] for more information

  • How to download a text file from the server

    hi everyone,
    can anyone tell me how to download and read a text file from the server and saved in into resource folder.
    with regards
    pallavi

    its really easy
    To read from server, use something like:
    HttpConnection connector = null;
    InputStream inp_stream = null;
    OutputStream out_stream = null;
    void CloseConnection()
         if(inp_stream!=null)inp_stream.close();
         inp_stream=null;
         if(out_stream!=null)out_stream.close();
         out_stream=null;
         connector.close();
         connector = null;
    public void getResponse(String URL,String params)
      try
         if(connector==null)connector = (HttpConnection)Connector.open(URL);//URL of your text file / php script
         connector.setRequestMethod(HttpConnection.POST);
         connector.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.1");
         connector.setRequestProperty("content-type", "application/x-www-form-urlencoded");
         //connector.setRequestProperty("charset","windows-1251");
         //*** If you need to send ("arg1=value&arg2=value") arguments to script use this:
         out_stream = connector.openOutputStream();
         byte postmsg[] = params.getBytes();
         out_stream.write(postmsg);
         int rc = connector.getResponseCode();//in any case here connection will be opened & closed
         if (rc != HttpConnection.HTTP_OK)
              CloseConnection();
              throw new IOException("HTTP response code: " + rc);
         inp_stream = connector.openInputStream();
         int pack_len = inp_stream.available();
         byte answ[]=new byte[pack_len];
         inp_stream.read(answ);
         CloseConnection();
         ProcAnswer(answ);//process received data
      catch(Exception ex)
         System.err.println("ERROR IN getResponse(): "+ex);
    } And you can read from resource file like
    public void loadFile(String filename)
        DataInputStream dis = new DataInputStream(getClass().getResourceAsStream("/"+filename));
        String str="";
        try
             while (true)
                ch = dis.read();//read character
                if(ch=='\r')continue;//if file made in windows
                if(ch=='\n' || ch==-1)//end of line or end of file
                    if(str.length()==0)continue;//if empty line
                    //do some thing with "str"
                    if(ch==-1)break;//it was last line
                    str="";//next line
                    continue;
                 str+=(char)ch;
           dis.close();
       catch (Exception e)
           System.err.println("ERROR in loadFile() " + e);
    }Welcome! =)
    Edited by: MorskoyZmey on Aug 14, 2008 3:40 AM

Maybe you are looking for

  • How to use two harddrives on one PC to store Itunes music

    I have 13,000 songs in Itunes, all in Apple lossless format. The main harddrive is full. I have a 400Gb external drive also. I can get Itunes to point to either drive but not to both at the same time. Does anyone know how to accomplish using both dri

  • India localization patch tool issue

    Hi, I am applying india localization patch using india localization patch tool. Getting below error while applying patch ***Error! Cannot find executable /app/oracle/UAT/apps/tech_st/10.1.2/bin/f60gen . Exiting.. ***Failed validating arguments. Exiti

  • Problem with entering Genius

    I have a problem subscribing to genius from my macmini. I am using the same username and pass that i use for my mac nad macbook but it says that there are technical problems nad come back later but later nothing happens the problems exists Please giv

  • Add an icon to a button

    Hello , I'm working with eclipse to prgram mu project I want to add for a button an icon and when I press this button this icon will be drawed. this is my code : import javax.swing.Icon ; public class Fenetre extends JFrame      Icon img = new Icon("

  • Order Cancel Report

    Hi, Is there a standard report that can be used to view canceled sales order? May I know how do I tell whether the particular sales order line has been canceled? Other than viewing the reason code. Thanks. Rewards will be given.