Manipulate Servlet Output

Hello:
I use RequestDispatcher to call servlet2 from servlet 1. It works, but I need to manipulate the output of servlet2 in servlet1.
While Servlet API 2.3 have some filter functionality, I am using WebSphere Application Server 4.0 and it does not support 2.3 API. Any suggestion will be greatly appreciated.
Best regards
Kent

If there is no need to sent the servlet2 out put to client (browser) you transform it to a compiled class (lets say c.class), create a instance of this class into servlet1 and call a method in c.class that gives the same servlet2 output.
A second solution is to get the output of the servlet2 content like this :
URL servlet2Url = new URL("servlet2 url");
URLConnection servlet2Conn= servlet2Url.openConnection();
servlet2Conn.connect();
DataInputStream is = new DataInputStream(servlet2Conn.getInputStream());
... then read the input stream "is" like any other inputStream
Hope this will help

Similar Messages

  • Servlet output not displayed properly in Internet Explorer

    Hi All,
    I'm developing a servlet which uploads a file. After the servlet parses the request body, it stores the file contents as a binary string in the database. While displaying the contents of the attached file, the IE(Internet Explorer) is ignoring all the newlines and spaces. IThe same uploaded file when viewed through Firefox browser is being displayed properly. I've added some debug statements to print the filecontent before sending it to servlet output stream. They look exactly as they were in the uploaded file. The MIME type is application/octet-stream.
    I've also made the response to accept "ISO-8859-1" and "UTF-8" charsets, yet the IE is not rendering the file contents properly. The code looks like this,
    response.setContentType("text/html; charset= ISO-8859-1, UTF-8");
    byte[] buff = attachment.getAttachObject();
    OutputStream out = response.getOutputStream();
    out.write(buff);
    out.close();
    I've tried using PrintWriter also. I've tried changing the content types, character encodings of request and response objects, still couldn't resolve the issue. What really baffles me is that when it's displaying properly in Firefox, why can't it render properly in IE? I'm using Win XP SP2, and IE version is 6.0.29. The content which is being sent to the output stream contains newline and space characters, but they are not displayed in the browser. Did any one face this sort of issue? Your help is highly appreciated.
    Thanks,
    Tarun.

    Hi,
    Thanks for looking into the issue. Let me tell you that I've tried keeping various content-types like text/plain, text/xml etc, but in none of those cases the IE rendered the output properly. But with the same content-type i.e text/html or text/plain, Firefox is able to render the file content properly. I've tried a brutal force approach like below,
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    String str = new String(attachment.getAttachObject());
    char[] buff = str.toCharArray();
    for(i=0;i< buff.length; i++)
    int n = (int)buff;
    if(n == 10)
    out.println();
    else
    out.print(buff[i]);
    out.close();
    I was trying to print a newline whenever I find a newline character in the file content. Even this didn't work. Please suggest me some way to get rid of this problem.

  • Converting servlets output to PDF fle

    How to convert Java Servlets output html file to PDF file or a Word document.

    not sure what u mean by 'convert' the output to PDF or word document
    Do you mean you want to force the browser to open file using MSWord / PDF viewer? If yes :
    For showing output as a word document, you can set the servlet response MIME type to 'application/ms-word' and set its extension to .rtf . You can then use a RTF template to build servlet output (since RTF is flat file format). By replacing placeholder tags in RTF template, you can generate content.
    For showing output as PDF, you'll need some library for PDF writing.
    hth,
    Subodh

  • Read Servlet output stream

    how can i read servlet output stream

    i m using SAX to create an XML.
    I set result to "Servlet Output Stream" as shown below :->
    SAXTransformerFactory saxTF = SAXTransformerFactory.newInstance();
    TransformerHandler th = saxTF.newTransformerHandler();
    Transformer t = th.getTransformer();
    StreamResult stRes = new StreamResult(res.getOutputStream());
    th.setResult(stRes);
    th.startDocument();
    what i want to wright the same xml result in file at the same time(parallel y).

  • Servlet Output Streams and clearing

    I am using servlets, and I want to be able to print something repeatedly. Well, that's not exactly true: I can print something repeatedly. Using a ServletOutputStream, it doesn't seem possible to clear what has already been written. Here's the code:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.io.*;
    public class AlwaysTime extends HttpServlet {
         public void doPost(HttpServletRequest req, HttpServletResponse res)                throws ServletException, IOException {
              HttpServletResponse oldRes = res;
              Date now = new Date();
              res.setContentType("text/html");
              ServletOutputStream out = res.getOutputStream();
              out.println("<html>");
              out.println("<head>");
              out.println("<title>Clock</title>");
              out.println("</head>");
              out.println("<body>");
              out.println("<h1 align=\"Center\">");
              out.println(now.toString());
              out.println("</h1>");
              out.println("</body>");
              out.println("</html>");
              try {
                 Thread.sleep(1000);
              } catch (InterruptedException ie) {}
              // Do nothing: wait for 1 second.
              doPost(req, oldRes);
         public void doGet(HttpServletRequest req, HttpServletResponse res)
              throws ServletException, IOException {
              doPost(req, res);
    }This code prints the time every second, but I want to clear the previous output stream. I thought the code shown above would work, but of course, oldRes points to the same object as res. But I don't know how to clear an output stream, so that it is completely empty. Instead, each of the new lines are appended to the same output stream.
    This doesn't only apply to servlet output streams: is there some way to clear the System output stream, for instance?
    But mainly the servlet output stream ...

    You would not want to use HTTP for this type of functionality. HTTP is known as a 'stateless' protocol that simply returns one exact response for each request. So, there is not way to 'clear' the stream (technically, you would not do so for 'normal' streams either, but when you add HTTP into the mix, the task is definitely not possible).
    You could implement the above using a RSS feed, or by using HTTP meta-refresh tags on the page itself ot resubmit the requests every second (though this would be inefficient). An applet would also do the task.
    - Saish

  • Servlet  output correct in ie and netscape, but not in portal

    I have a servlet that retrieves and xml document, applies a
    stylesheet, and uses PrintWriter to output the html.
    When I run the servlet, the output is correct in ie and netscape.
    So, I set the servlet up as a web portlet and have put it on a
    portal page.
    My problem: When I run the portal page, the mdashes and
    rsquotes, etc. show up in portal as question marks.
    I went into the provider.xml and added some information
    (contentType,charset), but that had no effect.
    Ideas appreciated.
    Thanks.

    I have been doing some research, and this appears to be some
    sort of character encoding/unicode problem.
    I have specified UTF-8 in my servlet. Does portal not work with
    UTF-8?
    Is there a setting somewhere that I can check in portal to
    verify what character encoding it is using? (ISO-8859-1, US-
    ASCII, etc?)
    This is a sample of my servlet code:
    public void DoGet(HttpServletRequest request, HttpServlet
    Response,response)
    throws ServletException, IOException
    DOMParser parser;
    XMLDocument xml,xsldoc;
    URL xslURL,xmlURL;
    String xmld = "";
    String xsld = "";
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try
    parser = new DOMParser();
    parser.setPreserveWhitespace(true);
    xslURL = createURL(xsld);
    parser.parse(xslURL);
    xsldoc = parser.getDocument();
    xmlURL = createURL(xmld);
    parser.parse(xmlURL);
    xml = parser.getDocument();
    XSLStylesheet xsl = new XSLStylesheet(xsldoc,xslURL);
    XSLProcessor processor = new XSLProcessor();
    processor.processXSL(xsl,xml,out);
    Any advice appreciated.

  • ### URGENT: duplicated servlet output ###

    Hi,
    I'm usin cos.jar of servlets.com for file uploading. But, sometimes, the output of my servlets are duplicated. This problem doesn't occur everytime even if for the same uploaded files. Also, When I encounter this problem on my desktop, It runs on the other desktops without any problem.
    I'm sure that lines of uploaded files are not re-read/re-processed twice immediately. Because, may applications would return errors in that case. But, if entire file is re-read/re-processed, there would not be errors returned.
    Here are my configuration:
    Browser:Internet Explorer 5.0
    OS: Windows 2000 Professional
    Servlet Engine: Resin 2.1.9
    Please help...This is very important problem. Because, the output of our sevlets are duplicated.
    thanks in advance...

    Thanks for the reply.
    I'm sure this is not a thread synchronization problem.
    Here is the doPost():
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    itrprofThread iThread;
    iThread = new itrprofThread(request,response);
    iThread.start();
    try {
    iThread.join();
    } catch (InterruptedException e) {}
    I'm sure that uploaded file is processed twice after the first entire process of the file is finished. Here is the proof:
    CORRUPTED LINEs AND THEIR DEPENDENTs (2 of 2)
    Errror code Line number Line
    itp-05 [2] 99 WAIT #0: nam='SQL*Net message from client' ela= 98956 p1=1413697536 p2=1
    itp-05 [2] 353 WAIT #0: nam='SQL*Net message from client' ela= 98956 p1=1413697536 p2=1
    As you see above, the lines are the same lines. In fact, it's single line in the uploaded file. But, If you notice the line numbers of the lines, they are different. The first line number is correct. But, the second is wrong. Because, second line is duplicated.
    Also, There are 252 lines in the file. But, line number of the second line is reported 353. This is not possible.
    I'm now sure that uploaded file in the second phase is processed after the first phase is completed. Because:
    Line number in the first phase: 99
    Total line number in the file: 252
    Line number in the second phase: 353
    If I sum 99 and 252, it gives 351. It's proof the entire file is processed twice after the first phase is completed.
    is is possible to see the contents of HTML form data before sending to servlet ?
    PLEASE HELP, THIS IS VERY IMPORTANT PROBLEM.

  • REG:SERVLET OUTPUT STREAM

    I am trying to implement upload/view functionality..To view an uploaded txt file or html file,I am just flushing out the file contents into servlet's output stream..The content type has been set appropriately.
    The problem is for some html files ia m able to see the file contents in the browser,and for some html files,the browser displays a open/save dialog box..
    Can any1 explain me why this discrepency?Its the sam e code and same content type..why is it so?

    Thanks for ur reply...
    All i mentioned was in the same browser..PFB the code snippet
         ServletOutputStream pic = null;
         pic = response.getOutputStream();
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         byte b[] = new byte[5*1024];
         while(true)
              int bytes = in.read(b);
              if(bytes == -1)
                   break;
              baos.write(b, 0, bytes);
         response.setContentLength(b.length);
         b = baos.toByteArray();
         pic.write(b, 0, b.length);
         pic.flush();
         pic.close()

  • How to set NLS character set for report 9i servlet output?

    Hi,
    I am running a Reports 9i report. My problem is that the output HTML file is UTF8 encoded while ALL my 9iASR2 registry setting are set to EEISO8859P2. When I issued the http://&lt;host:port&gt;/reports/rwservlet/showenv?server=servername command it returned that the NLS setting is UTF8.
    Can somebody please help me, how to set this environment variable for the report servlet to EE..P1? Thank you in advance.
    Regards,
    Tamas Szecsy

    Dmitry,
    recently I got this from Oracle support. :-(. Currently when I set the Windows 2000 local and default local to Hungarian and the charset to EE..P2 then I get Central-European encoded charset. I think you will have to experience around to get correct result (if it is possible at all).
    +++++++++++++++++++++++++++++++++++++++++++++++++++++
    This is bug Number 2472932 NLS:RWSERVLET SETS INVALID CHARSET AT THE HTTP HEADER
    marked as fixed in 9.0.2.2 . unfortunately this bug is not published so I will not be able to sent you the bug as a whole but here is problem description in bug:
    iAS9.0.2.0.1 (Reports9.0.2.0.1) on Solaris2.8
    Running rdf with rwservlet sends the invalid charset at the http header.
    Say ias is up with LANG=C, http header for the rwservlet
    is always sent as "iso-8859-1" regardless of rwserver's NLS_CHARACTERSET.
    This is the TCP/IP packet for the GET /reports/rwservlet?report=xxx&....
    HTTP/1.1 200 OK Date: Sat, 20 Jul 2002 01:15:37 GMT Cache-Cont
    rol: private Content-Language: en Server: Oracle9iAS/9.0.2 Ora
    cle HTTP Server Oracle9iAS-Web-Cache/9.0.2.0.0 (N) Content-Leng
    th: 6908 Content-Type: text/html; charset=ISO-8859-1 Set-Cooki
    In this example, to produce a html with other charset than
    iso-8859-1,usually the outputted html has the charset information at
    meta tag by setting "Before Report Value" property in rdf.
    However charset in meta tag is less priority than http header, browser
    such as IE6 or Netscape7 firstly displays the page in iso-8859-1.
    Hence the characters other than iso8859p1 gets garbage.
    To workaround it with IE6/NS7, set proper encoding manually.
    ('View'-'Encoding' for IE 'View'-'Character coding' for NS7 )
    However, NS4.7 does not have workaround for it.
    Besides, starting opmn in LANG=ja, the rwservlet's http header becomes
    Shift_JIS!!. Thus rwserver seems to set the http header based on the
    LANG on Solaris.
    To fix these issues,
    - The http header for rwservlet shold be based on the nls_characterset
    for the rwserver.
    This is no problem for reprots jsp run.

  • IE fails handing servlet output to plugin (netscape does)

    My servlet returns a file to the browser that a browser plugin is required to display. If I request the file using a GET from IE (5.0 or 5.5), the file is sent 2X from the servlet but does get displayed. This is fine for my test servlet, but my application can't handle being asked 2x for the same thing.If I use a POST, it only sends the file one time but fails to hand it off to the plugin and generates the Plugin Error dialog "The data that the plugin requested, did not download successfully". Everything works fine with netscape. I had someone test my servlet using IIS and JRun and they said it worked fine, so that pointed me to Weblogic.Thanks
              

    Hi
    A very interesting problem. Browsers handle html is different ways. IE may be rearranging the HTML removing the white space in between whereas Netscape might not.
    The best way to attack this problem is append the Html output into a String object as your processing moves through different stages. Now you can try printing it to the console or to a Log file once you are done. Alternately you can check to see the length of content if it matches the length of content which is printed out from a "view source" on IE.
    This is only to eliminate the probability of accidental appending of invisible characters during processing which the browsers might be auto correcting.
    I would think this process would help you to resolve the issue even though the problem may be somthing else.
    Keep us posted.
    Good Luck!
    Eshwar Rao
    Developer Technical Support
    Sun microsystems
    http://www.sun.com/developers/support

  • Writing to servlet output stream

    Hi All,
    I am writing to a servlet(imageservlet) output stream in a jsp page two times as follows:
    <img src="\imageservlet?key=x1">
    <img src="\imageservlet?key=x2">
    It is causing memory errors. Do I have to take special precautions?
    Thanks inadvance.

    Hi,
    THis is my servlet code.
    import java.io.*;
    import java.io.StringWriter;
    import javax.servlet.http.*;
    import javax.servlet.*;
    import java.awt.Color;
    import com.trizetto.healthweb.service.GenerateImage;
    * Simple servlet to use with Image I/O generator
    public class GenerateImageServlet extends HttpServlet
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
         String className="PieChartGenerator";
         if(request.getParameter("keyName").equals("Pie"))
              className=PieChartGenerator";
         else if( request.getParameter("keyName").equals("Gantt") )
              className="GanttChartGenerator";
    try
    GenerateImage ge=
    (GenerateImage) Class.forName(className).newInstance();
    String type = ge.createImage(response.getOutputStream());
    response.setContentType(type);
    catch (Exception e)
    throw new ServletException(e);
    But this one does not generate image. The image is generated from the Graphics object of the Frame.
    Something like the following code:
    http://www.javaworld.com/javaworld/jw-05-2000/servlets/Servlets.zip
    http://www.javaworld.com/javaworld/jw-05-2000/jw-0505-servlets-p2.html
    http://www.javaworld.com/javaworld/jw-05-2000/jw-0505-servlets-p1.html
    I am using Java 1.1.
    I am running my app. in websphere. The error happens randomly while I am stopping the websphere application server.
    Thanks in advance.

  • How to compress JSP/Servlet output with WebCache?

    Hello,
    I have an application using servlet/JSP. A request coming from the browser is handle by a servlet, and then forward the processing to a JSP page that produces the response. The requests are like http://host:port/athena/execute/action and we use POST method. It seems WebCache does not compress the output if I specify this compression rule
    URL expression: ^/athena/.*$
    Method POST
    POST Body Expression .*
    What's wrong ??
    Thanks in advance.

    This is already answered in another identical thread.

  • Include to jsf  servlet output data

    hello
    my servlet transforms xml document by xstl and i want to include into my jsf page what servlet writes in outputStream
    i had tried facelet's ui:include, but it said that the path invalid
    what way can i go to resolve this problem?
    thank you
    Edited by: user10279326 on Dec 24, 2010 1:16 PM
    Edited by: user10279326 on Dec 24, 2010 1:16 PM

    You could use an URLConnection in a JSF backing bean to invoke the servlet, then output the result through a property of the backing bean.
    If we're talking about lots of data you might want to rethink your strategy a little. For example you could use Ajax to fetch the data from the servlet through the client side and display a 'processing' icon while it is busy loading the data. That way your page displays almost immediately and the servlet result will then display as soon as it is done processing.

  • Sharing info among servlet, output right??

    hi everyone, i have written two servlet for sharing information, mean the information of one servlet can be shared by other. i have taken help from a book, but the desired output is not coming. can u please find what wrong with this 2 servlet.
    This is the first servlet which will set the property of password to dingdong.
    public class AttributeSetterServlet implements Servlet{
        public void init(ServletConfig config) throws ServletException{
            //bind object that is to be shared with other servlet
            ServletContext servletContext = config.getServletContext();
            servletContext.setAttribute("password", "dingdong");
        public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        public void destroy(){
        public String getServletInfo(){
            return null;
        public ServletConfig getServletConfig(){
            return null;
    }THis is the second servlet which will get the attribute value, but the desired output is not coming. it will display different output.
    public class DisplayAttributeServlet implements Servlet {
        ServletConfig servletConfig;
        public void init(ServletConfig config) throws ServletException{
            servletConfig = config;
        public void destroy(){
        public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            ServletContext servletContext = servletConfig.getServletContext();
            Enumeration attributes = servletContext.getAttributeNames();
            while(attributes.hasMoreElements()){
                String attribute = (String) attributes.nextElement();
                out.println("Attribute name: " + attributes);
                out.println("\n");
                out.println("Attributes value: " + servletContext.getAttribute(attribute));
                out.println("\n");
        public String getServletInfo(){
            return null;
        public ServletConfig getServletConfig(){
            return null;
    }

    Ok I know that. Now what I meant is do I need to poll the server for new messages (still using the chat-app between midlets example) or can I make both midlets open a connection to the server and send their messages to the server, and have the server redirect the messages to the respective client-midlet. I'm thinking something like each client midlet opens a connection, sends stuff whenever it wants (on the server side, output streams are not closed until some special flag is set) and keeps listening for answers until the user quits or say some special char comes from the server.
    The thing is I'm having some problems when I keep readStreams open after a while (inside a while loop waiting for some special code) and I was wondering if this is valid or is indeed a problem with my code.
    This is what I meant with tunnel before, not really say raw socket comm between midlets but a tunnel through a server that nevertheless kept each midlet from having to poll the ditto all the time. Apologies for not being too clear about it.
    I'm using something like (in pseudo pseudo-code & ommiting all the registration steps etc):
    client midlets
    conn = openConnection();
    out = conn.getOutpuStream();
    in = conn.getInputStream();
    if (!postbox.isEmpty()) {
    msg = removeHead(postbox);
    out.writeStream( sendMessage(msg) );
    ... on a separate thread
    while (USER_IS_ON){
    msg = in.readStream();
    if (msg != null) postbox.add(msg);
    close(conn, out, in);
    Server
    out = request.getOutpuStream();
    in = request.getInputStream();
    data = in.readStream();
    // write this guy's data on the other recipient's queue
    queue.add(data, id);
    ... on a separate thread
    while (USER_IS_ON){
    // get data to this guy from queue
    if (data = hasData(id) != null)
    out.writeStream(data, id);
    close(conn, out, in);
    On fear of making this too long, I'll stop here. I can post the source if you wish but it is rather lenghty :-)
    Thanks for the help!
    cheers
    j.

  • Controlling JSP/servlet output buffering

    I'm doing some performance testing on some JSPs and I need to be able
              to separate client side rendering/javascript execution time from
              server side execution of the (JSP-generated) servlet.
              The normal way for the servlet generated from the JSP to behave is
              that the output stream to the browser is buffered - that is, as the
              servlet generates output it is written to the buffer in chunks and the
              buffer is written to the browser in chunks. On all but the shortest
              pages the content from the bottom of the JSP hasn't even been
              generated yet at the time the buffer starts writing to the browser.
              I want to turn this behavior off. I want no output sent to the browser
              until the whole output is generated. This way I can put timers in my
              client side Javascript and know they are measuring only the client
              side execution time, not the server side.
              Does anyone know how to do this?
              Eliot Stock
              Premiere Retail Networks
              San Francisco
              

    Hi Eliot,
              you can use the page directive's buffer and autoFlush attributes to
              control the size of the output buffer.
              <%@ page buffer="100kb" autoFlush="false" %>
              Here's a link:
              http://java.sun.com/products/jsp/tags/10/syntaxref10.fm7.html
              Nils
              Eliot Stock wrote:
              >
              > I'm doing some performance testing on some JSPs and I need to be able
              > to separate client side rendering/javascript execution time from
              > server side execution of the (JSP-generated) servlet.
              >
              > The normal way for the servlet generated from the JSP to behave is
              > that the output stream to the browser is buffered - that is, as the
              > servlet generates output it is written to the buffer in chunks and the
              > buffer is written to the browser in chunks. On all but the shortest
              > pages the content from the bottom of the JSP hasn't even been
              > generated yet at the time the buffer starts writing to the browser.
              >
              > I want to turn this behavior off. I want no output sent to the browser
              > until the whole output is generated. This way I can put timers in my
              > client side Javascript and know they are measuring only the client
              > side execution time, not the server side.
              >
              > Does anyone know how to do this?
              >
              > Eliot Stock
              > Premiere Retail Networks
              > San Francisco
              ============================
              [email protected]
              

Maybe you are looking for

  • How can i find the serial number for an ipod classic

    I dont have the original packaging or the reciept, It wont connect to itunes or my laptop and all that shows on the ipod's screen is a red circle with a cross inside it. I have tried to reset it but have not been able to. Any help would be much appre

  • Partner should not be deleted

    Hi All,       In Ibase partner functions, it is displaying all partner. my requirement is ,it should not be deleted, when it is in display mode.      is there any configuration or BADI to control this one? kathir.

  • UITableView with custom frame size within a UINavigationController... how?

    I've seen similar questions asked all over the web, but so far not a single "real" answer has cropped up, so hopefully you folks will know the way to do this. I have a main view that with a UIView subview, inside of which I am programmatically adding

  • ITunes 11.1.4

    iTunes update 11.1.4 doesn't work. The error occurs when deleting existing version 11.1.3. If you receive error message and cannot open you need to completely remove (unitstall) iTunes and reinstal again and it will work fine. You won't lose your mus

  • Time machine was not working.  I bought a new time machine and migrated time machine files to new time capsule; not recognized by yosemite

    Time machine was not working after yosemite upgrade on new and old MacBooks in my house.  I bought a new time machine and migrated time machine files to new time capsule. I changed the names of the older sparse bundles to the default values.  Yosemit