Filter实战

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/chengqiuming/article/details/100585508

一 创建Filter类

package lee;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

import java.io.*;


@WebFilter(filterName="log"
    ,urlPatterns={"/*"})
public class LogFilter implements Filter
{
    // FilterConfig可用于访问Filter的配置信息
    private FilterConfig config;
    // 实现初始化方法
    public void init(FilterConfig config)
    {
        this.config = config;
    }
    // 实现销毁方法
    public void destroy()
    {
        this.config = null;
    }
    // 执行过滤的核心方法
    public void doFilter(ServletRequest request,
        ServletResponse response, FilterChain chain)
        throws IOException,ServletException
    {
        // ---------下面代码用于对用户请求执行预处理---------
        // 获取ServletContext对象,用于记录日志
        ServletContext context = this.config.getServletContext();
        long before = System.currentTimeMillis();
        System.out.println("开始过滤...");
        // 将请求转换成HttpServletRequest请求
        HttpServletRequest hrequest = (HttpServletRequest)request;
        // 输出提示信息
        System.out.println("Filter已经截获到用户的请求的地址: " +
            hrequest.getServletPath());
        // Filter只是链式处理,请求依然放行到目的地址
        chain.doFilter(request, response);
        // ---------下面代码用于对服务器响应执行后处理---------
        long after = System.currentTimeMillis();
        // 输出提示信息
        System.out.println("过滤结束");
        // 输出提示信息
        System.out.println("请求被定位到" + hrequest.getRequestURI() +
            "   所花的时间为: " + (after - before));
    }
}

二 视图

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Filter测试</title>
    <meta name="website" content="http://www.crazyit.org" />
</head>
<body>
<h2>Filter页面</h2>
</body>
</html>

三 测试

开始过滤...
Filter已经截获到用户的请求的地址: /filter.jsp
过滤结束
请求被定位到/filterTest/filter.jsp   所花的时间为: 904

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/100585508