Java Servlet Filter
Filters are part of Servlet API Since 2.3. Like a Servlet, a filter object is instantiated and managed by the Container and follows a life cycle that is similar to that of a Servlet. A Servlet has 4 stages as depicted below
These stages are similar to a servlet’s Instantiate, Initialize, Filter, destroy. The filter is used to pre-process the request and Post-processing the response. A Filter is a java object that performs the Filtering task on either the request to a resource or on the response from a resource or both.
Some of the Applications using Filter
- Logging and Auditing Filters
- Image Conversion Filters.
- Data Compression Filters.
- Encryption and Decryption Filters.
Interfaces belong to Filters.
All these interfaces are available in javax.Servlet Package
- A Filter is an interface.
- Every Filter must be inherited from this interface.
- It provides lifecycle methods
|init(FilterConfig filterconfig)||Called by the web container to indicate to a filter that it is being placed into service|
|doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)||It is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.|
|destroy()||to indicate to a filter that is being out of service.|
- Filter information must be provide inside web.xml .
- Filter is mapped with one or more than one servlet.
FilterChain is an interface, which is implemented by a servlet container. Filters use the FilterChain to invoke the next filter in the chain, or if the calling filter is the last filter in the chain to invoke the resource at the end of the chain.
Causes the next Filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked.
Return Type: Void
- HttpServletRequest request
- HttpServletResponse response
void doFilter(HttpServletRequest request, HttpServletResponse response)
We can Develop three types of filters as listed below as follows:
(1) Request Filter: Contain only pre-request Processing logic.
Example: Request count filter, Authentication filter, Authorization filter, Validation filter and etc.
(2) Response Filter: Contain only Post-response generation logic.
Example: Conversion filter, Compression filter and etc.
(3) Request-Response Filter: Contain both pre-request and post-response generation logic.
Example: Performance Test filter.
Implementation: Example of Filter
A. File: index.html
B. File: MyBlockFilter.java
C. File: HelloServlet
D. File: web.xml
Output: If our PC IP address is “127.0.0.1″ we cannot visit the website