Servlet過濾器示例

在本節中,給出了一個有用的過濾器示例。

這是一個僅通過過濾器發送響應的示例 -

文件: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("<br/>this site is underconstruction..");  
        out.close();  

    }  
    public void destroy() {}  
}

計算單頁訪問次數的示例

文件: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("<br/>Total visitors "+(++count));  
        out.close();  

    }  
    public void destroy() {}  
}

在過濾器中檢查總響應時間的示例

文件: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("<br/>Total response time "+(after-before)+" miliseconds");  
        out.close();  

    }  
    public void destroy() {}  
}