Filters are helpful in performing filter functionality in Java web application Application. A filter implements the javax.servlet.Filter interface. The primary filter functionality is implemented by the doFilter() method of the filter.

A filter is used to perform a particular task either before or after the actual functionality of a web application is performed. For example, if a request is made for a particular resource such as a Servlet in web application and a filter is used, the filter code may execute and then pass the user on to the Servlet. The filter may run a check before letting the user to the actual page.The filter checks the user permissions to access a particular servlet, and it might send the user to an error page rather than to the requested resource.

Below is a code which shows the filter in web.xml file

web.xml

 <webapp>
  <filter>
    <filter-name>SampleFilter</filter-name>
    <filter-class>com.mugil.filter.TestFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SampleFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  </web-app>

Filter code is java is as below
TestFilter.java

public class TestFilter implements Filter 
{
  public void init(FilterConfig fConfig) throws ServletException 
  {
     System.out.println("Filter Initialized");
  }
  
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException 
  {	
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();
     out.print("Filter Executed");		
     chain.doFilter(request, response);
  }

  public void destroy() 
  {
    System.out.println("Filter Destroyed");
  }
}

The init() method will be executed every time the server starts.The doFilter method is executed every time a Servlet or JSP page is accessed in the context.Filter destroy() method is called when the server is stopped.

Leave a reply