Filter过滤器(如何创建,生命周期,执行流程)

版权声明:《==study hard and make progress every day==》 https://blog.csdn.net/qq_38225558/article/details/83031051

Filter过滤器是什么??

       开发人员可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截。简单说,就是可以实现web容器对某资源的访问前截获进行相关的处理,还可以在某资源向web容器返回响应前进行截获进行处理。

过滤器就相当于是一个滤纸用来过滤条件的~~

过滤器链:多个过滤器

多个过滤器的执行顺序:(注意:请求和响应是相反的
请求时是:A --> B --> C
响应时是:C --> B --> A

如何实现过滤器??

①自定义类去实现Filter接口

public class MyFilter implements Filter {

	@Override
	public void init(FilterConfig config) throws ServletException {
		System.out.println("===过滤器初始化===");
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("===过滤器执行===");
		//放行请求
		chain.doFilter(req, resp);
		System.out.println("===放行之后会执行响应...===");
	}
	
	@Override
	public void destroy() {
		System.out.println("===过滤器销毁===");
	}

}

②在web.xml中配置或者使用注解配置@WebFilter("过滤器路径")   注意:不推荐使用注解配置)

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0" metadata-complete="false">
  
    <filter>
		<filter-name>a</filter-name>
		<filter-class>com.zhengqing.filter.MyFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>a</filter-name>
		<!-- url-pattern:需要过滤的访问路径 -->
		<url-pattern>/index.jsp</url-pattern>
	</filter-mapping>

</web-app>

为什么不使用注解配置??

和过滤器链(多个过滤器)有关!!

过滤器链的执行需要顺序     ----    注解确定不了顺序,但使用配置可以!!

配置如何确定顺序??      ==》  根据过滤范围从上到下与<filter-mapping>的配置顺序有关

为什么需要在web.xml中配置??   

因为过滤器的功能作用于路径上  也就是我们在web.xml中所配置的url-pattern (/index.jsp:过滤index.jsp一个具体的路径      /*:过滤所有路径   ...)

过滤器的生命周期???

tomcat服务器启动时创建 --> 初始化(init) --> 执行(doFilter)[每次请求/响应都执行] --> 销毁(destroy)(服务器正常关闭时销毁)

过滤器通过什么方式让请求通过??

放行请求代码:FilterChain对象.doFilter(请求对象,响应对象)

过滤器请求和响应的执行顺序??

请求的时候 : 执行放行上面的代码
响应的时候 : 执行放行下面的代码


ex: 结合过滤器生命周期来一起看执行顺序吧!

我的index.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"   %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
</head>
<body>
	<%
		System.out.println("===index首页执行===");
	%>
	这是首页
</body>
</html>

tomcat服务器启动时会创建过滤器然后初始化...

当我们访问index.jsp时  (浏览器输入访问路径:)

上面是存在放行代码的时候,如果没有放行请求,就不会执行响应!!

正常关闭服务器时销毁

 

 

猜你喜欢

转载自blog.csdn.net/qq_38225558/article/details/83031051