过滤器的案例

本文演示一些常用的过滤器示例。

1 使用过滤器输出响应内容

OutFilter:

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *一点教程网 - http://www.yiidian.com
 */
public class OutFilter implements Filter {


    public void init(FilterConfig config) throws ServletException {
    }

    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out=resp.getWriter();

        out.print("<br/>页面建设中..");
        out.close();

    }

    public void destroy() {

    }
}

2 统计访问人数

CountFilter:

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *一点教程网 - http://www.yiidian.com
 */
public class CountFilter implements Filter {
    static int count=0;

    public void init(FilterConfig config) throws ServletException {
    }

    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out=resp.getWriter();
        chain.doFilter(req,resp);

        out.print("<br/>总访问量:"+(++count));
        out.close();

    }

    public void destroy() {

    }
}

IndexServlet:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class IndexServlet extends HttpServlet{

    public void doGet(HttpServletRequest req,HttpServletResponse res)
            throws ServletException,IOException
    {
        res.setContentType("text/html;charset=utf-8");
        PrintWriter out = res.getWriter();

        out.print("<br>欢迎访问一点教程网<br>");
    }

}

3 计算页面响应时间

CalFilter:

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *一点教程网 - http://www.yiidian.com
 */
public class CalFilter implements Filter {
    static int count=0;

    public void init(FilterConfig config) throws ServletException {
    }

    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out=resp.getWriter();
        long before=System.currentTimeMillis();

        chain.doFilter(req,resp);

        long after=System.currentTimeMillis();
        out.print("<br/>总响应时长: "+(after-before)+" 毫秒");
        out.close();

    }

    public void destroy() {

    }
}

热门文章

优秀文章