SetContentType, Header or ??

Hi, first post so kid gloves please!
OS debian sarge
tomcat 5.0.19
j2sdk1.4.2_04
I have a minor but irritating problem. I have a servlet which produces a CSV file and prompts to save, and it works OK. The problem is that an unwanted blank browser window is spawned at the same time. The html page in the browser does not create the new window via JS etc.
I guess the method I have used is responsible, and any pointers to my errors would be appreciated. The bit of code below has all relevent stuff on it, further population of the file being done with out.println
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
     // get the data sent along with request.
     CustCode = request.getParameter("custCode");
     UserAuthority = request.getParameter("authCode");
     SessionCode = request.getParameter("sessionCode");
     Selection = request.getParameter("selection");
     //send back.
     //response.setContentType("application/x-download");
     response.setContentType("octet-stream");
     response.setHeader("Content-disposition","attachment; filename=Example.CSV");
     PrintWriter out = response.getWriter();
     // send headers
out.println("Serial,Reading,Date");
     // open db and send data from there
     openJDBC(out);

response.setContentType("octet-stream");First things first, your MIME type is incorrectly specified.
response.setContentType("application/octet-stream"); // media type for a generic resource
//response.setContentType("application/csv");  //this also works

Similar Messages

  • Problem setting Unicode (utf-8) in http header using tomcat

    Hi:
    I am trying to set a file name in utf-8 to http header using the following code:
    response.setContentType("text/html; charset=utf-8");
    response.setHeader("Content-disposition", "attachment; filename=解決.zip");
    // I actually has file name in utf-8 here to set to the header, and I know that the name is correctly
    // and I also looked into the response object MimeHeaders object and saw the head is correctly there
    then write the content of zip file using ServletOutputStream.
    The problem I have is that the file name is not displayed correctly when prompted to save or open in the pop up window next. I found out using Fiddler that the request header is wrong:
    Content-disposition: attachment; filename=�zn��.zip
    I am using Tomcat 5.0.28. Any idea how to get this working?
    Thanks in advance!

    You are setting the charset for the content to be UTF-8. (That is why the method is called setContentType.) But HTTP headers are not part of the content and so that has no effect on the header.
    The original specification for HTTP only allowed US-ASCII characters in headers. It is possible that more recent versions have features that allow for non-ASCII header data, but I don't know if that is the case or how you would use those features if they exist.

  • Problem with non-ASCII file name in content disposition header

    Hi All,
    I am facing some problems with the non-ASCII file name incase of content-disposition header. I read from the RFC 2183 that if the file name contains non-ASCII characters then the same should be encoded before sending to browser. I did the same but realized 2 problems:
    1. The name of the file is truncated in case the file name is slightly long for e.g. �����������j�b�g��������������������������.txt
    2. Also when the same file is opened in notepad, the title is showing encoded name %E6%9C%80%E4%B8%8A%E4%BD%8D.....
    Overall, I feel that the browser is not understanding or responding to the encoded header values.
    Is there any solution to this problem? I am using Microsoft IE 6.0.
    The code snippet is given below:
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              String fileName = "�����������j�b�g��������������������������.txt";          
              fileName = URLEncoder.encode(fileName, "UTF-8");
              resp.setCharacterEncoding("UTF-8");
              resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
              resp.setContentType("application/download-binary");
              String s = "This is inside txt file";
              resp.getOutputStream().write(s.getBytes("UTF-8"));
              return;
         }Any help or pointer would be highly appreciated.
    Thanks and Regards,
    Ashish

    The MIME standards for non-ASCII filenames are not widely implemented.
    Many mailers use an ad hoc method for encoding filenames. JavaMail
    supports both methods, but you need to set properties, such as the
    mail.mime.encodefilename property. See the JavaMail javadocs for
    the javax.mail.internet package.

  • How to print between head-Tags of a Portal component

    Hello,
    is it possible to print between the -Tags of the generated HTML-Code? I need to insert a JAVAScript between the tags.
    Currently i am simply using the Writer-Object in the doContent() to print out the HTML-Code. But i found nothing how to access the head?
    With best regards
    Edited by: Björn Karpenstein on Aug 19, 2008 9:12 AM

    Hi,
    One way of doing this is by creating a new Servlet Responce in doContent method. This way you can set the head tag by yourself.
    Here is the code:
    // get the reference to the ServletResponse (exclusivly) and set the content type to HTML                         
    ServletResponse sResponse = portalComponentRequest.getServletResponse(true);                                                    
    sResponse.setContentType("text/html");                                                                           
    // get the reference to the PrintWriter                                                                         
      PrintWriter writer = sResponse.getWriter();                                                                               
    // write the HTML header                                                                               
    writer.write("<html><head></head><body>\n");
    Check if this suites your requirement, if not let me know.
    Regards,
    Praveen Gudapati

  • SetContentType for text files

    Hi all
    I am trying to implement attachement viewing with servlets. Following is what I am doing in order to set the application type which will open the file.
    I can open all types of files except text. setcontenttype("text/html") should take care of text files. but I just get a blank page when I try to open the text file. no errors either.
    what could be the problem?
    following is the relevant code:
    if (fileName.indexOf("xls") > -1)
    res.setContentType( "application/vnd.ms-excel" ); // MIME type for xls document
    }else if (fileName.indexOf("pdf") > -1)
    res.setContentType( "application/pdf" ); // MIME type for Adobe pdf document
    }else if (fileName.indexOf("doc") > -1)
    res.setContentType( "application/msword" ); // MIME type for MSWord document
    }else if (fileName.indexOf("ppt") > -1)
    res.setContentType( "application/powerpoint" ); // MIME type for powerpoint document
    else
    res.setContentType("text/html");

    also if i view source in the blank page, i can see the following:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML><HEAD>
    <META http-equiv=Content-Type content="text/html; charset=windows-1252"></HEAD>
    <BODY></BODY></HTML>
    not sure where this comes from? but content=text/html is correct since i am setting it.
    any hints?

  • Http header setting in servlet

    Hello,
    I want to set the header parameters of http response in my servlet.
    I set parameters as below:
              theResponse.setHeader("Request Version", "HTTP/1.1");
              theResponse.setStatus(200);
              theResponse.setHeader("Date", "Wed, 18 Apr 2007 09:24:04 GMT");
              theResponse.setHeader("Server", "Tomcat");
              theResponse.addCookie(theRequest.getCookies()[0]);
              theResponse.setHeader("pragma", "no-cache"); // HTTP 1.0
              theResponse.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
              theResponse.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // a past date
              theResponse.setDateHeader("Last-Modified", (new java.util.Date()).getTime());
              theResponse.setHeader("Connection", "close");
              theResponse.setContentType("text/plain");
    //some other things...
              PrintWriter aPrintWriter = theResponse.getWriter();
              aPrintWriter.write("this is the string to be put into the body part of the http packet.");
    However, I am checking what I am sending as response using the ethereal network sniffing tool and seeing the result below:
    HTTP/1.1 200 OK\r\n
    Request Version: HTTP/1.1
    Response Code: 200
    Server: Apache-Coyote/1.1\r\n
    Content-Length: 68\r\n
    Date: Tue, 24 Apr 2007 17:55:10 GMT\r\n
    \r\n
    Data (68 bytes)
    I am setting header parameters as it should be.. But it doesn't care about my parameters and Tomcat puts some values that it selects..
    Where is my fault? Can anyone recommend sth please..? I am really stucked here..
    Thanks & Regards

    Hello,
    It looks like your question is really related to Tomcat (coyote). However if you want to control the server name on OC4J you can do it, see this blog entry:
    - OC4J tip: changing the server information
    Regards
    Tugdual Grall

  • Passing header to another servlet

    Hi guys,
    I'm trying to pass an 'Authorization' header from a servlet to another.
    I do something like this:
    String str = "root:12345678";
    String encodedStr = new String(Base64.encodeBase64(str.getBytes()));
    response.setContentType("text/html");
    response.setHeader("Authorization", "Basic " + encodedStr);
    response.sendRedirect("http://localhost:8080/Persister/servlet/DestinationServlet");
    In the doGet of the destination servlet i print the headers of the request but my 'Authorization' header is disappeared.
    Anyone can help me???
    Thanks,
    Massimo

    i think the answer lies in the question...
    Hi guys,
    I'm trying to pass an 'Authorization' header from a
    servlet to another.
    I do something like this:
    String str = "root:12345678";
    String encodedStr = new
    String(Base64.encodeBase64(str.getBytes()));
    response.setContentType("text/html");
    response.setHeader("Authorization", "Basic " +
    encodedStr);
    esponse.sendRedirect("http://localhost:8080/Persister/
    servlet/DestinationServlet");
    i think in destination servlet the header data is not submitted . i dont think you are able to get any data in the destination servlet as u are not sending anything to it. correct me if i am wrong
    In the doGet of the destination servlet i print the
    headers of the request but my 'Authorization' header
    is disappeared.
    Anyone can help me???
    Thanks,
    Massimo

  • Date Header from JSP

    Has anyone managed to set the date header in a JSP file?
    I'm generating an XML file - response.setContentType("text/xml");
    and I want IE7 to be able to cache the file but the Date Header seems to get filled in on my behalf at the end of the page even though I have :
    response.addHeader("Date", "Tue, 12 Feb 2008 10:00:00 GMT");
    I've tried setHeader and the addDateHeader/setDateHeader alternatives.
    I've set the cache-control but I can see using Fiddler that the Date Header of the reply is just set to the current date/time which forces IE7 to do a full load.
    Thanks.

    Have you also tried: response.setHeader("Cache-Control", "post-check=####"); with #### = some number?
    Microsoft calls this "lazy update" see http://support.microsoft.com/kb/843526/en-us:
    A Post-check directive is a cache-control directive that is included with the HTTP Expires header. Web sites use the HTTP Expires header to control how Internet Explorer caches content on the Web site. Post-check defines a time interval (in seconds) that defines after which an object must be checked for "freshness". This check allows Internet Explorer to display the content from its cache or in the Temporary Internet Files folder, and then update the cached copy of the content in the background. This update is also known as a lazy update.
    But they don't really document this well. Do you get the same result using other browsers?
    Finally I'd recommend that you ask this question at the http://forum.java.sun.com/index.jspa forums. The forum you have posted to here is specific to the Sun Java Studio Enterprise IDE developer tool, and since your question is not tool specific, you will receive very few responses to your post here.
    Regards,
    -Brad Mayer

  • Problem with StreamCorruptedException: invalid stream header: 3C68746D

    Hi
    I am attempting to code a project in Java which involves the user of object serialization to send a String via serialization from an applet embedded in a JSP tp a servlet all files are running on the same machine for testing purposes.
    However I seem to be getting StreamCorruptedException: invalid stream header: 3C68746D whenever I attempt to read the inputstream once I have written to it.
    My code is as follows below (I apologise for the lack of details I have attempted to comment and simplify my code as much as possible for improved readability)
    ////////////////////////APPLET CODE////////////////
    import java.io.*;
    import java.io.Serializable;
    import javax.servlet.http.*;
    import java.applet.*;
    import javax.swing.*;
    import java.net.*;
    *Compiled using netbeans 5.1
    *Uses Apache server embedded with netbeans
    *JSP address http://localhost:8084/TestServ
    *Applet is embedded within this page
    *Servlet address http://localhost:8084/TestServ/TServ
    public class Main extends javax.swing.JApplet {
    JFrame jf;//frame for the test applet
    JTextArea jt;//result text box
    public Main() {
    jt=new JTextArea();//set up applet
    this.add(jt);
    URL servletURL;
    HttpURLConnection servletConnection;
    InputStream iStream=null;
    try
    {   //this address as far as is known is correct
    servletURL = new URL( "http://localhost:8084/TestServ/TServ" );
    //open connection to servlet
    servletConnection = (HttpURLConnection)servletURL.openConnection();
    //set up connection
    servletConnection.setDoInput(true);
    servletConnection.setDoOutput(true);
    servletConnection.setUseCaches(false);
    servletConnection.setDefaultUseCaches(false);
    //have tried "GET" and "POST" and "PUT"(PUT not directly compatible with apache servers)
    servletConnection.setRequestMethod("POST");
    servletConnection.setRequestProperty("Content-type","application/octet-stream");
    /*Have also tried application/x-java-serialized-object*/
    //set object output stream
    ObjectOutputStream outStream =
    new ObjectOutputStream(servletConnection.getOutputStream());
    //write a string for test purposes (As far as I am aware String implements Serializable)
    outStream.writeObject("h");
    //flush and close connection
    //have tried a combination of flush and/or close
    outStream.flush();
    outStream.close();
    //get input stream rdy for objectinput stream
    iStream = servletConnection.getInputStream();
    catch(IOException e)
    jt.setText("Error in output "+e);
    ObjectInputStream oInStream=null;
    String str = iStream.toString();
    //iStream at this point equals ""sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@6754d6
    try
    //this is where the error occurs
    //upon even trying to create a objectinputstream using iStream IOException occurs
    oInStream = new ObjectInputStream(iStream);
    //program does not get any further
    oInStream.close();
    catch(IOException e)
    //this error has been driving me crazy :(
    jt.setText("Error in input "+e);
    Servlet code is below however it does not even reach this point
    (If reading input stream is removed from the applet the servlet provides the same error message)
    /////////////////////Servlet code (however does not reach this point)///////////////
    import java.io.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class TServ extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    ObjectInputStream inputFromApplet = null;
    InputStream in = request.getInputStream();
    BufferedReader inTest = null;
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet TServ</title>");
    out.println("</head>");
    out.println("<body>");
    try
    inputFromApplet = new ObjectInputStream(in);
    out.println("<h2>Sucess </h1>");
    catch(EOFException e)
    out.println("<h3>ERROR: " e " Error</h3>");
    out.println("<h3>End Servlet</h3>");
    out.println("</body>");
    out.println("</html>");
    out.close();
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    public String getServletInfo() {
    return "Short description";
    Thank you for your time I have searched for an answer for some time now and how found people in similar situations however no solution has been found
    Any help is appreciated
    Az

    The servlet isn't writing any objects back in reply. It is writing text. Not the same thing. If you want to read using an ObjectInputStream you have to write using an ObjectOutputStream.

  • SetContentType and charset

    Is there any possible way to set the Content-Type header of a servlet response so that it does not append the "charset=ISO-8859-1" on the end of the header value?
    I would simply like to send a response that contains the header:
    Content-Type: application/pdf
    However, using setContentType("application/pdf"), creates a header that looks like this:
    Content-Type: application/pdf;charset=ISO-8859-1
    I NEED to chop off that charset value completely. Is there any way of doing this?
    All help will be greatly appreciated.

    The following servlet:
    import java.io.IOException;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class OTest extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            ServletOutputStream sos = response.getOutputStream();
            sos.print("Test-Header: testing\n\n");
            sos.print("Here is the first line of the HTTP response.\n");
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
    }... produces the following server response:
    HTTP/1.1 200 OK
    Content-Length: 67
    Date: Thu, 22 Jan 2004 12:54:16 GMT
    Server: Apache-Coyote/1.1
    Test-Header: testing
    Here is the first line of the HTTP response.It appears that calling getOutputStream() flushes a default set of headers. Is there any way to intercept this output from the server and manually write header information? If not, is there a way, at least, to address the Content-Type problem I mentioned in my first post?
    I am at a loss for direction on this problem. Any/all help is greatly appreciated.

  • SetContentType and SJAS

    Hi,
    I'm trying to set the MIME type with response.setContentType().
    However it turns out that the type is determined by SJAS's 'Forced Response Type' (Response type to be used if no available MIME mapping matches the extension) on the Configuration / HTTP Service / HTTP Protocol page.
    How can I change this?
    I'm using Sun Java System Application Server Platform Edition 9.0_01 (build b14)

    The following servlet:
    import java.io.IOException;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class OTest extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            ServletOutputStream sos = response.getOutputStream();
            sos.print("Test-Header: testing\n\n");
            sos.print("Here is the first line of the HTTP response.\n");
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
    }... produces the following server response:
    HTTP/1.1 200 OK
    Content-Length: 67
    Date: Thu, 22 Jan 2004 12:54:16 GMT
    Server: Apache-Coyote/1.1
    Test-Header: testing
    Here is the first line of the HTTP response.It appears that calling getOutputStream() flushes a default set of headers. Is there any way to intercept this output from the server and manually write header information? If not, is there a way, at least, to address the Content-Type problem I mentioned in my first post?
    I am at a loss for direction on this problem. Any/all help is greatly appreciated.

  • Cost of free goods in header

    dear all
    i have configured free goods,in the order the cost is coming for free goods at item level and it is not adding  to the header cost total.
    for eg:i have 2 items and 1 free item.costs r 300,400,500 respectively.
    in the header it is showing only 700 as cost.
    i observed the inventory doc is posting correctly with 1200(which includes free goods cost). 
    can anybody tell weather it should add up or not and how it can be done??
    thanks
    reddy

    Dear Yugandhar
    Check
    SPRO->Sales and Distribution->Basic Functions->Free Goods->Control Free Goods Pricing->
    Control Pricing For Free Goods Item Category you will find statistical value
    or in VOV7 below pricing you find statistical value
    Statistical values                                                                               
    Indicates whether the system takes the value of an item into account 
        when it determines the total value of a document.                    
    There are three options                                                              
          System will copy item to header totals                  
    X     No cumulation - Values cannot be used statistically     
    Y     No cumulation - Values can be used statistically                                                         
    Check if it is initial for your item category
    Standard for TANN is initial and pricing is B     Pricing for free goods (100% discount)             
    Do give your feedback
    Regards
    Jitesh

  • Resetting Header and Footer in RTF templates

    Hi,
    I developed an RTF template (template 1). This template contains start:body and end body for printing the header and footer in all pages. After printing this template then i have to call another template(template 2) from this. I called the template (template 2) using call statement. But the probelm is that the header and footer of template1 is printed in the output of template2 .
    I dont want to print this header and footer for template 2. Can anyone please suggest me in doing this. I placed start:body and end body in the second template with the assumption that 1st template's header and footer will be overwritten. But if i preview then am getting the error
    Font Dir: C:\Program Files\Oracle\XML Publisher Desktop\Template Builder for Word\fonts
    Run XDO Start
    RTFProcessor setLocale: en-us
    FOProcessor setData: C:\Documents and Settings\kpoda\Desktop\Invoice Printing Efficiencies\Sample XML Data\Sample Output4.xml
    FOProcessor setLocale: en-us
    each
    Please sugget.
    Thanks

    Hi,
    Do you have two templates (template1 & template2) that you want to display in the same document where the pages for template1 has one set of header and footers; and template2 has another set of header and footer?
    If that is the case you can simply create a new section in your rtf template so you have section1 and section2.
    In the body of section1 you call template1 and template2 in the body of section2.
    You can then have different header and footers for the two templates in the same document.
    BR Kenneth

  • Header information not getting displayed in the lines

    Hello Everyone
    I have a very basic question - its very simple but not working for me with so many attempts
    My XML structure looks like this . In the RTF , I have header information and then a table for line information looping through G_LINES.
    IN this lines table I need the SHIP_CUSTOMER_ID of the header to be displayed. I have tried all options like <?../SHIP_CUSTOMER_ID?> or <?../G_ORDERS/SHIP_CUSTOMER_ID?> , however nothing seems to be working and I am not getting the field to be displayed. Can someone please help?
    XML structure is as follows:
    <XXSTOL_29251_PICK_TKT>
    <LIST_G_ORDERS>
    <G_ORDERS>
    <CUSTOMER_NUMBER>1411</CUSTOMER_NUMBER>
    <SHIPPING_INSTRUCTIONS1></SHIPPING_INSTRUCTIONS1>
    <SHIP_CUSTOMER_ID>256</SHIP_CUSTOMER_ID>
    <G_LINES>
    </G_LINES>
    <G_LINES>
    </G_LINES>
    </G_ORDERS
    </LIST_G_ORDERS>
    </XXSTOL_29251_PICK_TKT>

    Are you grouping within G_LINES? If so, use ../../SHIP_CUSTOMER_ID
    or send me the xml and RTF template to [email protected] so that I can get a better look at the data structure and try to help.
    Thanks,
    Bipuser

  • Header not getting  displayed in the next page in the second table

    Dear Experts ,
    I have a query regarding Header not getting  displayed in the next page in the second table of the main window. .Let me elobrate the issue.
    I have a smartform in which there are  2 tables TABLE 1 and TABLE 2 in the smartform MAIN window. TABLE 1 is for pending PO and TABLE 2 is  for future delivery date P O separated by text in between.
    Now the header for both the tables and the data are getting displayed properly if the total output is in only one page. But If there are more entries in the TABLE 1 the Header for the TABLE 2 is not getting displayed. Header for TABLE 1 yet gets displayed properly in the next page in case of more entries.
    Only issue is that Header for TABLE 2 is not getting displayed in second page but it gets displayed if the entries are less in TABLE 1 and the total output is in one page .
    Please provide a elobrate solution on this problem as the requirement is urgent.
    Thanks,
    Regards,
    Sachin Hada

    Hi Sachin,
    you need to cteate two pages FIRST and NEXT.
    in first page --> FIRST
        next       --> NEXT
    in next page
      page---> NEXT
      next ---> NEXT.
    you copy the first page main window is the same in next page
    aslo
    I think help ful for you
    thanks & Regards
    BHUPAL.

Maybe you are looking for

  • Flex 3.5 Rich Text Editor Bold Button is Selected by default?

    Hi and thanks in advance, I'm creating dynamic forms via action script in flex builder with SDK 3.5. One part of this form is a rich text editor, it creates and works just fine, but I have one little annoying issue the bold button is defaulted to on

  • Apple TV using Airplay

    When using Airplay with Apple TV to watch a movie saved on an iPad, does this use data from your data limit with your internet provider?

  • CS4 - Lion crashes when asked to print

    Hi I really would like to get my CS4 ind working in Lion. I can open a file and work on it and all is well,  As soon as I go into any of the print options (Print, Print Booklet ect) it crashes. 1. I have Trashed my preferences etc by keyboard method 

  • What is the fastest way to delete photos on the iphone?

    Is there a way to delete old photos that have been taken on my phone any other way than one picture at a time??  I am wanting to free up some memory......

  • Sub contract cost against sales T.codes & path

    Hi, Please find out the T.code and path for subcontract cost against sales.Very urgent. Regards R.Manigandan