[ Team LiB ] |
![]() ![]() |
Recipe 19.7 Filtering the HTTP ResponseProblemYou want to change the response with a filter while the client request is en route to the servlet. SolutionChange 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. DiscussionHere are the steps for changing a response with a filter and a wrapper class:
Example 19-9 shows the Java class that we will use to wrap the response object.
The ResponseWrapper class contains the skeleton of a new method named getWebResource. I want to show the mechanics of wrapping the response in a filter, so have kept this wrapper class very simple. All the other HttpServletResponse-derived method calls are delegated to the wrapped response object, which is the convenience of extending HttpServletResponseWrapper. Example 19-9. An HttpServletResponseWrapper class for use in a filterpackage com.jspservletcookbook; import javax.servlet.*; import javax.servlet.http.HttpServletResponseWrapper; import javax.servlet.http.HttpServletResponse; public class ResponseWrapper extends HttpServletResponseWrapper{ public ResponseWrapper(HttpServletResponse response){ super(response); } public String getWebResource(String resourceName){ //Implement a method to return a String representing //the output of a web resource //See Recipe 13.5 return "resource"; //for the compiler... }// getWebResource } Example 19-10 shows the doFilter( ) method inside the filter that uses this ResponseWrapper class.
Example 19-10. The doFilter( ) method of a filter that uses a HttpServletResponseWrapper classpublic void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws java.io.IOException, ServletException {
if(response instanceof HttpServletResponse){
chain.doFilter(request,
new ResponseWrapper((HttpServletResponse)response));
} else {
chain.doFilter(request,response);
}
}//doFilter
The code calls the chain.doFilter( ) method and passes in the wrapped response as a parameter. The web resource at the end of the chain has access to the customized response object and can call the additional method the response wrapper class has defined. All the other method calls on the HttpServletResponse object, such as getWriter( ) or getOutputStream( ), are passed through to the wrapped response object. See AlsoRecipe 7.9 on using a filter to read request parameter values; Recipe 11.11 on using a filter to monitor session attributes; Recipe 18.3 on using a filter to alter the request; Recipe 19.1-Recipe 19.4 on mapping filters to web components; Recipe 19.5 on configuring init parameters for a filter; Recipe 19.6 on blocking a request; Recipe 19.8 on using filters with RequestDispatchers; Recipe 19.9 on using filters to check request parameters; Recipe 19.10 on using filters to disallow requests from certain IP addresses. |
[ Team LiB ] |
![]() ![]() |