Problem writing to output using servlet

Hi All,
I created a servlet which reads file and writes to output . This works fine
when request protocol is http . But if protocol is changed to https servlet doesnt write to output. This servlet is deployed in secure environment as EAR project .But pops up error in popup
Internet explorer cannot download /ImageServlet/.... from the server....
requested site is unavailable.
Here is my servlet code
                    String key = request.getParameter("key");
                    if( key != null){
                         String[] keys = key.split(":");
                         System.out.println("request.getAuthType() :"+ request.getAuthType());
                         if(request.getAuthType() != null){
                         if(keys != null && keys.length >1){
                              ImageUtil imageUtil = new ImageUtil();
                              byte[] bytes = imageUtil.getDocumentContent(keys[0]);
                              ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                              BufferedInputStream bis = new BufferedInputStream(bais);
                              ServletOutputStream out = response.getOutputStream();
                              BufferedOutputStream bos = new BufferedOutputStream(out);
                              response.reset();
                              if(keys[1].equalsIgnoreCase("doc") ) {
                                   response.setContentType("application/msword;charset=utf-8");
                                   response.setHeader("Content-Disposition","inline;filename=\"file.doc\";");
                              }else if(keys[1].equalsIgnoreCase("xls") ) {
                                   response.setContentType("application/vnd.ms-excel");
                                   response.setHeader("Content-Disposition","inline;filename=\"file.xls\";");
                              }else if(keys[1].equalsIgnoreCase("rtf") ){
                                   response.setContentType("application/msword");
                                   response.setHeader("Content-Disposition","inline;filename=\"file.rtf\";");                         
                              }else if(keys[1].equalsIgnoreCase("html") || keys[1].equalsIgnoreCase("htm")){
                                   response.setContentType("text/html");
                                   response.setHeader("Content-Disposition","inline;filename=\"file.html\";");                         
                              }else if(keys[1].equalsIgnoreCase("txt")){
                                   response.setContentType("text/plain");
                                   response.setHeader("Content-Disposition","inline;filename=\"file.txt\";");                         
                              //setting some response headers
                              response.setHeader("Cache-Control","no-store, no-cache, must-revalidate,post-check=0, pre-check=0"); //HTTP 1.1
                              response.setHeader("Pragma","no-cache"); //HTTP 1.0
                              response.setDateHeader ("Expires", 0);
                         int i;
                         while ( (i = bis.read(bytes)) > 0)
                              bos.write(bytes,0,i);
                         bos.flush();               
                         bos.close();
                         bis.close();
                         bais.close();
                         System.out.println("Has written");
                         }else{
                              log.error("Key is not good.");
               }else{
                    log.error("Please enter key for streaming.");
          }catch(Exception e)     {
log.error(e.toString());
e.printStackTrace();
In web.xml
     <servlet>
          <servlet-name>ImageServlet</servlet-name>
          <servlet-class>
               com.pfpc.opdesktop.image.servlet.ImageServlet
          </servlet-class>
     </servlet>     
     <servlet-mapping>
     <servlet-name>ImageServlet</servlet-name>
     <url-pattern>/ImageServlet/*</url-pattern>
     </servlet-mapping>
     <security-constraint>
          <display-name>ImageServlet</display-name>
          <web-resource-collection>
               <web-resource-name>ImageServlet</web-resource-name>
               <description>ImageServlet</description>
               <url-pattern>/ImageServlet/*</url-pattern>
               <http-method>GET</http-method>
               <http-method>POST</http-method>
               <http-method>OPTIONS</http-method>
          </web-resource-collection>
          <auth-constraint>
               <description>ImageServlet</description>
               <role-name>ImageServlet</role-name>
          </auth-constraint>
          <user-data-constraint>
               <transport-guarantee>NONE</transport-guarantee>
          </user-data-constraint>
     </security-constraint>
          <security-role>
          <description>ImageServlet - OpDesktopWAR</description>
          <role-name>ImageServlet</role-name>
     </security-role>
In application.xml
     <security-role id="SecurityRole_1164052833984">
          <description>ImageServlet - OpDesktopWAR</description>
          <role-name>ImageServlet</role-name>
     </security-role>
Can anyone please tell me what is problem.very urgent.
Thankyou

Hi,
Found the solution for the problem. For some reason
response.setHeader("Cache-Control","no-store, no-cache, must-revalidate,post-check=0, pre-check=0"); //HTTP 1.1
                              response.setHeader("Pragma","no-cache"); //HTTP 1.0
                              response.setDateHeader ("Expires", 0);
These header settings were causing this issue. If I take out these settings then it works
FYI
Thankyou very much for all help

Similar Messages

  • Problem in downloading file using servlet

    Hello,
    I wnat to send a file throung servlet to my desktop program. when i call this servlet through internet explore it is working fine but when i call this in my desktop program then desktop program get nothing. my desktop program does not get anything. please help me. here is my both code servlet and desktop program.
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
              response.setContentType("text/html");
         //     PrintWriter out = response.getWriter();
              File filename = new File("");
    //          Set the headers.
              response.setContentType("application/x-download");
              response.setHeader("Content-Disposition", "attachment; filename=" + filename);
    //          Send the file.
              OutputStream out = res.getOutputStream( );
              returnFile(filename, out); // Shown earlier in the chapter
              String filePath = getServletContext().getRealPath("/");
              response.setContentType("application/x-download");
              response.setHeader("Content-Disposition", "attachment; filename="+"amit.doc");
         //     File tosave = new File(getServletContext().getRealPath("), cfile.getName());" +
              try{
              File uFile= new File(filePath);
              int fSize=(int)uFile.length();
              FileInputStream fis = new FileInputStream(uFile);
              PrintWriter pw = response.getWriter();
              int c=-1;
    //          Loop to read and write bytes.
    //          pw.print("Test");
              while ((c = fis.read()) != -1){
              pw.print((char)c);
    //          Close output and input resources.
              fis.close();
              pw.flush();
              pw=null;
              }catch(Exception e){
    public class AdDesktopClient {
         * @param args
         public static void main(String[] args) {
              try{ 
              URL url = new URL("http://localhost:8080/WebRoot1/servlet/Download");
              //URLEncoder.encode(xmlString);
              URLConnection connection = url.openConnection();
              HttpURLConnection con = (HttpURLConnection)connection;
              con.setDoInput(true);
              con.setDoOutput(true);
              con.setUseCaches(true);
              con.setRequestMethod("GET");
              // PrintWriter out = new PrintWriter(con.getOutputStream());
              BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
              String inputLine;
              int len = con.getContentLength();
              InputStream inn = con.getInputStream();
              byte[] buf = new byte[128];
              int c =0;
              System.out.print("len :"+len);
              System.out.print(inn.read());
              while( (c = inn.read())!= -1){
                   System.out.print(c);
    /*          while ((inputLine = in.readLine()) != null)
              System.out.println(inputLine);
              in.close();
              }catch(Exception e){
                   e.printStackTrace();
    Plaease help me to solve this problem. i want to send a file throuhg a servlet to my desktop program.
    Thanks in advance
    Ravi

    Give this a try:
    File strFile = new File(strFileName);
    long length = strFile.length();
    response.setContentType("application/octet-stream");
    response.setContentLength((int)length);
    response.setHeader("Content-Disposition", ("attachment; filename=" + strFileName));
    OutputStream out = response.getOutputStream();
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(strFile));
    int i = -1;
    while((i = in.read()) != -1) out.write(i);
    in.close();
    Kris

  • Problems with Flash output using Safari

    Hi All,
    does anyone know the solution to getting the flash output to work with safari?  The project plays properly on Firefox and Chrome.  On safari, my custom menus come up just the same as on the DVD version of the project, but the flash videos do not play - just a grey screen.  Interestingly, the duration of the clips is set correctly in the player, it just doesn't start the video. The flash files play correctly when loaded directly into Adobe flash player, so I am assuming there is a compatibility issue with the generated XML files or index.html.  The code inside the index.html seems very old and refereences macromedia.com and a windows .CAB file.  I have shortened the file names and eliminated any offending characters (all are in the form "Chapter_1").
    Anyway, this is stopping me delivering a project on USB stick for a client - seems to be a common issue when searching the web, but no solutions.  Any assistance or ideas would be greatly appreciated.
    I have the full CC (2014), but still have Encore CS6 installed for DVD production.
    Regards,
    Mark

    I read the thread you mentioned and all others relating to this issue - seems to be a number of people having the same issue over the last 3 years, but none have posted a successful conclusion.  I did see the post about strange characters in file names causing issues in the XML - I did also look at this and change all my content file names to innocuous "Chapter_X" & etc.  The paths to the "Sources" directory are all relative and the project works correctly on Chrome and Firefox.  Just safari is not working.  Agree, it could be permissions, but I have checked all security settings and the Abobe Flash player (with is called up by the script to display the videos in the browser) is specifically permitted to "Allow Always" in the security settings.  I can't help thinking there is a problem with the generated XML that safari is not behaving correctly - it wouldnt be the first time that Apple doest things using their interpretation of a standard. 
    However, after all that, the generated code from Encore doesn't result in a working local project that I can send to a client and expect to work.

  • Problems generating WebHelp output using RoboHelp X5

    Hello,
    I have been using RoboHelp X5, build 606 since last 2 weeks. I am facing problems with the generation of WebHelp output, when I generate and publish the project, it does not give me the Index and TOC. I have taken over the project from another author and when I compare the new Published Help folder with the previous author's work, I see some missing files. Could anyone from the group please help me resolve this issue?
    Thanks!

    Two possibilities from that information.
    1] Is the D drive a partition on your hard disk or a network drive? RoboHelp projects must be run from your hard disk.
    2] The more likely is that RH is not properly installed. When the previous author left, was RH uninstalled and reinstalled using your login? For X5 it must be installed using your login? Also you need local admin rights both to install and use it.
    My guess is this is all to do with X5 not having been installed with your login and with you having local admin rights.
    This will lead to another problem. X5 can no longer be activated. The solution to that is on my site. See Snippet 100.
    See www.grainge.org for RoboHelp and Authoring tips
    Follow me @petergrainge

  • Problem-Writing datas to a Servlet thro' URLConnection class

    Hi,
    Iam trying to post some string data to a servlet.
    The servlet reads 2 parameters from url.And reads the xml string message thro post method.
    So in the client program, I added those parameters to the URL directly like this,
    "http://localhost/servlet/test?action1=value1&action2=value2" ,and created url object .
    And using URLConnection iam trying to post the xml string.
    But the servlet does not read the parameter values.Is my approach is correct?
    client code:
    package test;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Testxml{
    public static void main(String ars[])
    String XML="<?xml version='1.0'?><Test><msg>test message</msg></Test>";
    String server="http://localhost/servlet/test";
    String encodeString = URLEncoder.encode("action1") + "=" + URLEncoder.encode("something1")+"&"+URLEncoder.encode("action2") + "=" + URLEncoder.encode("something2");
    try{
         URL u = new URL(server+"?"+encodeString);
         URLConnection uc = u.openConnection();
         uc.setDoOutput(true);
         uc.setUseCaches(false);
         uc.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
         OutputStream out = uc.getOutputStream();
         PrintWriter wout = new PrintWriter(out);
         wout.write(alertXML);
         wout.flush();
         wout.close();
         System.out.println("finished");
         catch(Exception e) {
         System.out.println(e);
    Servlet code:
    package test;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class test extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
         performTask(req, res);
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
         performTask(req, res);
    public void performTask(HttpServletRequest request, HttpServletResponse response) {
         try{
    String action1=request.getParameter("action1");
    String action2=request.getParameter("action2");
    if(action1.equals("something1") && action1.equals("something2") )
         ServletInputStream in = request.getInputStream();
         byte[] buffer = new byte[1024];
         String xmlMsg = "";
         int len = in.read(buffer,0,buffer.length);
         if(len>0)
         while (len > 0 ){
                   xmlMsg += new String(buffer,0,len);
                   len = in.read(buffer);
         System.out.println("xml : "+xmlMsg);
    This is not working.Even,it does not invoke servlet.Is this approach is correct?.
    Thanx,
    Rahul.

    Hi,
    Did you get the answer to your problem? I am facing the same problem, so if you have the solution, please share the same.
    TIA
    Anup

  • Problem writing xml file using DOM

    Hi,
    I am trying to write a xml file using DOM. I am using xalan 2.5, xerces 1.4.4, jdk 1.3.1 in JRun 3 on windows.
    The code where I get exception :
                   TransformerFactory tFactory = TransformerFactory.newInstance();
                   Transformer transformer = tFactory.newTransformer();
                   transformer.transform(new DOMSource(doc), new StreamResult("pr.xml"));
    I get the runtime error as follows:
    javax.servlet.ServletException: null
    java.lang.NoSuchMethodError
         at org.apache.xml.utils.DOM2Helper.getNamespaceOfNodeDOM2Helper.java:342)
         at org.apache.xml.utils.TreeWalker.startNode(TreeWalker.java:387)
         at org.apache.xml.utils.TreeWalker.traverse(TreeWalker.java:202)
         at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:343)
    Thinking it is because of classpath, I placed xalan 2.5, xerces 1.4.4 jar files in jrun admin lib directory and in server lib directory as well. Still getting the same error.
    Any suggestion?
    Thanks in advance

    xalan is included in JRun 4. However JRun 3 does not.
    However I tried with the same code in JRun3 in different system. The error is completely different. I understand this is because of different version of files. trying to solve ;)
    Here my new exception
    javax.servlet.ServletException: org/w3c/dom/ranges/DocumentRange
    java.lang.NoClassDefFoundError: org/w3c/dom/ranges/DocumentRange
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:493)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:111)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:248)
         at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:493)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:111)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:248)
         at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
         at org.apache.xerces.jaxp.DocumentBuilderImpl.(Unknown Source)
         at org.apache.xerces.jaxp.DocumentBuilderFactoryImpl.newDocumentBuilder(Unknown Source)
         at com.cybell.appl.deliveryorder.cmd.CreateXMLDOFile.createFile(CreateXMLDOFile.java:73)
         at com.cybell.appl.deliveryorder.cmd.CreateXMLDOFile.execute(CreateXMLDOFile.java:36)
         at com.cybell.appl.framework.cmd.BaseCommand.start(BaseCommand.java:50)
         at com.cybell.appl.framework.control.BaseController.service(BaseController.java:38)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:865)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1013)
         at allaire.jrun.servlet.JRunSE.runServlet(../servlet/JRunSE.java:925)
         at allaire.jrun.servlet.JRunNamedDispatcher.forward(../servlet/JRunNamedDispatcher.java:34)
         at allaire.jrun.servlet.Invoker.service(../servlet/Invoker.java:84)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1013)
         at allaire.jrun.servlet.JRunSE.runServlet(../servlet/JRunSE.java:925)
         at allaire.jrun.servlet.JRunRequestDispatcher.forward(../servlet/JRunRequestDispatcher.java:88)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1131)
         at allaire.jrun.servlet.JvmContext.dispatch(../servlet/JvmContext.java:330)
         at allaire.jrun.http.WebEndpoint.run(../http/WebEndpoint.java:107)
         at allaire.jrun.ThreadPool.run(../ThreadPool.java:272)
         at allaire.jrun.WorkerThread.run(../WorkerThread.java:75)

  • "encoding = UTF-8" missing while writing XML file using file Adapter

    Hi,
    We are facing an unique problem writing xml file using file adapter. The file is coming without the encoding part in the header of xml. An excerpt of the file that is getting generated:
    <?xml version="1.0" ?>
    <customerSet>
    <user>
    <externalID>51017</externalID>
    <userInfo>
    <employeeID>51017</employeeID>
    <employeeType>Contractor</employeeType>
    <userName/>
    <firstName>Gail</firstName>
    <lastName>Mikasa</lastName>
    <email>[email protected]</email>
    <costCenter>8506</costCenter>
    <departmentCode/>
    <departmentName>1200 Corp IT Exec 8506</departmentName>
    <businessUnit>1200</businessUnit>
    <jobTitle>HR Analyst 4</jobTitle>
    <managerID>49541</managerID>
    <division>290</division>
    <companyName>HQ-Milpitas, US</companyName>
    <workphone>
    <number/>
    </workphone>
    <mobilePhone>
    <number/>
    </customerSet>
    </user>
    So if you see the header the "encoding=UTF-8" is missing after "version-1.0".
    Do we need to configure any properties in File Adapter?? Or is it the standard way of rendering by the adapter.
    Please advice.
    Thanks in advance!!!

    System.out.println(nodeList.item(0).getFirstChild().getNodeValue());

  • Problem in displaying Alv grid output  using oops........

    hi,
    i have two problems in displaying ALV grid output Using Oops.
    1) How to modify the fieldcatalog after we getting a field catalog using general FM.
    2) initialy it is displaying 13 fields but there are 63 fields .
       eventhough we chage the layout to 63 fields it is displaying only 13 fields , these 13 fields may be different based on our selection but count  of displayed fileds are same . how can display 63 fields at a time .

    Hi,
    You can chnage using below code:
    loop at gt_fieldcat.
    if <gt_fieldcat-field_name> = 'FIELDNAME'.
    endif.
    modify gt_fieldcat.
    clear gt_fieldcat.
    endloop.
    Make sure that all the field should not have no_out = 'X' and tech = 'X'.
    Thanks,
    Sriram Ponna.

  • Outputting JPEG using servlets

    hi
    Im trying to output the JPEG created by the StockGraphProducer class i found on Javaworld to a webpage using a servlet output stream.
    The original code used a file output stream i have included a snippet of it below. I have also included my servlet where i have tried to amend it to render JPEG to the webpage but im not usre abotu it or what bits i need to change in the StockGraphProducer
    I woudl be very grateful if someone could take a quick look at this .
    thanks
    public class StockGraphProducer implements ImageProducer
      private static int ImageWidth = 300;
      private static int ImageHeight = 300;
      private static int VertInset = 25;
      private static int HorzInset = 25;
      private static int HatchLength = 10;
       *  Request the producer create an image
       *  @param stream stream to write image into
       *  @return image type
    // i want to try and use a servlet output stream to send the JPEG to the user insteadof outputstream.
    public String createImage(Outputstream stream) throws IOException
        plottedPrices = new Point2D.Double[5];
        int prices[] =  {105, 100, 97, 93, 93};
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(stream);
    //do i remove the stream paaremter from createiamge and above function???
        BufferedImage bi = new BufferedImage(ImageWidth + 10,
                                             ImageHeight,
                                             BufferedImage.TYPE_BYTE_INDEXED);
        graphics = bi.createGraphics();
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, bi.getWidth(), bi.getHeight());
        graphics.setColor(Color.red);
        createVerticalAxis();
        createHorizontalAxis();
        graphics.setColor(Color.green);
        plotPrices(prices);
        encoder.encode(bi);
        return "image/jpg";
    public final class GraphRenderer extends HttpServlet
         public void doGet(HttpServletRequest request,
                               HttpServletResponse response)
           throws IOException, ServletException
              HttpSession session = request.getSession(true);
                   response.setContentType("image/jpeg");
              ServletOutputStream sos= response.getOutputStream();
      //the original code
       /* try
           FileOutputStream f = new FileOutputStream("stockgraph.jpg");
           StockGraphProducer producer = new StockGraphProducer();
           producer.createImage(f);
           f.close();
        catch (Exception e)
          e.printStackTrace();
    //i want to try and use a servlet output stream so that the JPEG is sent to the webpage     i tried the following butim not sure about it. I got rid of the outputstream parameter from StockGraphProducer and left it empty and tried .
              try
                   StockGraphProducer producer = new StockGraphProducer();
                          producer.createImage();
                   //i dont think i need this part.      
                   /*Dimension size= producer.getPreferredSize();
                   BufferedImage image = new BufferedImage((int)size.getWidth(),                (int)size.getHeight(), BufferedImage.TYPE_INT_RGB);
                   Graphics g= image.createGraphics();
                   gp.paint(g);*/
                   // Send back image i dont think this is correct
                   JPEGImageEncoder encoder= JPEGCodec.createJPEGEncoder(sos);
                   JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
                   param.setQuality(1.0f, false);
                   encoder.setJPEGEncodeParam(param);
                   encoder.encode(image);
              catch(Exception ex)
              {

    Hi,
    I need to create a program where I get an Image from DB and then display it in Browser using servlets.
    I was looking at the StockGraphProducer, but it seems the code is not fully posted.
    I would greatly appreciate anyone who has this StockGraphProducer program would email me or post it.
    Thanks in advance.
    my email address is [email protected]
    Again Thanks

  • Problem with number-fields in PDF Output Using FOP

    When generating PDF Output using FOP as described in the utilitiy provided in the HTMLDB Studio http://htmldb.oracle.com/pls/otn/f?p=18326:44:12104450162492733947::::P44_ID:1522
    formatted numbers over 1,000 are resolved as characters (because of the comma) and are therefore right justified. This results in alignment issues for numeric columns.
    Does anyone have any ideas on how to work around this.
    Thanks,
    David

    Hello,
    Your probably going to have to edit the xslt to get the result either by stripping out the comma or by setting that column to explicitly align the way you want it.
    Carl

  • Using Servlets in java studio creator

    Hello, anyone can tell me how can i use a servlet in java studio creator, due the file is in .java i dont know how to use it, here is an example i want to add to my proyect:
    and other question is how can i make to work?
    * Sean C. Sullivan
    * June 2003
    * URL: http://www.seansullivan.com/
    package pdfservlet;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.io.ByteArrayOutputStream;
    import java.io.PrintWriter;
    // import the iText packages
    import com.lowagie.text.*;
    import com.lowagie.text.pdf.*;
    * a servlet that will generate a PDF document
    * and send the document to the client via the
    * ServletOutputStream
    * @author Sean C. Sullivan
    public class PDFServlet extends HttpServlet
         public PDFServlet()
              super();
         * we implement doGet so that this servlet will process all
         * HTTP GET requests
         * @param req HTTP request object
         * @param resp HTTP response object
         public void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws javax.servlet.ServletException, java.io.IOException
              DocumentException ex = null;
              ByteArrayOutputStream baosPDF = null;
              try
                   baosPDF = generatePDFDocumentBytes(req, this.getServletContext());
                   StringBuffer sbFilename = new StringBuffer();
                   sbFilename.append("filename_");
                   sbFilename.append(System.currentTimeMillis());
                   sbFilename.append(".pdf");
                   // Note:
                   // It is important to set the HTTP response headers
                   // before writing data to the servlet's OutputStream
                   // Read the HTTP 1.1 specification for full details
                   // about the Cache-Control header
                   resp.setHeader("Cache-Control", "max-age=30");
                   resp.setContentType("application/pdf");
                   // The Content-disposition header is explained
                   // in RFC 2183
                   // http://www.ietf.org/rfc/rfc2183.txt
                   // The Content-disposition value will be in one of
                   // two forms:
                   // 1) inline; filename=foobar.pdf
                   // 2) attachment; filename=foobar.pdf
                   // In this servlet, we use "inline"
                   StringBuffer sbContentDispValue = new StringBuffer();
                   sbContentDispValue.append("inline");
                   sbContentDispValue.append("; filename=");
                   sbContentDispValue.append(sbFilename);
                   resp.setHeader(
                        "Content-disposition",
                        sbContentDispValue.toString());
                   resp.setContentLength(baosPDF.size());
                   ServletOutputStream sos;
                   sos = resp.getOutputStream();
                   baosPDF.writeTo(sos);
                   sos.flush();
              catch (DocumentException dex)
                   resp.setContentType("text/html");
                   PrintWriter writer = resp.getWriter();
                   writer.println(
                             this.getClass().getName()
                             + " caught an exception: "
                             + dex.getClass().getName()
                             + "<br>");
                   writer.println("<pre>");
                   dex.printStackTrace(writer);
                   writer.println("</pre>");
              finally
                   if (baosPDF != null)
                        baosPDF.reset();
         * @param req must be non-null
         * @return a non-null output stream. The output stream contains
         * the bytes for the PDF document
         * @throws DocumentException
         protected ByteArrayOutputStream generatePDFDocumentBytes(
              final HttpServletRequest req,
              final ServletContext ctx)
              throws DocumentException
              Document doc = new Document();
              ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
              PdfWriter docWriter = null;
              try
                   docWriter = PdfWriter.getInstance(doc, baosPDF);
                   doc.addAuthor(this.getClass().getName());
                   doc.addCreationDate();
                   doc.addProducer();
                   doc.addCreator(this.getClass().getName());
                   doc.addTitle("This is a title.");
                   doc.addKeywords("pdf, itext, Java, open source, http");
                   doc.setPageSize(PageSize.LETTER);
                   HeaderFooter footer = new HeaderFooter(
                                       new Phrase("This is a footer."),
                                       false);
                   doc.setFooter(footer);
                   doc.open();
                   doc.add(new Paragraph(
                                  "This document was created by a class named: "
                                  + this.getClass().getName()));
                   doc.add(new Paragraph(
                                  "This document was created on "
                                  + new java.util.Date()));
                   String strServerInfo = ctx.getServerInfo();
                   if (strServerInfo != null)
                        doc.add(new Paragraph(
                                  "Servlet engine: " + strServerInfo));
                   doc.add(new Paragraph(
                                  "This is a multi-page document."));
                   doc.add( makeGeneralRequestDetailsElement(req) );
                   doc.newPage();
                   doc.add( makeHTTPHeaderInfoElement(req) );
                   doc.newPage();
                   doc.add( makeHTTPParameterInfoElement(req) );
              catch (DocumentException dex)
                   baosPDF.reset();
                   throw dex;
              finally
                   if (doc != null)
                        doc.close();
                   if (docWriter != null)
                        docWriter.close();
              if (baosPDF.size() < 1)
                   throw new DocumentException(
                        "document has "
                        + baosPDF.size()
                        + " bytes");          
              return baosPDF;
         * @param req HTTP request object
         * @return an iText Element object
         protected Element makeHTTPHeaderInfoElement(final HttpServletRequest req)
              Map mapHeaders = new java.util.TreeMap();
              Enumeration enumHeaderNames = req.getHeaderNames();
              while (enumHeaderNames.hasMoreElements())
                   String strHeaderName = (String) enumHeaderNames.nextElement();
                   String strHeaderValue = req.getHeader(strHeaderName);
                   if (strHeaderValue == null)
                        strHeaderValue = "";
                   mapHeaders.put(strHeaderName, strHeaderValue);
              Table tab = makeTableFromMap(
                        "HTTP header name",
                        "HTTP header value",
                        mapHeaders);
              return (Element) tab;
         * @param req HTTP request object
         * @return an iText Element object
         protected Element makeGeneralRequestDetailsElement(
                                  final HttpServletRequest req)
              Map mapRequestDetails = new TreeMap();
              mapRequestDetails.put("Scheme", req.getScheme());
              mapRequestDetails.put("HTTP method", req.getMethod());
              mapRequestDetails.put("AuthType", req.getAuthType());
              mapRequestDetails.put("QueryString", req.getQueryString());
              mapRequestDetails.put("ContextPath", req.getContextPath());
              mapRequestDetails.put("Request URI", req.getRequestURI());
              mapRequestDetails.put("Protocol", req.getProtocol());
              mapRequestDetails.put("Remote address", req.getRemoteAddr());
              mapRequestDetails.put("Remote host", req.getRemoteHost());
              mapRequestDetails.put("Server name", req.getServerName());
              mapRequestDetails.put("Server port", "" + req.getServerPort());
              mapRequestDetails.put("Preferred locale", req.getLocale().toString());
              Table tab = null;
              tab = makeTableFromMap(
                                  "Request info",
                                  "Value",
                                  mapRequestDetails);
              return (Element) tab;
         * @param req HTTP request object
         * @return an iText Element object
         protected Element makeHTTPParameterInfoElement(
                             final HttpServletRequest req)
              Map mapParameters = null;
              mapParameters = new java.util.TreeMap(req.getParameterMap());
              Table tab = null;
              tab = makeTableFromMap(
                        "HTTP parameter name",
                        "HTTP parameter value",
                        mapParameters);
              return (Element) tab;
         * @param firstColumnTitle
         * @param secondColumnTitle
         * @param m map containing the data for column 1 and column 2
         * @return an iText Table
         private static Table makeTableFromMap(
                   final String firstColumnTitle,
                   final String secondColumnTitle,
                   final java.util.Map m)
              Table tab = null;
              try
                   tab = new Table(2 /* columns */);
              catch (BadElementException ex)
                   throw new RuntimeException(ex);
              tab.setBorderWidth(1.0f);
              tab.setPadding(5);
              tab.setSpacing(5);
              tab.addCell(new Cell(firstColumnTitle));
              tab.addCell(new Cell(secondColumnTitle));
              tab.endHeaders();
              if (m.keySet().size() == 0)
                   Cell c = new Cell("none");
                   c.setColspan(tab.columns());
                   tab.addCell(c);
              else
                   Iterator iter = m.keySet().iterator();
                   while (iter.hasNext())
                        String strName = (String) iter.next();
                        Object value = m.get(strName);
                        String strValue = null;
                        if (value == null)
                             strValue = "";
                        else if (value instanceof String[])
                             String[] aValues = (String[]) value;
                             strValue = aValues[0];
                        else
                             strValue = value.toString();
                        tab.addCell(new Cell(strName));
                        tab.addCell(new Cell(strValue));
              return tab;
    }

    Hi, i've done all described in the posts, but i
    don't know how to call the servlet, using the web
    browser, and more, how can i call the servlet frrom
    a button action? or hyperlink?
    nks for the helpOk, I am not sure what you are trying to do. For these events you can
    use the SessionBean. What do you want the servlet to do that the session bean can't?
    I use the sessionbean because I don't know how to receive or respond to xmlhttpreq messages directly in my sessionbean. If you just need the standard http req/resp it doesn't seem like a servlet is needed.

  • PageNotFound when using servlets as clients for EJB

    Can anyone help me? I have a container managed EJB. I'm using servlets as my client. I placed my EJB's in a jar file and my servlets and html pages in a WAR file. I deployed them using J2EE's deploytool. I can access my html files but not my servlet files. It always says file not found or a 405 error (resource not allowed) I access my servlet this way...
    http://localhost:8000/ReservationContextRoot/ReservationAlias
    my web.xml file looks like the following:
    <?xml version="1.0" encoding="Cp1252"?>
    <!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN' 'http://java.sun.com/j2ee/dtds/web-app_2.2.dtd'>
    <web-app>
    <display-name>ReservationWAR</display-name>
    <description>no description</description>
    <servlet> <servlet-name>ReservationServlet</servlet-name>
    <display-name>ReservationServlet</display-name>
    <description>no description</description>
    <servlet-class>ReservationServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ReservationServlet</servlet-name>
    <url-pattern>ReservationAlias</url-pattern>
    </servlet-mapping>
    <session-config>
    <session-timeout>30</session-timeout>
    </session-config>
    <resource-ref>
    <description>no description</description>
    <res-ref-name>jdbc/ReservationDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    <ejb-ref> <description>no description</description>
    <ejb-ref-name>ejb/Reservation</ejb-ref-name>
    <ejb-ref-type>Entity</ejb-ref-type>
    <home>ReservationHome</home>
    <remote>Reservation</remote>
    </ejb-ref>
    </web-app>

    Are you sure your servlet class itself can run without problem? Try debug in the these steps:
    1. Change your servlet to simply output some HTML text, so you can be sure tomcat can get to your servlet. If this is OK, it means the servlet itself has problem, probably the EJB stuff.
    2. Make sure the EJB container is running.
    3. Make your servlet a standalone client (not a servlet) and see if it can run. Pay attention to how you do JNDI lookup of the EJB.
    Yi

  • URGENT.........File Upload using Servlets and jsp

    I am a new servlet programmer.......
    iam using tomcat server......
    can any one pls help in writing code for file upload using servlets and jsp without using multipart class or any other class like that....
    Please URGENT..

    Slow down! "Urgent" is from your perspective alone. I, myself, am not troubled or worried in the least.
    hi ugniss
    thanks for ur reply....sorry i was not
    y i was not asked not to use multipart class or any
    other class like that...is there any other
    possibility to do file uploading from jsp to
    servlet...
    Just as an aside, a JSP is a Servlet. But even if I move beyond that, the question does not make sense. If you want a "JSP to upload to a Servlet", then simply do so in memory. You are still (likely) within the same scope of a given request. However, if instead you are referring to a JSP that is displayed on a browser, then really you are talking about HTML, which is what the browser will receive. And since you are now talking about a browser, your only real, viable option is a multi-part file upload. So, it is either server or it is browser. And either way, the question leads to very established options, as outlined above.
    the main concept is.. in the browser the user selects
    a particular file and clicks the button upload..after
    clicking upload the jsp should sent the file to the
    servlet in streams...there the servlet gets in and
    saves in a server location........this is wat i hav
    to do...
    Okay. So, after reading my previous (redundant) paragraph, we have arrived at the crux of the issue. You have a JSP that will be output as HTML to a client (browser) which you want to upload content to your server (handled by a Servlet). So, you are now stuck again with multi-part. The requirement to not use multi-part is non-sensical. You can overcome it, say, if you write your own applet or standalone Swing client. However, if your users are invoking this functionality from a browser, you are limited by the options that W3C has provided you. Use multi-part.
    is there aby possibilty to do this.....can any one
    pls help....Take the advice to download and review Jakarta Commons FileUpload. Inform your management that their requirement makes no technical sense. Research on your own. There are dozens of examples (and tutorials) on file upload using multi-part. Embrace it. Live it. Love it.
    - Saish

  • Open Jasper Report in new page using servlet

    Guys,
    Looks very simple but i am having problem making this process work. I am using 11.1.1.4
    This is my use case:
    - From a employee page, user clicks on a menu item to open report for current employee. I need to pass appropriate report parameters to servlet and open report into new page.
    I can successfully call servlet using commandmenuitem and set request parameters and call servlet from backing bean.... but that doesn't open report in a new page.... any way i can do this?
    Another option i tried was that using gomenuitem and setting target=blank but in that case i need to pass the parameter using servlet url which i like to avoid.(in case i need to pass many parameters in future) (also values will be set on page so i need to generate url when then click the menuitem...... so there are some hoops and loops i need to go through) I don't know a way to pass the request parameter using backing bean to servlet... i don't think it is possible.
    Those are the two approaches i tried.
    If you have any better approach...I would appreciate if you can let me know. (i have searched on internet for two days now.... for the solution)
    -R
    Edited by: polo on Dec 13, 2011 7:22 AM

    Hi,
    Hope following will useful
    http://sameh-nassar.blogspot.com/2009/10/using-jasper-reports-with-jdeveloper.html
    http://www.gebs.ro/blog/oracle/jasper-reports-in-adf/

  • Using servlet to generate XML file

    What I want to do is simple but can't work. Hope you guys can give me a hint.
    I succesfully generate XML file in command line using Oracle XML parser and class generator. Then I was trying to do it using servlet. it compiles fine but generate NullPointer exception at the line:
    Emp e1= new Emp(); //Emp is the root of XML
    I suspect the Emp constructor can't correctly find the globalDTD in its superclass -CGDocument. Please note this only happens in servlet setting, not is command line setting. Any suggestion to get arounf this?
    Another unrelated question is that when I create a XML file using the Oracle XML parser, it seems all the elements a file has to be added once, otherwise the compiler will compalain about the missing element. this will be inconvinient when I constructing a big XML file, which I 'd liek to split into small piece and add them up. Maybe there is a good way but I just don't know it.
    my email: [email protected]

    Hi,
    I'm running into the same problem deploying the classes generated by the class generator. Code works fine from JDeveloper, but had to put my DTD in the directory where my classes are. Deploying the classes with Apache's JServ gives me a NullPointer exception on the first addNode method. I guess it can't find the DTD. I tried to put the DTD in many locations but this didn't fix the problem. Any suggestions?
    Steve,
    Did you fix this problem? Thanx!
    null

Maybe you are looking for

  • My SLi issue and what seems to have solved it.

    I've had my new xpower  motherboard for a few weeks now.  From the very first day everything has worked with one exception.  When I put a second GTX 460 Hawk on the system for SLi problems began.  The first thing I noticed was the computer would take

  • How can I disable (not hide) the Boomarks Toolbar?

    I have installed the "Multirow Bookmarks Toolbar Plus 1.2" extension. In the Firefox customize toolbars box I dragged the Firefox bookmarks toolbar to the right of my home button instead of where it normally is. I then Right-clicked on the toolbar an

  • Display Sales Order Result List for a customer from ECC

    Hello Experts. I have a requirement to display list of sales order posted for a particular date or sold-to-party or ship-to-party. System landscape is as below: My ECC system  holds all the data. Orders and subsequent documents are created here. My C

  • 52" samsung lcd

    My 1year old tv just developed a 1/8"  white circle in the lower right hand corner with spider like webs with multi colored lines.  whats this all about?  I do have Black Tie Protection, is this a tv defect and is it common.  This is my first lcd tv.

  • ECC 6.0 Service Pack 4 Upgrade Impact on CRM 5.0

    Hello, With regards to an upgrade of ECC 6.0 SP4 (Enhancement Pack 1 to Enhancement Pack 4), I wish to know which areas of the CRM module would be impacted (also considering that the version is CRM 5.0). Any known experienced issues of ENH 4 impact o