Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

Useful Examples


There is given some useful examples of filter.

Example of sending response by filter only

MyFilter.java

  1. import java.io.*;
  2. import javax.servlet.*;
  3. public class MyFilter implements Filter{
  4.     public void init(FilterConfig arg0) throws ServletException {}
  5.     public void doFilter(ServletRequest req, ServletResponse res,
  6.             FilterChain chain) throws IOException, ServletException {
  7.         PrintWriter out=res.getWriter();
  8.         out.print(“<br/>this site is underconstruction..”);
  9.         out.close();
  10.     }
  11.     public void destroy() {}
  12. }

Example of counting number of visitors for a single page

MyFilter.java

  1. import java.io.*;
  2. import javax.servlet.*;
  3. public class MyFilter implements Filter{
  4.     static int count=0;
  5.     public void init(FilterConfig arg0) throws ServletException {}
  6.     public void doFilter(ServletRequest req, ServletResponse res,
  7.             FilterChain chain) throws IOException, ServletException {
  8.         PrintWriter out=res.getWriter();
  9.         chain.doFilter(request,response);
  10.         out.print(“<br/>Total visitors “+(++count));
  11.         out.close();
  12.     }
  13.     public void destroy() {}
  14. }

Example of checking total response time in filter

MyFilter.java

  1. import java.io.*;
  2. import javax.servlet.*;
  3. public class MyFilter implements Filter{
  4.     static int count=0;
  5.     public void init(FilterConfig arg0) throws ServletException {}
  6.     public void doFilter(ServletRequest req, ServletResponse res,
  7.             FilterChain chain) throws IOException, ServletException {
  8.         PrintWriter out=res.getWriter();
  9.         long before=System.currentTimeMillis();
  10.         chain.doFilter(request,response);
  11.         long after=System.currentTimeMillis();
  12.         out.print(“<br/>Total response time “+(after-before)+” miliseconds”);
  13.         out.close();
  14.     }
  15.     public void destroy() {}
  16. }

Comments

comments