Introduction to Java Servlet Filters and Their Configuration
This article explains the concept, functions, development steps, configuration, lifecycle methods, and practical examples of Java Servlet Filters, showing how they intercept requests and responses, modify data, and integrate with web.xml, Spring, Hibernate, and Struts2 for backend web applications.
Filters, also known as servlet filters, are a core part of Java Servlet technology that allow developers to intercept and process all web resources—such as JSPs, servlets, static images, or HTML files—before they reach the client, enabling functions like URL‑level access control, sensitive word filtering, and response compression.
Filters can preprocess incoming HttpServletRequest objects and post‑process outgoing HttpServletResponse objects. The typical flow is: a filter preprocesses the request, passes it to the target servlet, receives the generated response, and then performs post‑processing before the response is sent back to the client.
Key capabilities include:
Intercepting and optionally modifying the request before it reaches a servlet.
Intercepting and optionally modifying the response before it is returned to the client.
When a filter is mapped to a resource, the web container invokes the filter's doFilter method before the resource's service method. Inside doFilter, developers can decide whether to continue the chain by calling filterChain.doFilter(request, response) or to block the request.
Developing a filter involves two steps:
Implement a Java class that implements the javax.servlet.Filter interface and provides an init, doFilter, and destroy method.
Register the filter in web.xml (or via annotations) and define the URL patterns or servlet names it should intercept.
Typical web.xml elements for a filter are:
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.example.MyFilter</filter-class>
<init-param>
<param-name>exampleParam</param-name>
<param-value>value</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>The filter lifecycle consists of three methods:
public void init(FilterConfig filterConfig) throws ServletException; // called once when the filter is created public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException; // called for each request that matches the mapping public void destroy(); // called once when the filter is taken out of serviceThe FilterConfig interface gives access to initialization parameters and the servlet context, allowing filters to read configuration values at startup.
Example: a login‑validation filter that checks a session attribute and redirects unauthenticated users to a login page.
package com.action.login;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Determines whether a user is logged in; if not, redirects to login page.
*/
public class SessionFilter implements Filter {
private FilterConfig config;
public void init(FilterConfig filterConfig) throws ServletException { this.config = filterConfig; }
public void destroy() { this.config = null; }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponseWrapper resp = new HttpServletResponseWrapper((HttpServletResponse) response);
String logonStrings = config.getInitParameter("logonStrings");
String includeStrings = config.getInitParameter("includeStrings");
String redirectPath = req.getContextPath() + config.getInitParameter("redirectPath");
String disable = config.getInitParameter("disabletestfilter");
if ("Y".equalsIgnoreCase(disable)) { chain.doFilter(request, response); return; }
String[] logonList = logonStrings.split(";");
String[] includeList = includeStrings.split(";");
if (!isContains(req.getRequestURI(), includeList) || isContains(req.getRequestURI(), logonList)) {
chain.doFilter(request, response); return;
}
String user = (String) req.getSession().getAttribute("useronly");
if (user == null) { resp.sendRedirect(redirectPath); return; }
chain.doFilter(request, response);
}
private boolean isContains(String uri, String[] patterns) {
for (String p : patterns) { if (uri.contains(p)) return true; }
return false;
}
}Other common filters include an encoding filter to prevent Chinese character garbling, the Spring CharacterEncodingFilter, the Hibernate OpenSessionInViewFilter for lazy‑loading support, and the Struts2 filter ( StrutsPrepareAndExecuteFilter) for action processing.
When configuring multiple filters, the order in web.xml determines the execution sequence; the container creates a FilterChain object that passes control from one filter to the next until the target resource is reached.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
