Servlet Filter
Servlet Filter
- Payal Chaudhari
Working of Web API (with servlets)
Filters for Servlet
Filters :
• A Servlet filter is an object that can intercept HTTP requests targeted
at your web application.
• A servlet filter can intercept requests both for servlets, JSP's, HTML
files or other static content,
Usage of Filters
Filters for Servlet
Filters :
• A filter is an object that is invoked at the preprocessing and
postprocessing of a request.
• It is mainly used to perform filtering tasks such as conversion, logging,
compression, encryption and decryption, input validation etc.
• The servlet filter is pluggable, i.e. its entry is defined in the web.xml
file, if we remove the entry of filter from the web.xml file, filter will be
removed automatically and we don't need to change the servlet.
• So maintenance cost will be less.
• More than one Filter can also work in chain mode.
More than one filters can work in Chain
Usage of Filter
• Recording all incoming requests
• Logs the IP addresses of the computers from which the requests
originate
• Conversion
• Data compression
• Encryption and decryption
• Input validation etc.
Advantages of Filter
• Filter is pluggable.
• One filter don't have dependency onto another resource.
• Less Maintenance
Creating Filters
To work with Filters, we need following
• 3 Interfaces
• jakarta.servlet.Filter <- You have to implement it
• jakarta.servlet.FilterChain
• jakarta.servlet.FilterConfig
• 2 classes
• jakarta.servlet.annotation.WebFilter (Optional if you are going to work with web.xml)
• jakarta.servlet.http.HttpFilter <- You have to extend it
Filter Lifecycle
• Initialization (using Init Method)
• Service (using doFilter Method)
• Destroy (using destroy Methos)
Init Method
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
• We will see the Filter creation process step by step from next slide
<- Right click on Project
name
<- Select New
<- Select Filter
Write Package Name
Write Class
Name
• In the import section you will see following that will cause errors