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


 

项目结构:

 

 

 

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方法

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM