A Servlet Filter is a component that can perform filtering tasks on either the request to a resource (a servlet, JSP page, etc.), or on the response from a resource, or both. It acts as a layer between the client and the resource on the server, allowing for centralized management of tasks such as authentication, logging, and data compression.
Here’s a high-level overview of how a Servlet Filter works:
- Initialization: When the web application starts, the servlet container initializes the filters as defined in the
web.xml
file or annotated with@WebFilter
. - Request Processing: When a request comes in, the servlet container invokes the
doFilter
method of each filter mapped to the requested resource. ThedoFilter
method can modify the request or directly send a response. - Response Processing: After the requested resource (servlet or JSP) has processed the request, the response can also be modified by the filters before it’s sent back to the client.
- Cleanup: When the web application is undeployed or stopped, the servlet container calls the
destroy
method of each filter to release any resources held.
Here’s a simple example of a Servlet Filter that logs the IP address of the client making the request:
import javax.servlet.*;
import java.io.IOException;
public class LogFilter implements Filter {
public void init(FilterConfig config) throws ServletException {
// Filter initialization code here
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// Get the IP address of client machine.
String ipAddress = request.getRemoteAddr();
// Log the IP address and current timestamp.
System.out.println("IP " + ipAddress + ", Time " + new java.util.Date().toString());
// Pass request back down the filter chain
chain.doFilter(request,response);
}
public void destroy() {
// Cleanup code here
}
}
In this example, the doFilter
method logs the client’s IP address and the current timestamp to the console. Then, it passes the request and response objects to the next entity in the filter chain using chain.doFilter(request, response)
. If this filter is the last one in the chain, the request is then passed to the actual resource.
To use this filter, you would need to configure it in your web.xml
file or use the @WebFilter
annotation to specify the URL patterns for which this filter should be applied.