Filters

  • Filters are java components that can be used to process or intercept request from client to server before the request is sent to filter or to process responses after the servlet has completed its job and before this response reaches the client.
  • Deployment descriptor defines when to kick in filters.
  • Filters implement the Filter java interface.
  • Filters when used to intercept request can perform security checks, reformat request headers or bodies and can audit or log requests
  • Filters when used to process responses can compress the response stream, alter the response stream and can create a different response stream together.
  • Filters can also be chained together. Deployment descriptor will define the order in which they run.
  • Filters have a doFilter() method that the implementing class overwrites.
  • The container manages the life cycle of the filter. In many ways, Filter is like Servlet in characteristic.
  • Every filter can have access to ServletContext from its FilterConfig Object.

Filter’s Life Cycle:

  • Every filter must implement init(), do Filter() and destroy() methods.
  • Init(): This is where you do any set up tasks. The most common implementation is as follows

Public void init(FilterConfig config) throws ServletException{

// you can store config object of type FilterConfig in a variable to use it     //latter.you will get the servlet context from this config object

}

  • doFilter(): This is the method that gets called when ever the container determines that the filter should be applied to cureent request or response. It takes three arguments. They are ServletRequest, a ServletResponse and a FilterChain.This is where you implement your filter functionality.
  • Destroy(): called when the container decides to remove the instance. You can do any clean up work here.

How to Declare and order Filters?

Declaring a filter

<filter>

<filter-name>myFilter</filter-name>

<filter-class>com.mydomain.MyFilter</filter-class>

<init-param>

<param-name>user</param-name>

<param-value>sukumarvaddi</param-value>

</init-param>

</filter>

Declaring a filter mapping to a URL pattern

<filter-mapping>

<filterName>myFilter</filterName>

<url-pattern>*.do</url-pattern>

</filter-mapping>

Declaring a filter mapping to a servlet name

<filter-mapping>

<filter-name>myFilter<filter-name>

<servlet-name>com.myDomain.MyServlet</servlet-name>

</filter-mapping>