Updated March 27, 2023
Introduction to Servlet Filter
The filter is a server-side component which is used to pre-process and post-process client request. Filters are mainly used to perform the filter task such as server-side logging, authentication, and authorization, input validation, etc. the servlet is pluggable-meaning the entry is defined in the web.xml file if entry is removed from web.xml, then filter will be removed automatically.to create filter, it must implement javax.servlet.Filter interface. Since servlets are written in highly portable Java language, and it follows the standard framework. Hence it provides means to create sophisticated server extensions in server and operating systems in an independent way.
Why do We Need Servlet Filters?
In certain situations where we want to manage user sessions in web applications, with some restrictions like making sure that the resources are accessible only when the user session is valid, this task is achieved using servlet session attributes. this approach is simple, but if the number of servlets and js ps, it becomes hard to maintain because of redundant code. to avoid these complications, we make use of servlet filters.
Following are the list of the task we can perform with servlet filters:
- Server-side logging.
- Logging request parameter to log files.
- Server-side authentication and authorization.
- Compression and decompression.
- Encryption and decryption.
- Server-side validation.
Servlet Filter Interface
To create a filter, the programmer needs to follow three steps:
- Write a java class that implements the Filter interface and overrides the filter cycle methods.
- Initialize filter parameters – If necessary.
- Filter mapping.
Filter Interface
The filter interface is part of javax.servlet package to create filter, we must implement a Filter interface. The filter interface consists of 3 life cycle methods.
1. public void init(FilterConfig config) throws ServletException
This method is overridden for initializing filter parameters. This invokes the web container to indicate to a filter that is being placed into service. It takes one parameter, i.e. FilterConfig type or FilterConfig object.
2. Public void doFilters(ServletRequest request,ServletResponse response,FileterChain chain)throws ServletException,IOException
This method is considered the most important method in the Filter interface.it takes three parameters, ServletRequest object, ServletResponse object and object of FilterChain, to invoke the next filter. It performs some important tasks like.
- It examines the request header.
- Customizes the request objects if it feels necessary. Modify the request header or complete data.
- Even it also customizes response objects if it feels necessary.it can modify only the response header or complete data.
- It invokes the next filter by using the FilterChain object passed as a signature if there is filter chaining.
- It also examines the response header after invoking the next filter in the filter chaining.
- It is also responsible for throwing an Exception indicating that error/Exception is processing.
3. Public void destroy()
The container invokes this method to indicate the filter is finished its task or the filter is taken out from service. Users can override this method to writing some finalizing codes like freeing some resources, objects, etc.
Defining Filters in Servlet
The general format to defining filter in servlet.
Code:
public class HelloFilter implements Filter
{
public void init(ServletConfig config)
{
}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws ServletException,IOException
{
}
public void destroy()
{
}
}
Mapping filter in web.xml.
<web-app>
<filter>
<filter-name>HelloFilter</filter-name>
<filter-class>HelloFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HelloFilter</filter-name>
<url-pattern>/HelloFilter</url-pattern>
</filter-mapping>
</web-app>
Examples of Servlet Filter
An example of a servlet filter is given below:
Servlet Class:
import java.util.*;
import java.io.*;
import javax.Servlet.*;
import javax.Http.*;
public class HelloServlet1 Extends HttpServlet
{
protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
PrintWriter out=response.getWriter();
out.println("Hello ");
}
protected void doPost(request,response)throws ServletException,IOException
{
}
}
Filter Class:
import java.util.*;
import java.io.*;
import javax.Servlet.*;
import javax.Http.*;
public class ServletFilter implements Filter
{
public void init()throws ServletException
{
}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws ServletException,IOException
{
String ip=request.getRemoteHost();
System.out.println(“Remote Host:”+ip);
for(int i=0;i<9999;i++)
for(int j=0;j<9999;j++)
;
chain.doFilter(request,response)
for(int i=0;i<9999;i++)
for(int j=0;j<9999;j++)
;
System.out.println("Filter Finished");
}
public void destroy()
{
}
}
Web.xml mapping:
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>ServletFilter</filter-name>
<filter-class>ServletFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HelloFilter</filter-name>
<url-pattern>/HelloServlet1</url-pattern>
</filter-mapping>
</web-app>
Output:
Advantages of Servlet Filter
- Filters examine the user request before the servlet is called.
- Filter modifies the request header and data; hence, providing customized data request objects wraps up the actual request data.
- Filters help to intercept servlets invocation after servlet is called.
- The filter is pluggable, and one filter doesn’t have a pendency on other resources.
- The filter performs encryption and decryption; this helps in data security.
- The input validation task of the er helps in preventing irrelevant data processing.
- Filters perform the data compression process; this reduces storage space on the er.
- Since the filters perform server-side authentication and authorization, this benefits security on server-side data access or manipulation.
- Filters also help in interacting with external resources.
Conclusion
We have seen the advantages of filters; it clearly denotes that using filters in servlet is best suitable for developing web applications where the request and response processing is faster and filtered or intercepted. Most of the cases using filters help in server-side coding. Overall compared to other web development processes using a filter is the best way of achieving security, space utilization and many more.
Recommended Articles
This is a guide to Servlet Filter. Here we discuss the Introduction and why we need servlet filters and different examples and their code implementation. You may also have a look at the following articles to learn more –