Filter filter & Listener listener

Filter

  1. Filters in the web When a user accesses server resources, the filter intercepts the request and completes some common operations
  2. Application scenarios such as: login verification, unified encoding processing, sensitive character filtering

Write a filter to intercept the target resource servlet

1. 编写java类,实现filter接口
public class QuickFilter implements Filter {
    
    
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
    
    }
	/**
	* 此方法拦截用户请求
	* @param servletRequest :请求对象
	* @param servletResponse :响应对象
	* @param filterChain :过滤器链(是否放行)
	*/
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
		System.out.println("QuickFilter拦截了请求...");
		// 放行
		filterChain.doFilter(servletRequest, servletResponse);
	}
	
	@Override
	public void destroy() {
    
    }
}

② Configure web.xm

<?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">
<!--注册filter-->
<filter>
	<filter-name>QuickFilter</filter-name>
	<filter-class>com.lagou.a_quick.QuickFilter</filter-class>
</filter>
<!--配置filter拦截路径-->
<filter-mapping>
	<filter-name>QuickFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

How filters work

insert image description here

life cycle

  1. Life cycle: refers to the process of an object from life (creation) to death (destruction)

    // 初始化方法
    public void init(FilterConfig config);
    // 执行拦截方法
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain);
    // 销毁方法
    public void destroy();
    
  • Create: The server starts the project loading, creates the filter object, and executes the init method (only once)
  • Run (filtering and interception): when the user accesses the intercepted target resource, execute the doFilter method
  • Destroy: When the server closes the project to unload, destroy the filter object and execute the destroy method (only once)
  • Supplement: filter must be created prior to servlet
// @WebFilter(value = "/show.jsp"})
public class LifecycleFilter implements Filter {
    
    
/*
filterConfig 它是filter的配置对象
注意作用:获取filter的初始化参数
*/

private String encode;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    
    
	System.out.println("LifecycleFilter创建了...执行init方法");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse
	servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
	System.out.println("LifecycleFilter拦截了请求...执行deFilter方法");
	// 放行
	filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
    
    
	System.out.println("LifecycleFilter销毁了...执行destroy方法");
	}
}

interception path

  1. During development, the interception path of the filter can be specified to define the scope of interception target resources
  • Exact match: When the user accesses the specified target resource (/show.jsp), the filter intercepts it
  • Directory matching: When a user accesses all resources in the specified directory (/user/*), the filter will intercept
  • Suffix matching: When a user accesses a resource with a specified suffix (*.html), the filter intercepts it
  • Match all: When the user accesses all resources (/*) of the website, the filter will intercept
// @WebFilter("/show.jsp") 精准匹配
// @WebFilter("/user/*") // 目录匹配
// @WebFilter("*.html") // 后缀匹配
@WebFilter("/*") // 匹配所有
public class UrlPatternFilter implements Filter {
    
    
	public void init(FilterConfig config) throws ServletException {
    
    
	}
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
    
    
		System.out.println("UrlPatternFilter拦截了请求...");
		// 放行
		chain.doFilter(servletRequest, servletResponse);
	}
	public void destroy() {
    
    }
}

filter chain

  1. In one request, if our request matches multiple filters, passing the request is equivalent to stringing these filters together to form a filter chain

    * 需求
    用户访问目标资源 /targetServlet时,经过 FilterA FilterB
    * 过滤器链执行顺序 (先进后出)
    1.用户发送请求
    2.FilterA拦截,放行
    3.FilterB拦截,放行
    4.执行目标资源 show.jsp
    5.FilterB增强响应
    6.FilterA增强响应
    7.封装响应消息格式,返回到浏览器
    * 过滤器链中执行的先后问题....
    配置文件
    谁先声明,谁先执行
    <filter-mapping>
    

insert image description here

Listener listener

  1. In a java program, sometimes it is necessary to monitor certain things, and once the monitored object changes accordingly, corresponding actions should be taken.
  2. Listen to the three major domain objects of the web: HttpServletRequest, HttpSession, and ServletContext Monitor the creation and destruction of the three major domain objects through the listener
  3. The number of historical visits, the statistics of the number of online users, and the initial configuration information when the system starts

Introduction to Listener Listener

  1. Listeners are rarely used in web development, and there are even fewer opportunities to see them, so use ServletContextListenner to learn about listeners, because this listener is the most frequently used listener, and the use of listeners is similar . We can use this listener to do some things when the project is started and destroyed, for example, load the configuration file when the project starts.
ServletContextListener接口的API介绍:
void contextDestroyed(ServletContextEvent sce) 监听servletcontext销毁
void contextInitialized(ServletContextEvent sce) 监听servletcontext创建

Use of listeners

  1. Create a class that implements the ServletContextListenner interface
  2. Implement the contextInitialized and contextDestroyed methods of ServletContextListenner.
  3. Configure this class in xml
package com.code.listenner;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyServletContextListenner1 implements ServletContextListener {
    
    

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
    
    
		System.out.println("服务器启动,servletContext被创建了");
	}
	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
    
    
		System.out.println("服务器停止,servletContext被销毁了");
	}
}

The configuration of web.xml is as follows:

<listener>
	<listener-class>com.code.listenner.MyServletContextListenner1</listenerclass>
</listener>

You can also monitor the creation and destruction of session objects and request objects in the same way using the following interface

```clike
HttpSessionListener:监听Httpsession域的创建与销毁的监听器
ServletRequestListener:监听ServletRequest域的创建与销毁的监听器
```

Guess you like

Origin blog.csdn.net/qq_43408367/article/details/130184185