Java.Servlet.What do you know about servlet filters?

Servlet filters are like middleware in Java web applications — they allow you to intercept and modify requests and responses before they reach a servlet or after the servlet processes them.

🧰 What Is a Servlet Filter?

A filter is a Java class that implements:

javax.servlet.Filter

🧠 Key Uses:

  • Logging
  • Authentication/authorization checks
  • Compression (e.g. GZIP)
  • Request/response modification
  • CORS handling
  • XSS/SQL injection sanitization

⚙️ How Does It Work?

The servlet container:

  1. Receives a request
  2. Passes it through any matching filters
  3. Filters can:
    • Modify the request
    • Block the request (send error, redirect)
    • Let the request proceed by calling chain.doFilter()
  4. After the servlet processes the request, the response goes back through the filter (reverse order)

🔁 Filter Lifecycle

Just like servlets, filters have a defined lifecycle:

init()         // Called once when the filter is created
doFilter()     // Called on each request
destroy()      // Called when the app shuts down or filter is undeployed

🧪 Simple Filter Example

@WebFilter("/secure/*")
public class AuthFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        HttpSession session = request.getSession(false);
        boolean loggedIn = (session != null && session.getAttribute("user") != null);

        if (loggedIn) {
            chain.doFilter(req, res); // ✅ Continue to the servlet
        } else {
            response.sendRedirect("/login"); // 🔒 Block or redirect
        }
    }
}

🗂️ Declaring Filters

1. With Annotations (@WebFilter)

@WebFilter(urlPatterns = {"/admin/*", "/user/*"})
public class MyFilter implements Filter { ... }

2. In web.xml

<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>com.myapp.MyFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/admin/*</url-pattern>
</filter-mapping>

🔧 Filter Chain Order

If multiple filters apply, the container runs them in the order they’re declared (in web.xml), or order may be container-defined if declared with annotations.

✅ Summary

FeatureDescription
Interfacejavax.servlet.Filter
Methodsinit(), doFilter(), destroy()
Common usesAuth, logging, compression, request/response manipulation
Configuration@WebFilter or web.xml
Key methodchain.doFilter() to continue the chain
This entry was posted in Без рубрики. Bookmark the permalink.