9.7. Blocking the Response

Up to now, all the filters discussed have concluded their doFilter methods by calling the doFilter method of the FilterChain object. This approach is the normal one—the call to doFilter invokes the next resource in the chain (another filter or the actual servlet or JSP page).

But what if your filter detects an unusual situation and wants to prevent the original resource from being invoked? How can it block the normal response? The answer is quite simple: just omit the call to the doFilter method of the FilterChain object. Instead, the filter can redirect the user to a different page (e.g., with a call to response.sendRedirect) or generate the response itself (e.g., by calling getWriter on the response and sending output, just as with a regular servlet). Just remember that the first two arguments to the filter’s main doFilter method are declared to be of type ServletRequest and ServletResponse. So, if you want to use methods specific to HTTP, cast these arguments to HttpServletRequest and HttpServletResponse, respectively. Here is a brief example:

public void doFilter(ServletRequest request, 
                     ServletResponse response, 
                     FilterChain chain) 
    throws ServletException, IOException {
  HttpServletRequest req = (HttpServletRequest)request; 
  HttpServletResponse res = (HttpServletResponse)response; 
  if (isUnusualCondition(req)) {
						res.sendRedirect("http://www.somesite.com");
						} else {
						chain.doFilter(req,res);
						} 
} 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.93.0