項目結構:

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