There is given some useful examples of filter.

Example of sending response by filter only

MyFilter.java

import java.io.*;  
import javax.servlet.*;  
  
public class MyFilter implements Filter{  
    public void init(FilterConfig arg0) throws ServletException {}  
  
    public void doFilter(ServletRequest req, ServletResponse res,  
            FilterChain chain) throws IOException, ServletException {  
      
        PrintWriter out=res.getWriter();  
          
        out.print("
this site is underconstruction..");  
        out.close();  
          
    }  
    public void destroy() {}  
}

Example of counting number of visitors for a single page

MyFilter.java

import java.io.*;  
import javax.servlet.*;  
  
public class MyFilter implements Filter{  
    static int count=0;  
    public void init(FilterConfig arg0) throws ServletException {}  
  
    public void doFilter(ServletRequest req, ServletResponse res,  
            FilterChain chain) throws IOException, ServletException {  
      
        PrintWriter out=res.getWriter();  
        chain.doFilter(request,response);  
          
        out.print("
Total visitors "+(++count));  
        out.close();  
          
    }  
    public void destroy() {}  
}

Example of checking total response time in filter

MyFilter.java

import java.io.*;  
import javax.servlet.*;  
  
public class MyFilter implements Filter{  
    static int count=0;  
    public void init(FilterConfig arg0) throws ServletException {}  
  
    public void doFilter(ServletRequest req, ServletResponse res,  
            FilterChain chain) throws IOException, ServletException {  
      
        PrintWriter out=res.getWriter();  
        long before=System.currentTimeMillis();  
  
        chain.doFilter(request,response);  
          
        long after=System.currentTimeMillis();  
        out.print("
Total response time "+(after-before)+" miliseconds");  
        out.close();  
          
    }  
    public void destroy() {}  
}