Request.setHeader in servlet filter

Hi there,
I am working on servlet filter to filter HttpServletRequest before sending it to the original servlet.
The original servlet expects some content posted in the body of HttpServletRequest object.
In my servlet filter, I need to modify this content (already done) and then doFilter to the origin.
And here is the problem:
The original servlet uses HTTP header's content-length value to read the entire content posted. But if I modify this content in my filter, it will never get correct content of the request.
Unfortunately the original servlet is black boxed and there is no way to modify it.
Is there any way to modify HTTP headers of HttpServletRequest in servlet filter?
Thank you for any suggestions,
mato_v

Hum... ServletRequest.getHeader is read only, so you can't change them. There few solution you may try though:
* Try create another wrapper instance of ServletRequest inside your filter and forward it to your black box servlet. You might have to wrote your own implementation to manipulate those Headers.
* How about after you changed your data, redirect/post to your black box with the correct content? Use java.net.HttpURLConnection or a java Http client to do fancy posting if needed.
Hope these helps.

Similar Messages

  • Servlet Filter - Reading Request Error

    I have a servlet filter that sits in front of a webservice servlet (AXIS) - what I want the filter to do is to look at the content of the ServletRequest and if a particular string is located in the request, I want to call another service. Everything works just fine except (isin't there always an execept) that when I execute the following code in the filter:
    BufferedReader inReader = request.getReader();
    String line = null;
    StringBuffer sbuf = new StringBuffer();
    // Read the current request into a buffer
    while((line = inReader.readLine()) != null) {
    sbuf.append(line);
    sbuf.append("\n\r");
    if (sbuf.toString().indexOf("mystring") > -1) {
    // I do some code
    } else {
    chain.doFilter(request, wrapper);
    When I execute this code, at the chain.doFilter I get an "java.lang.IllegalStateException: getReader() has already been called for this request"
    I know that this is because I obtained the Reader from the request. But my question is - How can I look at the request string so that I can evaluate it and not have this exception thrown..
    Thx in advance...

    My guess is that when you do the chain.doFilter you pass the request to another resource that then tries to access the request.getInputStream method.
    From the JavaDocs:
    getReader
    public java.io.BufferedReader getReader()
    throws java.io.IOException
    Retrieves the body of the request as character data using a BufferedReader. The reader translates the character data according to the character encoding used on the body. Either this method or getInputStream() may be called to read the body, not both.
    Returns:
    a BufferedReader containing the body of the request
    Throws:
    java.io.UnsupportedEncodingException - if the character set encoding used is not supported and the text cannot be decoded
    IllegalStateException - if getInputStream() method has been called on this request
    java.io.IOException - if an input or output exception occurred

  • Strange behavior when using servlet filter with simple index.htm

    I am new to J2EE development so please tolerate my ignorance. I have a web application that starts with a simple index.htm file. I am using a servlet filter throughout the website to check for session timeout, redirecting the user to a session expiration page if the session has timed out. When I do something as simple as loading the index.htm page in the browser, the .css file and one image file that are associated, or referenced in the file are somehow corrupted and not being rendered. How do I get the filter to ignore css and image files??? Thank you!!
    The servlet filter:
    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class SessionTimeoutFilter implements Filter {
         String[] excludedPages = {"SessionExpired.jsp","index.htm","index.jsp"};
         String timeoutPage = "SessionExpired.jsp";
         public void destroy() {
         public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
              if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
                   HttpServletRequest httpServletRequest = (HttpServletRequest) request;
                   HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                   //httpServletResponse.setHeader("Cache-Control","no-cache");
                   //httpServletResponse.setHeader("Pragma","no-cache");
                   //httpServletResponse.setDateHeader ("Expires", 0);
                   String requestPath = httpServletRequest.getRequestURI();
                   boolean sessionInvalid = httpServletRequest.getSession().getAttribute("loginFlag") != "loggedIn";               
                   System.out.println(sessionInvalid);
                   boolean requestExcluded = false;
                   System.out.println(requestExcluded);
                   for (int i=0;i<excludedPages.length;i++){
                        if(requestPath.contains(excludedPages)){
                             requestExcluded = true;
                   if (sessionInvalid && !requestExcluded){
                        System.out.println("redirecting");
                        httpServletResponse.sendRedirect(timeoutPage);
              // pass the request along the filter chain
              chain.doFilter(request, response);
         public void init(FilterConfig arg0) throws ServletException {
              //System.out.println(arg0.getInitParameter("test-param"));
    The index.htm file (or the relevant portion)<HTML>
    <Head>
    <META http-equiv="Content-Style-Type" content="text/css">
    <LINK href="RTEStyleSheet.css" rel="stylesheet" type="text/css">
    <TITLE>Login</TITLE>
    </HEAD>
    <BODY>
    <FORM NAME="Login" METHOD="POST" ACTION="rte.ServletLDAP"><!-- Branding information -->
    <table width="100%" border="0" cellpadding="0" cellspacing="0">
         <tr>
              <td width="30%" align="left"><img src="images/top_logo_new2.gif">
              </td>
              <td width="37%" align="center"></td>
              <td width="33%" align="right"></td>
         </tr>
    </table>
    My web.xml entry for the filter:     <filter>
              <description>
              Checks for a session timeout on each user request, redirects to logout if the session has expired.</description>
              <display-name>
              SessionTimeoutFilter</display-name>
              <filter-name>SessionTimeoutFilter</filter-name>
              <filter-class>SessionTimeoutFilter</filter-class>
              <init-param>
                   <param-name>test-param</param-name>
                   <param-value>this is a test parameter</param-value>
              </init-param>
         </filter>
         <filter-mapping>
              <filter-name>SessionTimeoutFilter</filter-name>
              <url-pattern>/*</url-pattern>
              <dispatcher>REQUEST</dispatcher>
              <dispatcher>FORWARD</dispatcher>
         </filter-mapping>

    Hi,
    Try adding CSS files and images to the excluded Pages.

  • Set Roles in servlet filter

    How can I set the user's role in the request object in a servlet filter
    so that in my action class, i can query the role using
    request.isUserInRole() and request.getUserPrinciple() methods.
    Any ideas...
    Thanks,

    How can I set the user's role in the request object
    in a servlet filter
    so that in my action class, i can query the role
    using
    request.isUserInRole() and request.getUserPrinciple()
    methods.You may want to check out JAAS in the Creator tutorial:
    http://developers.sun.com/prodtech/javatools/jscreator/ea/jsc2/reference/sampleapps/

  • Servlet filter problem

    I've written a simple servlet filter to intercept a request to another servlet. So when the user tries to access /servlet/ViewMetadata servlet, they first hit InterceptServlet, the filter configured in Tomcat.
    I need to access the name and URL of the target servlet ViewMetada within InterceptServlet but don't know how to do this. I am familiar with HttpServletRequest.getServletPath() but doFilter uses ServletRequest as its argument.
    Can I obtain the target servlet name inside the filter servlet? I know this is probably very basic!
    Arc

    If the filter is invoked by a HttpServletRequest, then the ServletRequest handle you've in the filter is just an instance of HttpServletRequest.
    Cast it back.

  • Memory leak in Servlet Filter handling?

    In Sun Web Server 6.1, I'm finding a memory leak when using servlet filters. I've even created a "no op" servlet filter. When it's registered, every 10000 hits or so to filtered static content will eat up about 5 to 10 MB of RAM. The JVM heap size doesn't increase.
    When I remove the filter, I've hit the same static page on the server 50000 times without seeing an increase in memory usage by the process.
    This is on Windows 2000, and I think the Sun Web Server 6.1 is SP1. I haven't tried SP2 yet.
    For reference, here's the filter I put in:
    public class NoOpFilter implements Filter
    public void init(FilterConfig arg0) throws ServletException {}
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    chain.doFilter(request, response);
    public void destroy() {}
    }

    I found the bug. I get the memory leak if magnus.conf has either or both of the following entries:
    AdminLanguage en
    DefaultLanguage en
    If I delete the entries, the memory leak goes away. I suppose this should get fixed by Sun sometime. Maybe I'll figure out how to officially report the bug later.

  • Servlet Filter

    Hi, all
    I work on a web application running on a Jboss server and i would like to filter all the http request in order to save it in a database. (i save those informations for manage web stats).
    I suppose i may use servlet filter, but i don't know the operation of this
    Does anyone could help me giving some example and the protocol to set up this on the server (file server configuration as web.xml)

    Well here is what I know. I hope it helps.....
    First thing is to create a class that implements the "javax.servlet.Filter" interface. But there are also other Filter interfaces that you could use depending on what you want: Filter, FilterChain, and FilterConfig.
    You have to implement the init(), destroy() and doFilter() methods (I ommitted the arguments).
    But most of your work will be done in the doFilter () method. You could extract request information from one of the arguments in these method and have a datasource connection to save to your back-end.
    Something like :
    public void doFilter( ServletRequest request, ServletResponse responce, FilterChain chain ) throws  ServletException {
          HttpServletRequest httpRequest = (HttpServletRequest) request;
          backEndDelegate.saveInformation(  request.getRemoteAddr(),  request.getRemoteHost() );
          chain.doFilter( request, responce );
    }Second, you need to configure the Filter. In the web.xml file add the following tags:
    <filter>
         <filter-name>StatsFilter</filter-name>
          <description>Logs Web Stats to the back end</description>
         <filter-class>com.yourpackage.StatsFilter</filter-class>
         <!--  you can also pass parameters to the StatsFilter -->
          <!--
           <init-param>
                   <param-name>some parameter</param-name>
                   <param-value>some parameter</param-value>
            </init-param>
            -->
    </filter>
    <filter-mapping>
          <filter-name>StatsFilter</filter-name>
          <filter-pattern>*.jsp</filter-pattern>
    </filter-mapping>That is just a little example. You can associate a filter with a Servlet using the <filter-mapping> tags too. And you can also do filter chains, but I don't feel like going there.
    I sure hope that it was helpful. If not then "RTFM"

  • Accessing Managed Session Bean in Servlet Filter

    I wrote a Servlet Filter to handle user authentication. Now I'm trying to access my Managed Session Bean in the filter in order to save the current user. Unfortunately the Session Bean is created after the Filter executes for the first time.
    I'm trying to access the Session Bean in this way:
    (SessionBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("sessionBean");
    In this case getExternalContext() is equals null.
    Is there any way to create the Session bean before the filter executes or any other ideas how to handle this?
    I already searched around the internet but couldnt figure out something.
    Thanks guys,
    Paul

    Ok, fixed it like this. Works perfect. JSF finds and uses the handmade Session Bean as well.
    if(request.getSession().getAttribute(BeanNames.SESSION_SCOPE_BEAN) == null) {
         SessionBean sessionBean = new SessionBean();
         request.getSession().setAttribute(BeanNames.SESSION_SCOPE_BEAN, sessionBean);
    }Thanks,
    Paul

  • Managed session bean in servlet filter

    Hi,
    Is there a way to get hold of a managed bean with session scope in a servlet filter? The code below throws an error due to the fact that the faces context is null.
    FacesContext facesContext = FacesContext.getCurrentInstance();
    System.out.println("facesContext: " + facesContext); // shows that facesContext is null
    ApplicationFactory appFactory = ApplicationFactory)FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
    Application app = appFactory.getApplication();
    Object obj = app.createValueBinding("user").getValue(facesContext); //throws the error due to the null parameter
    Object obj2 = app.createValueBinding("user"); //results in a valid ValueBindingHere is the faces-config snippet for the managed bean:
    <managed-bean>
        <managed-bean-name>user</managed-bean-name>
        <managed-bean-class>biz.libereco.skemo.info.asl.beans.User</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>For the record, I am using JSF 1.0 Final.
    Thank you,
    Marcel

    wynton_0 wrote:
    Yes, there is a way to get hold of a managed bean with session scope in a servlet filter.
    See here:
    [http://wiki.apache.org/myfaces/AccessFacesContextFromServlet]
    and here:
    [how to access faces context and backing beans in a servlet filter|http://www.thoughtsabout.net/blog/archives/000033.html]
    This makes no utter sense. A JSF session scoped managed bean is under the hood just put as a HttpSession attribute with the managed bean name as key. Guess what, you can just access the HttpSession in Filter by ((HttpServletRequest) request).getSession() and then just call getAttribute() on it. If it isn't there yet, then just do a setAttribute() with a new instance.
    After I get User bean in my Servlet filter, I populate value to this bean, for example:
    user.setLanguage(request.getParameter("locale"));
    The User bean is in session scope. The User bean's language attribute suppose to be same in the whole session scope, but later on, I got null. My question is:
    how to keep this value in session scope?The the session was apparently invalidated/renewed or you manually removed the bean or replaced it by null.
    In the future, please don't resurrect old topics, just start a new topic for each independent problem/question.

  • Null query string in servlet filter with OC4J 10.1.3.1.0

    I have a strange problem with OC4J 10.1.3.1.0. In the servlet filter, while requesting the querystring with HttpServletRequest.getQueryString the result is null, even if it is verified with a sniffer that that query string is there. This happens only with certain requests. The query string is long but nothing very special otherwise.
    Any ideas what might be wrong?
    Thanks,
    Mika

    I got the same problem. I tried in others application servers alternatives and it works. By now i have to change links like this "http://localhost:8888/SIVIUQ/LoadIndex.portal?test=1" for forms using javaScript to send the parameters corresponding to the button pressed. To use buttons instead links is not the better solution due to usability. Any suggestion to solve this problem?
    Thanks
    Javier Murcia
    Yo tengo el mismo problema. He intentado con otros servidores de aplicaciones y funciona. Por ahora tengo que cambiar links como "http://localhost:8888/SIVIUQ/LoadIndex.portal?test=1" por formularios, usando javaScript para enviar los parametros correspondientes al boton presionado. Usar botones en vez de links no es la mejor solucion debido a usabilidad. ¿Alguna sugerencia para resolver este problema?
    Gracias
    Javier Murcia

  • Providing redirects in Servlet filter

    Hi,
    I need to provide serverside redirects in Servlet filter.O tried the below code, But unable to do it.
    Is it possible to do such a thing.
    public void doFilter(ServletRequest req, ServletResponse res,
                   FilterChain chain) throws IOException, ServletException {
              logger.info("Start of RedirectFilter ");
              HttpServletRequest request = (HttpServletRequest) req;
              HttpServletResponse response = (HttpServletResponse) res;
              String requestURI=request.getRequestURI();
              String domainURL=request.getServerName().toLowerCase();
              logger.info("domainName--"+domainName);
              String keywordToBeAppended=domainURL.replaceAll(domainName,"");
              logger.info("url--"+request.getRequestURI());
              logger.info("servername--"+request.getServerName());
              logger.info("keywordToBeAppended-"+keywordToBeAppended);
              String finalURL= request.getScheme()+"://"+domainURL+"/"+keywordToBeAppended+requestURI;
              logger.info("finalURL--"+finalURL);
              RequestDispatcher rd = request.getRequestDispatcher(finalURL);
              rd.forward(request, response);
              logger.info("End of RedirectFilter ");
              chain.doFilter(request, response);
         }

    There is technically a huge difference between "redirect" and "forward". You're doing here forwards. And because you continue the filter chain, you run into problems. You should do either a forward OR continuing the current request unchanged (through the filter chain) OR send a redirect. You cannot do one or more simultaneously.

  • How to conditionally forward a request to a Servlet for processing?

    Hi,
    I am writing a middleware application, where the application receives HTTPRequest from front end, and based on the URL string it will forward the request to one of the servlets which will handle the processing.
    I need ideas about what is the best way to write the forwarding logic. Should it be a Servlet Filter, or an initial Servlet that only does forwarding? Any code samples will be greatly appreciated.
    Thanks.

    This is almost textbook definition of a Controller Servlet. I would use a Servlet that switches on what option needs to be performed and forwards to the proper URL.

  • How to embed servlet filter to an existing website

    I want to make an application using java servlet filters and I want to know the possibility of making this application as an add-on where anyone could take this application as it is and attach it to his website without knowing anything about servletes and with a very low programming or no programming effort, is it possible? If yes how and if no what is the alternative?

    836522 wrote:
    I really cant thank everyone enough for your help, thank you :)
    why not proxy? because I don't want the full functionalities of a proxy, so I thought why not to implement a servlet filter to do my task especially that all what I want to do could be easily implemented using the methods provided in servlets/filters. what I am thinking of now is to install servlet container and make it run in the proxy mode so any request to the website I want to protect will be directed first to the servlet then the servlet decide whether to pass this request to website or not, what do you think of this??I am afraid that will either not work or be overly complicated. The problem is with this
    so any request to the website I want to protect will be directed first to the servlet then the servlet decide whether to pass this request to website or notHow will the servlet pass on the request to the web site? Since it is not part of the other application, it cannot do a forward or include on the resource. Similarly a chain.doFilter() which is the normal way for the Filter to pass the request along to the end resource will not work.
    You can theorotically use a HttpClient from the Filter which will create a new http request to the underlying web site and flush the response received back to the browser. I think using a Proxy is the best bet. I would recommend an apache http server with some custom modules to implement your 'filter' code
    ram.

  • Can java servlet filter capture anchors in URL

    Hi I need to capture the anchor in the URL that is requested by user. For example, if some one clicks http://www.abc.com/somepage.html#intro, I would like to capture all the info in the URL including "intro". Is it possible through the java servlet filter architecture? If so, what API should I use? Some sample code would be very helpful as well. Thanks!!

    No, this is not possible. Anchors are handled by the client (i.e. web browser). The server never sees them.

  • SSO2Ticket within servlet filter - Orionserver

    Hi,
    I need to validate user that already logged in via SAP portal.
    So I get ticket as cookie.
    I read this cookie and try to validate it with SSO2Ticket.java that is JNI wrapper for C application.
    For this I put 2 files in system32 folder: sapssoext.dll and sapsecu.dll and I register first one with regsvr32.
    Now I try to run SSO2Ticket.java and it works perfectly. But I need this functionality inside my login servlet filter.
    So I still use SSO2Ticket.java but in stead of main method I put same calls into may filter.
    It seams to load sapssoext.dll but what ever method I call I get:
    java.lang.UnsatisfiedLinkError
    Here is method that performs calls. Method is called from filter doFilter method.
    There is SSO2Ticket.java attached here.
    private void checkSAPTicket(HttpServletRequest request) throws Exception
    System.out.println("checkSAPTicket");
    //Ticket is hardcoded and valid
    String ticket="AjExMDAgABNwb3J0YWw6U0VEQVZJRFNTT05QiAATYmFzaWNhdXRoZW50aWNhdGlvbgEADFNFREFWSURTU09OUAIAAzAwMAMAA0hTMQQADDIwMDYxMjE1MDgwOQUABAAAAAgKAAxTRURBVklEU1NPTlD/APUwgfIGCSqGSIb3DQEHAqCB5DCB4QIBATELMAkGBSsOAwIaBQAwCwYJKoZIhvcNAQcBMYHBMIGAgEBMBMwDjEMMAoGA1UEAxMDSFMxAgEAMAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wNjEyMTUwODA5NTFaMCMGCSqGSIb3DQEJBDEWBBRhLnWWaKW8yXyGSrs6gBTC97XnlTAJBgcqhkjOOAQDBC8wLQIUQrgjCpKQeEScuFP7rGWO7V76b5ICFQCT0WhSpqIB11L+HVLmyAjcWeUlw==";
    // get PAB (public key) of issuing system. It is in root of my app server
    File pab=new File("verify.pse");
    String pabFilePath=pab.getAbsolutePath();
    System.out.println("pabFilePath="+pabFilePath);
    Object [] o=null;
    File sapsecu=new File("sapsecu.dll");
    String ssf_library=sapsecu.getAbsolutePath();
    System.out.println("ssf_library="+ssf_library);
    try
    String version =SSO2Ticket.getVersion();
    //String ssf_library="sapsecu.dll";
    if(!SSO2Ticket.init(ssf_library)) {
    System.out.println ("Could not load library: " + ssf_library);
    return;
    System.out.println("evalLogonTicket call...");
    // Validate logon ticket.
    o = SSO2Ticket.evalLogonTicket (ticket, pabFilePath, null);
    } catch (Exception e) {
    System.out.println(e);
    } catch (Throwable te) {
    System.out.println(te);
    System.out.println("evalLogonTicket call ended...");
    And the log I get when I run this:
    checkSAPTicket
    pabFilePath=C:\project\GSS\orion-2.0.2\verify.pse
    ssf_library=C:\project\GSS\orion-2.0.2\sapsecu.dll
    SAPSSOEXT loaded.
    static part ends.
    java.lang.UnsatisfiedLinkError: getVersion
    evalLogonTicket call ended...
    Could not validate SAP login ticket from HTTP Header.
    If I omit call SSO2Ticket.getVersion(); than the same exception is for SSO2Ticket.init(ssf_library).

    Hi,
    I think java.lang.UnsatisfiedLinkError means that it cannot find the .dll files.
    I am not sure it will find them even if the are registered with regsvr32.
    Have you tried placing the .dll files somewhere in the classpath ?
    Dagfinn

Maybe you are looking for

  • Can I change the File name of pics when capturing with iPhoto?

    Hi, I am a new user of Macbook and Mac OS, so, maybe this is a stupid issue. I have a sony cybershot and I was wondering if when I capture my pics from the camera with iPhoto I could change the name of the picture file?....or the filename will always

  • ITunes 8 on Leopard 10.5.7 won't play any songs

    Hi, So I recently backed up my whole computer (I was running 10.4). I did a fresh install of Leopard and then I copied all my songs to the new installation and let iTunes 8 discover the songs on my computer. They have all been successfully copied to

  • I photo 09 disappeared photos after import

    After photographing my daughters 6th birthday party , I imported the photos to iphoto.All seemed fine and I chose to delete photos from my camera when asked. A problem with iphoto occurred and the photos have gone from both my camera and iphoto libra

  • RESTORING BACKUP FROM Z10 TO Q10 AND OUTLOOK ISSUE!

    Hello Everyone!                              just yesterday I got new blackberry q10 and now its been 8 hours am searching and trying to restore my z10 backup to q10 and am getting error says (incompatible device restore) please need help and I wante

  • I can't get tabs to work, can't open with mouse, can't close only in groups does it work

    I was forced to upgrade hate it, lost most of my apps, can't get tabs to work, can't change tabs with mouse, can't close tabs, UNLESS i go to the tab group and then I have a button to close the tab or change tabs but that is a huge pain. Yes i have o