Modify Servlet response using filter

This is the code wht i am using, this is an example give in the oronserver.com and some other sites too..
import javax.servlet.*;
public class GenericFilter implements javax.servlet.Filter {
public FilterConfig filterConfig;
public void doFilter(final ServletRequest request,
final ServletResponse response,
FilterChain chain)
throws java.io.IOException, javax.servlet.ServletException {
chain.doFilter(request,response);
public void init(final FilterConfig filterConfig) {     this.filterConfig = filterConfig;
public void destroy() {                                             
=============================================================
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class FilterServletOutputStream extends ServletOutputStream {
private DataOutputStream stream;
public FilterServletOutputStream(OutputStream output) {
stream = new DataOutputStream(output);
public void write(int b) throws IOException {
stream.write(b);
public void write(byte[] b) throws IOException {
stream.write(b);
public void write(byte[] b, int off, int len) throws IOException {
stream.write(b,off,len);
===================================================
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class GenericResponseWrapper extends HttpServletResponseWrapper {
private ByteArrayOutputStream output;
private int contentLength;
private String contentType;
public GenericResponseWrapper(HttpServletResponse response) {
super(response);
output=new ByteArrayOutputStream();
public byte[] getData() {
return output.toByteArray();
public ServletOutputStream getOutputStream() {
return new FilterServletOutputStream(output);
public PrintWriter getWriter() {
return new PrintWriter(getOutputStream(),true);
public void setContentLength(int length) {
this.contentLength = length;
super.setContentLength(length);
public int getContentLength() {
return contentLength;
public void setContentType(String type) {
this.contentType = type;
super.setContentType(type);
public String getContentType() {
return contentType;
===========================================================
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class PrePostFilter extends GenericFilter {
public void doFilter(final ServletRequest request,
final ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
OutputStream out = response.getOutputStream();
out.write("<HR>PRE<HR>".getBytes());
GenericResponseWrapper wrapper = new
GenericResponseWrapper((HttpServletResponse) response);
chain.doFilter(request,wrapper);
out.write(wrapper.getData());
out.write("<HR>POST<HR>".getBytes());
out.close();
===========================================================
filter3.jsp
<HTML>
<HEAD>
<TITLE>Filter Example 3</TITLE>
</HEAD>
<BODY>
This is a testpage. You should see<br>
this text when you invoke filter3.jsp, <br>
as well as the additional material added<br>
by the PrePostFilter.
<br>
</BODY>
</HTML
When i run the above code i am not getting data which is there in the jsp page, i am getting data which i am writing it in the prepostFilter.
the output is
PRE
Post
Is the above is overwriting the actual response ?
If so can anyone tell me how to modify the response of the servlet instead of overwriting.............i will so thankful to you.

i run your codes and get the following:
PRE
This is a testpage. You should see
this text when you invoke filter3.jsp,
as well as the additional material added
by the PrePostFilter.
POST
my testing environment is
sun j2ee ri 1.3.1
and i deploy filter3.jsp and set the filter Mapping as the following
Filter Name: PrePostFilter
Target Type: Url Pattern
Target : /*

Similar Messages

  • Caching response using filter without closing response

    Hi all SAP J2EE Gurus!
    I have implemented a servlet filter that caches the response to the client in memory and then uses the cached page for the following calls until the TimeToLive has been reached and this caching is repeated.
    This works fine, except for the actual call that creates the cache. This call, once I have read the response through the responsewrapper, is empty, hence the requesting user gets a blank page and needs to hit refresh to see the cached output.
    All the other calls work fine when we just return the cached page in the response.
    I have gathered so far that the reason for this behaviour is in the implementation of the servlet container in the J2EE engine and hence the behaviour differs between different server implementations.
    I have wrapped the outputstream and its write methods with custom implementation as well as extended the HttpServletResponseWrapper and overwritten the getWriter and getOutputstream methods with custom implementations.
    I am using this filter with the ISA 4.0 which is basically a Struts application.
    Does anyone have some experience with caching the response of the SAP J2EE engine without closing the stream? If yes then would be interested to hear how this was achieved.
    I will add some code snippets with explanation later if someone has some relevant ideas that would need them for clarification.

    i run your codes and get the following:
    PRE
    This is a testpage. You should see
    this text when you invoke filter3.jsp,
    as well as the additional material added
    by the PrePostFilter.
    POST
    my testing environment is
    sun j2ee ri 1.3.1
    and i deploy filter3.jsp and set the filter Mapping as the following
    Filter Name: PrePostFilter
    Target Type: Url Pattern
    Target : /*

  • How to modify a servlet response?

    Hi all,
    I want to modify the servlet response string returned by the portal irj servlet.
    For this I created a filter.
    Now my requirement is to do something like this in the doFilter method:
    doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
    PrinterWriter pq = res.getWriter();
    Reader reader = new StringReader(printWriter.toString());
    BufferedReader bufferedReader = new BufferedReader(reader);
    String line;
    while ((line = bufferedReader.readLine()) != null) {
    line.replaceAll("Welcome", "Welcome to XXXX");
    What I am trying to do is in the response stream replace the letter welcome with "Welcome to XXXX".
    I know I cant accomplish this by the code given above.
    Any body has a code snippet of how to get this working?
    Thanks

    Hi,
    You are already in the right way, things missing are:
    1. Forgot the do the filter chain     
          filterChain.doFilter(request, wrapper);
    2. Write back the modified stream to response
    // write the response stream           
          response.setContentLength(responseStr.length());
          response.getWriter().write(responseStr);      
    You can use the HttpServletResponseWrapper to manipulate the response too, check the examples at this link:
    http://www.jsp-develop.de/faq/show/47/
    Greetings,
    Praveen Gudapati
    [Points are always welcome for helpful answers]

  • Servlet Response Problem

    Hello all,
    My simple servlet takes in a URL as a parameter and the uses the httpUrlConnection method to retrieve that page. It then just writes the html to the browser in the hope that it would be displayed as if retrieved directly.
    Although the source of a page retrieved in this way is identicle to the expected source, no images appear. I think (guess) this is because the address of a page retrieved in this way will not be the same as if retrieved normally. This, in turn, messes up the relative file paths. e.g www.mypage.com becomes something like http://localhost/httpProxyServer?URL=http%3A%2F%2Fwww.mypage.com (httpProxyServer is the name of the servlet).
    To get to the point, idoes anyone know if there is a way i can set the address of the returned page to be as if retrieved directly? I have looked in to response headers with little luck although i am very new to servlets. Thanks for any tips or advice.
    Christie

    This question can be better answered if you point out the need to examine each response before actually sending it out to the browser. What exactly do you look for in the response ? Do you compress it / transform it / parse it ?
    Having said that, you could use filters to meet any of your above needs.
    1. The first obvious gain is that it is a standard, widely accepted and part of the j2ee specification. As you said, it provides modularity and resuability of code. Somebody who goes through your work would easily pick up the trail, comprehend concisely the effort and the ends you attempt to achieve. You would have implicit server support (more of this later)
    2. You use a servlet that intercepts each request. It then uses a HttpURLConnection to get the response from each resource. As you can see straight away, this essentially makes it two requests per request - the original request goes to your general purpose servlet; then the general purpose Servlet(GPS hereafter) makes the url connection to the resource, its a brand new request. The original request may have lots of params coming in which have to be reconstructed by the GPS and included in the call to the resource which delivers the actual response back to the GPS. Hope you begin to see the pitfalls here (for example imagine the incoming stream is a byte stream resulting from a file upload)
    **in short** the 'simple servlet' is going to get very very complex as your application grows.
    3. All the above rerouting (even if you manage to achieve it successfully) will take its toll on the performance measured in terms of the response time.
    4. In established MVC2 framework like Struts or JSF, the Servlet that intercepts every request is a Controller Servlet (which knows how to handle the request, which validations to perform, which beans to invoke and so on). Your GPS should in addition to examining responses, do all this stuff or else you would end up with multiple Controllers making your app quite unwieldy.
    5. Using filters, you could side step all the above which in itself is a huge advantage (me thinks :)) besides providing a standard way to implement tasks similar to yours. I mentioned implicit server support, right ? Filters are supported by all standard j2ee web severs. You neednt write a single line of code to have your filter modify the response. All you have to write is the actual modification algorithm. However the path you choose, you would have to manually do all the dirty work of transferring the request to the actual resource (using HttpUrlConnection). You should receive each request params and convey that to the resource being accessed and so on. (see #2 above)
    Hope all that helps.
    cheers,
    ram.

  • How to  use  Filter  in ActionServlet

    hi how do i use filter in my ActionServlet ?
    here is a code :
    package test;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    public class TimeFilter implements Filter {
      public void init(FilterConfig config) throws ServletException {
      public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        // only service the request between 08:00 and 17:59
        if (hour >= 8 && hour <= 17) {
          chain.doFilter(request, response);
        // for other times, forward the request to someplaceelse
        } else {
          request.getRequestDispatcher("/someplaceelse").forward(request, response);
      public void destroy() {
    }where do i place it in my ActionServlet to get filtered access ?
    My ActionServlet :
    import javax.servlet.http.*;
    import org.apache.struts.action.*;
    import java.io.*;
    import java.util.*;
    public final class SubmitAction extends Action {
      public ActionForward perform(ActionMapping mapping,
          ActionForm form,
          HttpServletRequest request,
          HttpServletResponse response) {
          DynaActionForm SubmitForm = (DynaActionForm) form;
         // blah
        // blah
    return (mapping.findForward("success"));
    }can ActionServlet use filter ?
    How do i use the Filter class in ActionServlet if i want to get filtered Aceess of the website ?

    Ok, this is how filters work.
    Typically the filter maps to '/*' and your action servlet maps to '/*.do'. So if you request 'login.do', then the filter would first be called. If it's not between 08:00 and 16:59, the request will be passed on to the action servlet, else it would be forwarded to the action servlet.
    There's no need to 'integrate' the filter into you action servlet.

  • Simple authentication and authorization with a servlet and a filter

    Could somebody point me to code example that do simple authentication/authorization using one servlet and one filter? (without Spring, Struts, JSF or any framework)
    I&rsquo;m having a lot of problems with that, apparently, easy task.
    These are the rules:
    - A simple login page
    - Two roles (admin, registered).
    - If the user loged is an admin, redirect to his entry page (private/admin/index.jsp).
    - If the user loged is of role registered, redirect him to his entry page (private/registered/index.jsp).
    - If it&rsquo;s not a valid user, redirect again to login page.
    - Admin&rsquo;s users cannot go to private/registered/ area.
    - Registered users cannot go to private/admin/ area.
    - Non authenticated user cannot go to private/ area
    Thanks a lot in advance!
    Edited by: JLuis on 25-ago-2010 15:27

    AccessControl.java:
    package com.tlsformacion.security;
    import java.io.IOException;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.tlsformacion.utils.Log;
    public final class AccessControl extends HttpServlet {
         private static final long serialVersionUID = 5741058615983779764L;
         private static final String USERNAME_ATTR = "username";
         private static final String PWD_ATTR = "password";
         private static final String LOGIN_PAGE_ATTR = "login_page";
         private static final String ROL_ATTR = "role";     
         private boolean isAuthentic = false;
         private String role = null;
         private String loginPage = null;
         public AccessControl() {
            super();
         public void init(ServletConfig config) throws ServletException {
              loginPage = config.getInitParameter(LOGIN_PAGE_ATTR);
         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside doGet");
              doAccessControl(request, response);
         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside doPost");
              doAccessControl(request, response);
         private void doAccessControl (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside doAccessControl");
              doAuthentication(request, response);     
              if (isAuthentic) { //Authentic user
                   doAuthorization(request, response);                         
              } else { //User NOT authentic
                   doRejection(request, response);
         private void doAuthentication(HttpServletRequest request, HttpServletResponse response) {     
              debug("Inside doAuthentication");                         
            String requestedURI = request.getRequestURI();
            if (requestedURI.contains("/AccessControl")) { //Comes from login page           
                 debug("Comes from login page");
                  String username = request.getParameter(USERNAME_ATTR);
                String pwd = request.getParameter(PWD_ATTR);   
                 role = getRole(username, pwd);
                 if (role != null) {
                      isAuthentic = true;
                      request.getSession().setAttribute(ROL_ATTR, role);
            } else { //Doesn't comes from login page
                 debug("Doesn't comes from login page");
                 if (isInSession(request)) {
                      debug("Rol is in session");               
                      isAuthentic = true;
                 } else {
                      debug("Rol is NOT in session");
         private void doAuthorization(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          
              debug("Inside doAuthorization");
              String requestedURI = request.getRequestURI();
              debug("requestedURI: " + requestedURI);
              if (requestedURI.contains("/AccessControl")) { //Comes from login page                                                                 
                   goHomePage(request, response);
              } else if (requestedURI.contains("/private/" + role)) { //Trying to access his private area
                   goRequestedPage(request, response);
              } else { //Trying to access other roles private area
                   goLoginPage(request, response);
        private void doRejection(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          
             debug("Inside goRejection");
             role = null;
              goLoginPage(request, response);         
         private void goHomePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside goHomePage");     
              String homePage = "private/" + role + "/index.jsp";
              goPage(request, response, homePage);
         private void goLoginPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside goLoginPage");
              goPage(request, response, loginPage);
         private void goRequestedPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside goRequestedPage");
              String contextPath = request.getContextPath();          
              debug("contextPath: " + contextPath);
              String requestedPage = request.getRequestURI().replace(contextPath + "/", "");
              goPage(request, response, requestedPage);
         private void goPage(HttpServletRequest request, HttpServletResponse response, String page) throws IOException, ServletException {
              debug("Inside goPage ...trying to go to: " + page);
              //Option A
              response.sendRedirect(page);
              //Option B
              //RequestDispatcher requestDispatcher = request.getRequestDispatcher(page);
              //requestDispatcher.forward(request, response);                  
         private boolean isInSession(HttpServletRequest httpRequest) {
             boolean inSession = false;
              role = (String)httpRequest.getSession().getAttribute(ROL_ATTR);
              if (role != null && !role.equals("")) {
                   inSession = true;
             return inSession;
        //PENDIENTE: mock method!
        private String getRole(String username, String pwd) {         
             String role = null;
             if (username.equals("admin") && pwd.equals("admin")) {
                  role = "administrator";
             } else if (username.equals("regis") && pwd.equals("regis")) {
                  role = "registered";
             return role;
        private void debug(String msg) {
             Log.debug(msg);
    }Proyect Folder Structure:
    WebContent
         login.html
         private
              administrator
                   index.jsp
              registered
                   index.jspBasically, the problem is that if you try to log as admin/admin (for example) the servlet AccessControl executes infinitely
    Edited by: JLuis on 26-ago-2010 8:04

  • IPlanet 6.0 And servlet filters with filter-test.war not working

    Hi, I am trying to get servlet filters running on iPlanet6.0. I deployed the 'filter-test.war' file, and then modified web-apps.xml to contain the filter configuration. I even modified the example classes to log to a file on disk. The only thing that happens is intialization. Further it never get's to call the 'doFilter' method at all.
    Is there anything I'm missing?
    All I did was deploy the war file, and then modify the web-apps.xml file, and then restart the server. Is there anything else?
    Here is my web-apps.xml file as been modified.
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE vs PUBLIC "-//Sun Microsystems, Inc.; iPlanet//DTD Virtual Server Web Applications 6.0//EN"
         "http://developer.iplanet.com/webserver/dtds/iws-webapps_6_0.dtd">
    <vs>
    <web-app uri="/" enable="true"/>
    <web-app uri="/filter-test" dir="C:/temp/iplanet/deployed" enable="true">
    <!-- Define servlet-mapped and path-mapped example filters -->
    <filter>
    <filter-name>Servlet Mapped Filter</filter-name>
    <filter-class>filters.ExampleFilter</filter-class>
         <init-param>
         <param-name>attribute</param-name>
         <param-value>filters.ExampleFilter.SERVLET_MAPPED</param-value>
         </init-param>
    </filter>
    <filter>
    <filter-name>Path Mapped Filter</filter-name>
    <filter-class>filters.ExampleFilter</filter-class>
         <init-param>
         <param-name>attribute</param-name>
         <param-value>filters.ExampleFilter.PATH_MAPPED</param-value>
         </init-param>
    </filter>
    <filter>
    <filter-name>Request Dumper Filter</filter-name>
    <filter-class>filters.RequestDumperFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>Servlet Mapped Filter</filter-name>
         <servlet-name>invoker</servlet-name>
    </filter-mapping>
    <filter-mapping>
    <filter-name>Path Mapped Filter</filter-name>
         <url-pattern>/servlet/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
    <filter-name>Request Dumper Filter</filter-name>
         <url-pattern>/servlet/*</url-pattern>
    </filter-mapping>
    </web-app>
    </vs>
    Thank you

    Why not try WS 6.1 -- which has the full support for Servlet 2.3 including filters.
    As for 6.0, what URI do you use? Is it:
    /filter-test/servlet/<servlet-name>

  • A problem with servlet  mapping , using a servlet to produce some chart in

    Hi
    Thank you for reading my post.
    My problem is about using a Chart library which works well in jsf application but it does not works in JSF portlets.
    I think i find the problem but i do not know the solution.
    to use this charting library we should add a servlet to web.xml
    something like :
    <servlet>
    <servlet-name>Jenia internal servlet</servlet-name>
    <servlet-class>org.jenia.faces.util.Servlet</servlet-class>
    <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>Jenia internal servlet</servlet-name>
    <url-pattern>/jenia4faces/*</url-pattern>
    </servlet-mapping>
    so , when we try to load a chart , it will make the chart image source
    something like
    http://localhost:28080/Adv/jenia4faces/chart/OAReport.jspBarChart3d_id0.png
    in the above sample , adv is the name of web application which is
    deployed in a servlet container.
    and filter applied to make the chart render-able.
    to use the chart library in jsf portlet , i add the servlet
    description as i did for web application , so i add
    <servlet>
    <servlet-name>Jenia internal servlet</servlet-name>
    <servlet-class>org.jenia.faces.util.Servlet</servlet-class>
    <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>Jenia internal servlet</servlet-name>
    <url-pattern>/jenia4faces/*</url-pattern>
    </servlet-mapping>
    to my portlet web.xml file.
    when we have portlet , the url to access that portlet (which indeed is a
    web application) changes
    for example
    url for a sample portlet with same web application name
    will be like
    http:// localhost:28080/pluto/portal/Adv/
    as you can see there are some prefix to web application name in the url
    , but when i use chart component to show
    same chart , it still look for the chart in url like :
    http://localhost:28080/Adv/jenia4faces/chart/OAReport.jspBarChart3d_id0.png
    As you may already sugest , the image will not render because browser is
    looking in wrong place.
    now i
    think if i find some way to map that servlet to correct url
    pattern it will works.
    my question is :
    1-what will be new servlet url pattern ?
    2-is my assumption correct ?
    Thank you very much for reading such a long post

    i wrote an app i.e servlet which would select the data from the database and retrive the data.but i want to send this data to normal java file(which is not a servlet) and i want to display results in the normal java file.
    can any body help this concept........
    send me mail:[email protected]

  • Concurrent processing of POST requests and automatic flushing of the servlet response buffer in WLS6.1.

              Hi all,
              I encountered the following 2 servlet problems in WLS 6.0/ 6.1:
              1. Processing concurrent POST requests
              WLS seems to disallow concurrent executions of any servlet's doPost servlet method.
              When two clients attempt to send a request to a servlet using POST, the socond
              one
              is blocked until the first customer is served. In essence, the servlet ends up
              operating in
              1-user mode. I just learned from Jervis Liu that the problem is solved in WLS6.0
              if you disable http-keepalive.
              For WLS 6.1 a partial workaround is to make the servlet work in a single-thread
              mode (by implementing the javax.servlet.SingleThreadModel interface). In this
              case,
              WLS dispatches concurrent requests to different instances of the servlet.
              This doesn't completely eliminate the problem - still only one customer can be
              connected at a time. The improvement is that once the first customer is disconnects,
              the second can be served even if the doPost method for the first has not finished
              yet.
              2. Flushing the response buffer in WLS 6.1
              The servlet response buffer is not flushed automatically until doPost ends, unless
              you
              explicitly call response.flushBuffer(). Closing the output stream doesn't flush
              the
              buffer as per the documentation.
              I see that other people are experiencing the same problems.
              Has anyone found any solutions/workarounds or at least an explanation.
              Any input would be highly appreciated.
              Thanks in advance.
              Samuel Kounev
              

    Thanks for replying. Here my answers:
              > Did you mark your doPost as synchronized?
              No.
              > Also, try testing w/ native i/o vs not ... is there a difference?
              With native I/O turned off I get a little lower performance, but the
              difference is not too big.
              Best,
              Samuel Kounev
              > Peace,
              >
              > --
              > Cameron Purdy
              > Tangosol Inc.
              > << Tangosol Server: How Weblogic applications are customized >>
              > << Download now from http://www.tangosol.com/download.jsp >>
              >
              > "Samuel Kounev" <[email protected]> wrote in message
              > news:[email protected]...
              > >
              > > Hi all,
              > >
              > > I encountered the following 2 servlet problems in WLS 6.0/ 6.1:
              > >
              > > 1. Processing concurrent POST requests
              > >
              > > WLS seems to disallow concurrent executions of any servlet's doPost
              > servlet method.
              > >
              > > When two clients attempt to send a request to a servlet using POST, the
              > socond
              > > one
              > > is blocked until the first customer is served. In essence, the servlet
              > ends up
              > > operating in
              > > 1-user mode. I just learned from Jervis Liu that the problem is solved in
              > WLS6.0
              > >
              > > if you disable http-keepalive.
              > >
              > > For WLS 6.1 a partial workaround is to make the servlet work in a
              > single-thread
              > >
              > > mode (by implementing the javax.servlet.SingleThreadModel interface). In
              > this
              > > case,
              > > WLS dispatches concurrent requests to different instances of the servlet.
              > > This doesn't completely eliminate the problem - still only one customer
              > can be
              > >
              > > connected at a time. The improvement is that once the first customer is
              > disconnects,
              > > the second can be served even if the doPost method for the first has not
              > finished
              > > yet.
              > >
              > > 2. Flushing the response buffer in WLS 6.1
              > > The servlet response buffer is not flushed automatically until doPost
              > ends, unless
              > > you
              > > explicitly call response.flushBuffer(). Closing the output stream doesn't
              > flush
              > > the
              > > buffer as per the documentation.
              > >
              > > I see that other people are experiencing the same problems.
              > >
              > > Has anyone found any solutions/workarounds or at least an explanation.
              > > Any input would be highly appreciated.
              > >
              > > Thanks in advance.
              > >
              > > Samuel Kounev
              =====================================================
              Samuel D. Kounev
              Darmstadt University of Technology
              Department of Computer Science
              DVS1 - Databases & Distributed Systems Group
              Tel: +49 (6151) 16-6231
              Fax: +49 (6151) 16-6229
              E-mail: mailto:[email protected]
              http://www.dvs1.informatik.tu-darmstadt.de
              http://skounev.cjb.net
              =====================================================
              [att1.html]
              

  • Weblogic 12c Servlet Response - Special characters show up as question mark

    My web app is running on Weblogic 12c (12.1.1) using WebWork + Hibernate. The program streams data (bytes making up a pdf) from a CLOB in an Oracle Database to the AsciiStream of the servlet output response. No exceptions are thrown, but the generated pdf contains blank pages. Comparing the bytes of the generated pdf, special characters are showing up as question marks.
    Some of the bytes read in from the database contain 8 bits (correct data), but the bytes that the servlet return contain only 7 (all bytes with 8 bits become "1111111"). The number of bytes returned from the servlet is correct.
    Code:
    //Response is HttpServletResponse
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "inline; filename=\"test.pdf\"");
    out = response.getOutputStream();
    byte[] buf = new byte[16 * 1024];
    InputStream in = clob.getAsciiStream();
    int size = -1;
    while ((size = in.read(buf)) != -1){
    // buf contains the correct data
    out.write(buf, 0, size);
    // other exception handling code, etc
    out.flush();
    out.close();
    "Correct" pdf byte example:
    10011100
    10011101
    1010111
    1001011
    1101111
    11011011
    Incorrect pdf byte example:
    111111
    111111
    1010111
    1001011
    1101111
    111111
    I have verified that the data read from the CLOB in the database IS correct. My guess is that the Weblogic server has some strange servlet settings that causes the bytes to be written to the servlet output stream incorrectly, or a character encoding issue. Any ideas?
    Edited by: 944705 on Jul 26, 2012 10:17 AM

    Solution found, I'll post the work around to those who might encounter the same problem.
    Somewhere in the layers of technology (webwork or weblogic I'd guess), the servlet response is encoded into UTF-8 regardless. The encoding in the database was ISO-8859-1. Sending ISO encoded bytes by UTF-8 caused the conflicting character codes (anything above 127) to show up as undefined.
    The fix is to decode the input byte array into ISO-8859 string, then encode that string into UTF-8, which can be send by Weblogic.
    isoConvert = new String(buf, "ISO-8859-1");
    out.write(isoConvert.getBytes("UTF-8"), 0, isoConvert.getBytes("UTF-8").length);

  • ALV grid, prevent return to line 1 column 1 after using filter button

    How can I prevent the ALV grid display from returning to line 1, column 1, after a user has modified the display using the filter or sort button ?  I know this is possible using the is_stable field when control is passed to my ALV code, but when the automatic on-screen buttons are used I can't find a way of controlling how the screen is displayed.

    Max,
    Thanks, the AFTER_USER_COMMAND event allows me access after the filter or sort button has bee npressed, but I am unable to prevent the grid from reverting to column1 line1.  By using the method GET_CURRENT_CELL I can find out the column, but it does not return me the row.   I have tried putting this column id into  SET_CURRENT_CELL_VIA_ID, as suggested by Naimesh above, and calling this from the AFTER_USER_COMMAND method, but it does not effect how the grid displays.    
    Any further advice would be very welcome.

  • IOException - WEB8001 - when writing to servlet response outputstream

    I am attempting to port a Java servlet application from iws 6.0 to 6.1, sp2, but am encountering IOExceptions during load testing.
    The servlet composes its response in a character array, and then calls the following method to write the characters to the servlet response object:
    static void writeResponse( HttpServletResponse response, char[] chars, String charset ) throws IOException {
        OutputStreamWriter writer =
            new OutputStreamWriter( response.getOutputStream(), charset );
        char[] buffer = new char[8192];
        CharArrayReader reader = new CharArrayReader( chars );
        int read = 0;
        while(( read = reader.read( buffer, 0, 8192 )) > -1 )
           writer.write( buffer, 0, read );
        writer.close();
    }Under moderate load (2-4 simultaneous connections), an IOException will sometimes be thrown. The stack dump is:
    java.io.IOException: WEB8001: Write failed
         at com.iplanet.ias.web.connector.nsapi.NSAPIConnector.write(NSAPIConnector.java:750)
         at com.iplanet.ias.web.connector.nsapi.NSAPIResponseStream.write(NSAPIResponseStream.java:74)
         at org.apache.catalina.connector.ResponseBase.flushBuffer(ResponseBase.java:765)
         at org.apache.catalina.connector.HttpResponseBase.flushBuffer(HttpResponseBase.java:779)
         at com.iplanet.ias.web.connector.nsapi.NSAPIResponse.flushBuffer(NSAPIResponse.java:127)
         at org.apache.catalina.connector.ResponseBase.write(ResponseBase.java:738)
         at org.apache.catalina.connector.ResponseStream.write(ResponseStream.java:325)
         at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:336)
         at sun.nio.cs.StreamEncoder$CharsetSE.implWrite(StreamEncoder.java:395)
         at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:136)
         at java.io.OutputStreamWriter.write(OutputStreamWriter.java:191)
         at eng.pubs.servlet.DocServlet.writeResponse(DocServlet.java:1034)The exception is not thrown consistently for any given URL, but appears to be random. When run under iws 6.0, the exceptions do not occur at all. Most of the time, the method will have written 32K
    of data when the exception is thrown.
    Any clues about how I might debug this?

    What are you using as your test client?The test client is WebStone 1.0. WebStone always downloads the whole response, and reports the size of the response in bytes. From this I can see that when the IO exception occurs, webstone is unable to read the whole response, as it reports a smaller size.
    So, I do not think the problem is that the client has prematurely aborted its download. WebStone doesn't work that way. I think something has gone awry on the server side, and this worries me.

  • How to run servlet by using main?

    How can I use main to run servlet?
    I cannot put request and response object into doGet(request, response) method
    I want this because I want to run this servlet daily and I plan to put it in cron job
    Calvin

    Hi
    Perhaps you cannot run servlet without using browser. But you can make that program as an application in order to run in Dos or Unix shell.
    But still you can run servlet without using browser How?
    You can debug servlets with the same jdb commands you use to debug an applet or an application. The JavaTM Servlet Development Kit (JSDK) provides a standalone program
    called servletrunner that lets you run a servlet without a web browser. On most systems, this program simply runs the java sun.servlet.http.HttpServer command. You
    can, therefore, start a jdb session with the HttpServer class.
    A key point to remember when debugging servlets is that Java Web server and servletrunner achieve servlet loading and unloading by not including the servlets directory on
    the CLASSPATH. This means the servlets are loaded using a custom classloader and not the default system classloader.
    Running servletrunner in Debug Mode
    Running Java Web ServerTM in Debug Mode
    Running servletrunner in Debug Mode
    In this example, the servlets examples directory is included on the CLASSPATH. You can configure the CLASSPATH for debug mode as follows:
    Unix
    $ export CLASSPATH=./lib/jsdk.jar:./examples:$CLASSPATH
    Windows
    $ set CLASSPATH=lib\jsdk.jar;examples;%classpath%
    To start the servletrunner program you can either run the supplied startup script called servletrunner or just supply the servletrunner classes as a parameter to jdb. This
    example uses the parameter to servletrunner.
    $ jdb sun.servlet.http.HttpServer
    Initializing jdb...
    0xee2fa2f8:class(sun.servlet.http.HttpServer)
    > stop in SnoopServlet.doGet
    Breakpoint set in SnoopServlet.doGet
    > run
    run sun.servlet.http.HttpServer
    running ...
    main[1] servletrunner starting with settings:
    port = 8080
    backlog = 50
    max handlers = 100
    timeout = 5000
    servlet dir = ./examples
    document dir = ./examples
    servlet propfile = ./examples/servlet.properties
    To run SnoopServlet in debug mode, enter the following URL in a browser where yourmachine is the machine where you started servlet runner and 8080 is the port number
    displayed in the settings output.
    http://yourmachine:8080/servlet/SnoopServlet
    In this example jdb stops at the first line of the servlet's doGet method. The browser will wait for a response from your servlet until a timeout is reached.
    main[1] SnoopServlet: init
    Breakpoint hit: SnoopServlet.doGet (SnoopServlet:45)
    Thread-105[1]
    We can use the list command to work out where jdb has stopped in the source.
    Thread-105[1] list
    41 throws ServletException, IOException
    42 {
    43 PrintWriter out;
    44
    45 => res.setContentType("text/html");
    46 out = res.getWriter ();
    47
    48 out.println("<html>");
    49 out.println("<head>
    <title>Snoop Servlet
    </title></head>");
    Thread-105[1]
    The servlet can continue using the cont command.
    Thread-105[1] cont
    Running Java Web Server in Debug Mode
    The JSDK release does not contain classes available in the Java Web server and it also has its own special servlet configuration. If you cannot run your servlet from
    servletrunner, then the other option is to run the Java Web server in debug mode.
    To do this add the -debug flag for the first parameter after the java program. For example in the script bin/js change the JAVA line to look like the following. In releases prior
    to the Java 2 platform release, you will also need to change the program pointed to by the variable $JAVA to java_g instead of java.
    Before:
    exec $JAVA $THREADS $JITCOMPILER $COMPILER $MS $MX \
    After:
    exec $JAVA -debug $THREADS $JITCOMPILER
    $COMPILER $MS $MX \
    Here is how to remotely connect to the Java Web Server. The agent password is generated on the standard output from the Java Web Server so it can be redirected into a file
    somewhere. You can find out where by checking the Java Web Server startup scripts.
    jdb -host localhost -password <the agent password>
    The servlets are loaded by a separate classloader if they are contained in the servlets directory, which is not on the CLASSPATH used when starting the Java Web server.
    Unfortunately, when debugging remotely with jdb, you cannot control the custom classloader and request it to load the servlet, so you have to either include the servlets
    directory on the CLASSPATH for debugging or load the servlet by requesting it through a web browser and then placing a breakpoint once the servlet has run.
    In this next example, the jdc.WebServer.PasswordServlet is included on the CLASSPATH when Java Web server starts. The example sets a breakpoint to stop in the service
    method of this servlet, which is the main processing method of this servlet.
    The Java Web Server standard output produces this message, which lets you proceed with the remote jdb session:
    Agent password=3yg23k
    $ jdb -host localhost -password 3yg23k
    Initializing jdb...
    > stop in jdc.WebServer.PasswordServlet:service
    Breakpoint set in jdc.WebServer.PasswordServlet.service
    > stop
    Current breakpoints set:
    jdc.WebServer.PasswordServlet:111
    The second stop lists the current breakpoints in this session and shows the line number where the breakpoint is set. You can now call the servlet through your HTML page. In
    this example, the servlet is run as a POST operation
    <FORM METHOD="post" action="/servlet/PasswordServlet">
    <INPUT TYPE=TEXT SIZE=15 Name="user" Value="">
    <INPUT TYPE=SUBMIT Name="Submit" Value="Submit">
    </FORM>
    You get control of the Java Web Server thread when the breakpoint is reached, and you can continue debugging using the same techniques as used in the Remote Debugging
    section.
    Breakpoint hit: jdc.WebServer.PasswordServlet.service
    (PasswordServlet:111) webpageservice Handler[1] where
    [1] jdc.WebServer.PasswordServlet.service
    (PasswordServlet:111)
    [2] javax.servlet.http.HttpServlet.service
    (HttpServlet:588)
    [3] com.sun.server.ServletState.callService
    (ServletState:204)
    [4] com.sun.server.ServletManager.callServletService
    (ServletManager:940)
    [5] com.sun.server.http.InvokerServlet.service
    (InvokerServlet:101)
    A common problem when using the Java WebServer and other servlet environments is that Exceptions are thrown but are caught and handled outside the scope of your servlet.
    The catch command allows you to trap all these exceptions.
    webpageservice Handler[1] catch java.io.IOException
    webpageservice Handler[1]
    Exception: java.io.FileNotFoundException
    at com.sun.server.http.FileServlet.sendResponse(
    FileServlet.java:153)
    at com.sun.server.http.FileServlet.service(
    FileServlet.java:114)
    at com.sun.server.webserver.FileServlet.service(
    FileServlet.java:202)
    at javax.servlet.http.HttpServlet.service(
    HttpServlet.java:588)
    at com.sun.server.ServletManager.callServletService(
    ServletManager.java:936)
    at com.sun.server.webserver.HttpServiceHandler
    .handleRequest(HttpServiceHandler.java:416)
    at com.sun.server.webserver.HttpServiceHandler
    .handleRequest(HttpServiceHandler.java:246)
    at com.sun.server.HandlerThread.run(
    HandlerThread.java:154)
    This simple example was generated when the file was not found, but this technique can be used for problems with posted data. Remember to use cont to allow the web server
    to proceed. To clear this trap use the ignore command.
    webpageservice Handler[1] ignore java.io.IOException
    webpageservice Handler[1] catch
    webpageservice Handler[1]
    I hope this will help you.
    Thanks
    Bakrudeen

  • Delaying server [servlet] response

    I'm using AJAX to update my div tag telling me if a username is valid / invalid. I've tried using wait(long) to pause the doGet thread , init thread and start thread but I get the following warning:
    "Current thread not owner"
    Who's the owner or "main" thread? I've also tried respone.wait and request.wait but the same exception is being thrown. Or is there a different way to delay the servlets response, or is this impossible with XML?
    Thanks,
    -ls6v

    it sort of sounds to me like you're used to thick
    client gui programming - not sure why - but trying to
    control the number of hits to a database in a web
    app
    by messing with javascript controls smells a bit (it
    may be because of the nature of AJAX which I admit I
    haven't used). Embedding in depth knowledge of the
    back end in the front end is always a bit odd.
    Would it not be better to implement this sort of
    control (as in programmatic logic) server side ? Is
    there a need for an AJAX request to hit a database
    each time ? Might create an awful load (maybe this is
    what you're addressing). Perhaps some cached server
    side data structure might be of better use than
    trying to hack the front end in this fashion.Basically I'm going to use AJAX for the its look and feel, even if it isn't necessary. The load was what the other person brought up so I thought I could test it by slowing things down because I can't simulate 1,000 simultaneous connections. I'm not really worried about it because I figured that AJAX might actually help an over loaded server. If the server is too busy to respond I would catch that in my JS and and try to request it again after a few seconds. req.open("GET", url2, true);
    req.onreadystatechange = callback;
    req.send(null);
    function callback()
    if (req.readyState == 4)
            if (req.status == 200)
    else if(){...}
    }So if it comes back busy it'll wait before requesting the server again. I'll use DOM to manipulate the original login.html page so the input field will call a different JS function if it fails the first time. There's a bit more but that's what I'm going to try to do and hopefully bypassing this slow down testing won't matter.

  • How to pass servlet parameter using encodeURL function in JSP page

    Hi!!!
    I have a very urgently problem.
    in my JSP I have this:
    <IMG border="0" src='<%=response.encodeURL("/MyImageServlet")%>'>
    In this way, my servlet works fine (and I have in my page my blob-image).
    But I have to pass to my servlet a list of dynamic parameter. I have tried all the possibilities like:
    <IMG border="0" src='<%= (response.encodeURL("/MyImageServlet") + "?Param_name=" + sessionBean.getParamValue() + "&anotherParam" + sessionBean.getAnotherParamValue())%>'
    but nothing....
    In my servlet I use the init function to retrieve the initial parameters(defined in my web.xml file) in this way:
    public void init(ServletConfig config) throws ServletException
    super.init(config);
    myParam = getInitParameter( "name_of_param");
    but I retrieve only the default value (-1).
    How to pass to my servlet the parameters? Please help me!
    Excuse me for my english,
    thank you for your help!

    Hi!
    Thanks for your reply!
    I have tried this solution but it doesn't work!
    When I do getInitParameter in the init function, the servlet take the default values...
    Maybe I have wrote something wrong?
    Excuse me for my english,
    Thanks

Maybe you are looking for

  • Short dump while loading data in to Bw using Process Chain.

    got the problem in the Production System.......... I won't get any confirmation from my customer to debug the program in the Poduction. In BW I have to load the data every day using the process chain. in the monitor I can't find any problem every thi

  • Ipod mini detected, bu no driver found

    I´ve installed the latest Itunes version on my new pc. My Ipod runns with the latest update. When I connect the Ipod with the PC, the PC detect the Ipod but could not find the Ipod mini driver. So a popup appers and ask my if i want to look for the d

  • Multithreaded access to TopLink API

    Hi, If several threads need to access the TopLink API for a given Project, what can be shared and what can't be shared or must be synchronized? Should a different DatabaseSession be used for each thread?

  • Sharing video; unable to publish to YouTube and cannot compress enough to send as attachment in email

    I have followed the instructions for sharing but I am unable to publish  3 minute video (and it is not in HD).  What am I missing?  I also cannot seem to compress it enough to send as an attachment in an email.  Any suggestions?

  • Narrative reports not showing beyond first page if printed out

    I'm trying to print out a CO1/CO2 record using the 'printer friendly' function. Although everything appears fine on screen, all narrative reports in the related information sections do not appear in the printout if it extends to more than 1 page. Thi