Master Core Java & Servlets!
Subscribe to Ram N Java for beginner-friendly coding walkthroughs, web architecture guides, and practical backend demonstrations!
🔔 Subscribe to Ram N JavaWhat is a Servlet Filter?
In Java web applications, a Filter is a pluggable Java component that intercepts incoming client requests before they hit a servlet, and inspects outgoing responses before they are returned to the browser.
Filters are ideal for cross-cutting tasks such as logging request metadata, verifying user credentials, modifying headers, or compressing data—without modifying the business logic inside the target servlet itself.
How a Single Filter Works in Practice
To implement a servlet filter, your class must implement the javax.servlet.Filter interface and override its core methods:
- init(FilterConfig config): Called once by the web container when initializing the filter.
- doFilter(ServletRequest request, ServletResponse response, FilterChain chain): Executes every time a matching request arrives.
- destroy(): Called once when the filter is taken out of service.
// Step 1: Pre-processing before servlet invocation
System.out.println("Filter: Pre-processing client request...");
// Step 2: Pass control to the destination servlet or next filter
chain.doFilter(request, response);
// Step 3: Post-processing after servlet generates response
System.out.println("Filter: Post-processing server response...");
Key Takeaways from the Demo
- web.xml Configuration: The filter is mapped to specific servlet names or URL patterns using
<filter>and<filter-mapping>tags. - chain.doFilter() is Crucial: Failing to invoke
chain.doFilter()blocks the request and prevents the servlet from executing. - Two-Way Interception: Code written before
chain.doFilter()executes during the request phase, while code written after runs during the response phase.
Recommended Related Tutorials
Explore more in-depth filter concepts with these tutorials from Ram N Java:
Click here to watch in Youtube : https://www.youtube.com/watch?v=xHl_0yuDN6c
Click the below Image to Enlarge
SingleFilterDemo Project Dir Structure