3、过滤器细节:
1、web.xml配置
<filter>
<filter-name>test1</filter-name>
<filter-class>com.example.web.filter.FilterDemo1</filter-class>
</filter>
<filter-mapping>
<filter-name>test1</filter-name>
<!--拦截路径-->
<url-pattern>/*</url-pattern>
</filter-mapping>
2、过滤器执行流程
1. 执行过滤器
2. 执行放行后的资源
3. 回来执行过滤器放行代码下边的代码
3、过滤器声明周期方法
1. init:在服务器启动后,会创建Filter对象,然后调用init方法。只执行一次。用于加载资源
2. doFilter:每一次请求被拦截资源时,会执行。执行多次
3. destroy:在服务器关闭后,Filter对象被销毁。如果服务器是正常关闭,则会执行destroy方法。只执行一次。用于释放资源
4、过滤器配置详解
5、过滤器链(配置多个过滤器)
1.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_4_0.xsd" version="4.0"> <filter> <filter-name>test1</filter-name> <filter-class>com.example.web.filter.FilterDemo1</filter-class> </filter> <filter-mapping> <filter-name>test1</filter-name>
<!--拦截路径--> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
实现
/**
* 过滤器快熟入门
*/
public class FilterDemo1 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { Filter.super.init(filterConfig); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("被执行了。。。"); //放行 filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { Filter.super.destroy(); } }
2.过滤器执行流程 @WebFilter("/*") public class FilterDemo2 implements Filter { public void init(FilterConfig config) throws ServletException { } public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { System.out.println("FilterDemo2跑了..."); //放行 chain.doFilter(request, response); System.out.println("FilterDemo2又回来了"); } }
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <title>JSP - Hello World</title> </head> <body> index.jsp... <% System.out.println("index.jsp..."); %> </body> </html>
3.过滤器声明周期方法 @WebFilter("/*") public class FilterDemo3 implements Filter { /** * 在服务器启动后,创建Filter对象,然后用init方法,只执行一次 * @param config * @throws ServletException */ public void init(FilterConfig config) throws ServletException { System.out.println("init..."); } /** * 在服务器关闭后,filter对象被销毁,如果服务器是正常关闭,则会执行destroy方法,只执行一次,用于释放资源 */ public void destroy() { System.out.println("destroy..."); } /** * 每一次被请求拦截资源时,会执行多次 * @param request * @param response * @param chain * @throws ServletException * @throws IOException */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { System.out.println("doFilter..."); //放行 chain.doFilter(request, response); } }
标签:xml,web,ServletException,void,public,Filter,过滤器,throws From: https://www.cnblogs.com/agzq/p/17136426.html