Servlets - Intercepting Filter

Intercepting Filter


Definition
A pluggable component design to intercept incomming requests and outgoing responses, provide common services in a standard manner (independently) without changing core processing code.
Where to use & benefits
  • Logging and authentication.
  • Enhance security.
  • Add additional function to existing web application.
  • Decorate main process.
  • Debug.
  • Pre-processing or post-processing for specific clients.
  • Uncompress incoming request.
  • Convert input encoding schema.
  • Being added or removed transparently or declaratively and triggered automatically
  • Improve reusability
  • Deployment-time composability
  • Each filter is loosely coupled
  • Inefficient for information sharing.
  • Related patterns include
    • Front Control better suited to handling core processing.
    • Template good for template filter strategy
    • Decorator providing for dynamically pluggable wrappers.
Example
To create a basic filter, you need to:
  1. implement Filter interface
  2. implement doFilter method
  3. call doFilter from FilterChain object
  4. register the filter with the appropriate servlets and JSP pages
  5. Mapping the filter to specific pages
  6. disable the invoker servlet
General skeleton program
import javax.servlet.*;
import javax.servlet.http.*;

public class MyFilter implements Filter {
    public void doFilter(ServletRequest request,
                        ServletResponse resonse,
                        FilterChain chain)
                throws ServletException, IOException {
   

         //work on request and response

        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {
        //work on config
    }

    public void destroy() {
        //work on clean up
    }
}      
Register and filter mapping
//in web.xml file
<web-app>
...
Before the servlet description
    <filter>
        <filter-name>MyFilter</filter-name>
        <display-name>MyCoolFilter</display-name>
        <description>This is my cool filter</description>
        <filter-class>somePackage.MyFilter</filter-class>
        <init-param>
            <param-name>yyy</param-name>
            <param-value>/xxx/zzz</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/xxx.jsp</url-pattern>
    </filter-mapping>

<!-- also apply to another servlet -->
    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <servlet-name>xxx</servlet-name>
    </filter-mapping>
...
</web-app>
You may use filter mapping and servlet mapping in web.xml file to diable the invoker servlet to apply the filter.