创建一个过滤器拦截所有请求

梦想与她 提交于 2019-12-04 15:09:49

 

项目结构:

 

 

 

AFilter:

package cn.itcast.web.filter;

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

public class AFilter implements Filter {
    /**
     * init方法在filter创建之后立即执行,用来做初始化
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化!");
    }

    /**
     * 每次过滤时都会执行
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器拦截。。。");
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("回来执行doFilter方法。。。");
    }

    /**
     * destroy方法在销毁之前执行,用来对非内存资源释放
     */
    @Override
    public void destroy() {
        System.out.println("过滤器销毁!");
    }
}

 

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>AServlet</servlet-name>
        <servlet-class>cn.itcast.web.servlet.AServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AServlet</servlet-name>
        <url-pattern>/AServlet</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>AFilter</filter-name>
        <filter-class>cn.itcast.web.filter.AFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>AFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

 index.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%System.out.println("执行index.jsp。。。");%>
    index.jsp页面
</body>
</html>

 

 控制台输出:

项目启动时执行init方法

 访问index.jsp,http://localhost:8080/day09/index.jsp

 执行doFilter方法

 

 关闭服务器销毁filter

 

销毁filter之前会调用destroy方法

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!