1/31/2009

Filter

javax.servlet.Filter intercepts a request and manupulates a ServletRequest object or a ServletResponse object.
e.g.
・Filter can intercepts a request to the application and encode a string.
・Total management using Filters

web.xml definition
You have to define filters on the web.xml.
e.g.
<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>filter.MyFilter</filter-class>
    <init-param>
            <param-name>EncodeName</param-name>
            <param-value>Shift_JIS</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

filter-name : The name of the Filter class
fiter-class : The fully qualified name of the Filter class
init-param : Initial parameter. It can be reached by FilterConfig.
url-pattern : Specifies the URL. An asterisk (*) can be used.
dispatcher : Specifies REQUEST,FORWARD,INCLUDE,ERROR. The default is REQUEST.



Methods in the Filter interface
public void init(FilterConfig config)

public void doFilter(ServletRequest request,
    ServletResponse response, FilterChain chain)

public void destroy()

<Sample>
public class MyFilter1 {
    private FilterConfig config = null;
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)req;
        String url = request.getRequestURI();

        /* Do something, for example, counting up in a database */
    
        /* to the next filter */
        chain.doFilter(req,res);
    }
    public void destroy() {}
}

    <filter>
        <filter-name>MyFilter1</filter-name>
        <filter-class>filter.MyFilter1</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>MyFilter1</filter-name>
        <url-pattern>/MyFilter1</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>