📜  Servlet筛选器的示例

📅  最后修改于: 2021-01-09 12:49:38             🧑  作者: Mango

有用的过滤器示例

给出了一些有用的过滤器示例。

仅通过过滤器发送响应的示例


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() {} }

单页访问者计数示例


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() {} }

在过滤器中检查总响应时间的示例


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() {} }