O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

19.7. Filtering the HTTP Response

Problem

You want to change the response with a filter while the client request is en route to the servlet.

Solution

Change the javax.servlet.ServletResponse inside the filter's doFilter( ) method by wrapping the response with your own object. Then pass the wrapped response as a parameter into the FilterChain.doFilter( ) method.

Discussion

Here are the steps for changing a response with a filter and a wrapper class:

  1. Create a Java class that extends javax.servlet.http. HttpServletResponseWrapper.

  2. Place this class, including its package-related directories, in WEB-INF/classes.

  3. Use the wrapper class in the filter to wrap the response object, which is a parameter to the filter's doFilter( ) method.

  4. Call the chain.doFilter( ) method with the wrapped response as a parameter.

Example 19-9 shows the Java class that we will use to wrap the response object.

Note

If you are just making a simple response change, you do not have to go to the trouble of using an HttpServletResponseWrapper class. This code inside of a filter's method adds a header to the response, then calls the chain.doFilter( ) method with the altered response:

if(response instanceof HttpServletResponse){
    //cast to HttpServletResponse  to call 
    //addHeader
    myHttpResponse =
       ((HttpServletResponse)response);

 myHttpResponse.addHeader("WWW-Authenticate",
         "BASIC realm=\"Admin\"");

   chain.doFilter(request,response); }

The ResponseWrapper class contains the skeleton of a new method named getWebResource. I want ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required