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.6. Optionally Blocking a Request with a Filter

Problem

You want the option to block a request with a filter.

Solution

Do not call the FilterChain object's doFilter( ) method inside of the filter. Output the response to the client inside of the filter's doFilter( ) method instead.

Discussion

A filter blocks a request from getting to a web component, such as a servlet, JSP, or HTML page, by never calling FilterChain.doFilter( ) inside the filter's own doFilter( ) method.

The BlockFilter class in Example 19-8 attempts to authenticate the user based on a request parameter. If the authentication fails, the filter uses the response object to output a response to the client, and the request is effectively blocked from reaching the requested servlet. A filter can output the final response to the client, not just initiate its filtering tasks.

Example 19-8. A filter optionally blocks the request and issues a response itself

package com.jspservletcookbook;import java.io.PrintWriter;
import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

public class BlockFilter implements Filter {
    
    private FilterConfig config;
    
    /** Creates new BlockFilter */
    public BlockFilter( ) {}
    
    public void  init(FilterConfig filterConfig)  throws ServletException{
    
        this.config = filterConfig;
    }
    
  public void  doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
 
    HttpServletRequest req = null;
    boolean authenticated = false; PrintWriter out ...

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