A filter is an object that dynamically intercepts requests and responses to transform or use the information contained in the requests or responses.

Filters typically do not themselves create responses but instead provide universal functions that can be “attached” to any type of servlet or JSP page.

The filter is run before rendering view but after controller rendered response.

A Filter is used in the web layer only as it is defined in web.xml.

Filters are more suitable when treating your request/response as a black box system. They’ll work regardless of how the servlet is implemented.

Filters are used to perform filtering tasks such as login authentication ,auditing of incoming requests from web pages, conversion, logging, compression, encryption and decryption, input validation etc.

A Servlet Filter is used in the web layer only, you can’t use it outside of a
web context.

servlet filter

Filter Interface methods :-

Method Description
public void init(FilterConfig config) init() method is invoked only once.
It is used to initialize the filter.
public void doFilter( HttpServletRequest request,
HttpServletResponse response, FilterChain chain)
doFilter() method is invoked every time when user
request to any resource, to which the filter is mapped.
public void destroy() This is invoked only once when filter is taken
out of the service.

Filter Example :-


import javax.servlet.*;
import java.io.IOException;

public class MyFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain)
    throws IOException, ServletException {
      // your code goes here

    public void destroy() {


import java.io.IOException;  
import java.io.PrintWriter;  
import javax.servlet.ServletException;  
import javax.servlet.http.*;  
public class HelloServlet extends HttpServlet {  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        PrintWriter out = response.getWriter();  
        out.print("<br>Hello from servlet<br>");  

Configuring the Servlet Filter in web.xml


For more detail :-


Leave Comment

Your email address will not be published. Required fields are marked *