Use of Filter and Listener in Spring -- 4

Filter

1. Overview

Concept: Filter, also known as Filter, is mainly used to preprocess user requests or post process HttpServletResponse. The complete process of using Filter: Filter preprocesses the user request, then sends the request to the Servlet for processing and generates a response, and finally Filter post processes the server response.
Function: intercept the customer's HttpServletRequest before the HttpServletRequest reaches the Servlet. You can also modify the Servlet header and the PHP header as needed.

Intercept the HttpServletResponse before it reaches the client. Check the HttpServletResponse as needed, or modify the HttpServletResponse header and data.
Filter chain: in a web application, multiple filters can be developed and written. These filters are combined to be called a filter chain.
The web server is on the web according to the filter The registration order in the XML file determines which filter to call first. When the doFilter method of the first filter is called, the web server will create a FilterChain object representing the filter chain and pass it to the method. In the doFilter method, if the developer calls the doFilter method of the FilterChain object, the web server will check whether there is a filter in the FilterChain object. If so, call the second filter. If not, call the target resource.
Filter lifecycle:

public void init(FilterConfig filterConfig) throws ServletException;//initialization
 And what we wrote Servlet The procedure is the same, Filter Created and destroyed by WEB The server is responsible. web When the application starts, web The server will create Filter And call its init Method, reading web.xml Configure to complete the initialization function of the object, so as to prepare for the interception of subsequent user requests( filter The object is created only once, init Method is also executed only once). Developers pass init Method can be obtained to represent the current filter Of configuration information FilterConfig Object.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;//Intercept request
 This method completes the actual filtering operation. When a customer requests access to the information associated with the filter URL When I was young, Servlet The filter will execute first doFilter method. FilterChain Parameter is used to access subsequent filters.

public void destroy();//Destroy
Filter After the object is created, it will reside in memory web Destroy only when the application is removed or the server is stopped. stay Web Container unloading Filter Object was called before. This method is used in Filter Execute only once in the lifecycle of. In this method, the resources used by the filter can be released.

FilterConfig interface:
When configuring the filter, users can configure some initialization parameters for the filter. When the web container instantiates the filter object and calls its init method, it will pass in the filterConfig object that encapsulates the initialization parameters of the filter. Therefore, when writing filter, developers can obtain the following contents through the method of filterConfig object:

String getFilterName();//Get the name of the filter. 
String getInitParameter(String name);//Returns the value of the initialization parameter with the name specified in the deployment description. If it does not exist, null is returned 
Enumeration getInitParameterNames();//Returns an enumerated collection of the names of all initialization parameters of the filter. 
public ServletContext getServletContext();//Returns a reference to the Servlet context object.

2. Filter usage example

Filter implementation class

package com.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class myFilter implements Filter {
	private FilterConfig config;
	public void init(FilterConfig config) {
		this.config = config;
	}
	public void destory() {
		this.config=null;
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		ServletContext context = this.config.getServletContext();
		long before = System.currentTimeMillis();
		System.out.println("Start filtering....");
		HttpServletRequest hrequest = (HttpServletRequest)request;
		System.out.println("Intercepted request address:"+hrequest.getServletPath());
		String name = config.getInitParameter("name");
		String age = config.getInitParameter("age");
		System.out.println("Obtained Name:"+name);
		System.out.println("Age of acquisition:"+age+"\n");
		chain.doFilter(request, response);
		long after = System.currentTimeMillis();
		System.out.println("End of filtering");
		System.out.println("The request is scheduled to arrive"+hrequest.getRequestURI()+"The time taken is:"+(after-before));
	}
}

web.xml configuration

<filter>
  	<filter-name>log</filter-name>
  	<filter-class>com.filter.myFilter</filter-class>
  	<init-param>
  		<param-name>name</param-name>
  		<param-value>Jack</param-value>
  	</init-param>
  	<init-param>
  		<param-name>age</param-name>
  		<param-value>29</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>log</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

3. The spring boot annotation uses the Filter example

Using @ ServletComponentScan annotation on SpringBootApplication, Servlet, Filter and Listener can be automatically registered directly through @ WebServlet, @ WebFilter and @ WebListener annotation without other code.
Startup class:

//Remove auto configuration dataSource
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@ServletComponentScan
public class TestApplication {
	public static void main(String[] args) {
		SpringApplication.run(TestApplication.class, args);
	}
}

Specific implementation:

@RestController
@RequestMapping("/test")
public class Test1 {
	@PostMapping("/a")
	public void A() {
		System.out.println("aaa");
	}
}

@WebFilter(urlPatterns = "/*")
class TestFilter implements Filter{
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("filter initialization!!!!!!!!!!!!!!!");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("filter Intercept!");
	}
	
	@Override
	public void destroy() {
		System.out.println("filter Destroy!!!!!!!!!!!!");
	}
}

Listener

1. Overview

Concept: the listener is used to monitor the creation, destruction, addition, modification, deletion and other actions of some objects and information in web applications, and then make corresponding response processing. When the state of the scope object changes, the server automatically calls the methods in the listener object. It is often used to count the number of online people and online users, initialize information when the system is loaded, and count the number of visits to the website.
Classification:
1. By listening object, it can be divided into
ServletContext object listener
HttpSession object listener
ServletRequest object listener
2. By listening events
Listener for the creation and destruction of the object itself
Listener for creating and eliminating properties in objects
A listener for the state change of an object in a session
Function:
1. ServletContextListener: used to monitor the startup and shutdown of Web applications
2. ServletContextAttributeListener: used to listen for attribute changes within the scope of ServletRequest (application)
3. ServletRequestListener: used to listen to user requests
4. ServletRequestAttributeListener: used to listen for attribute changes within the scope of ServletRequest (request)
5. HttpSessionListener: used to listen for the beginning and end of a session
6. HttpSessionAttributeListener: used to listen for attribute changes within the HttpSession range (session)

2. Use examples based on SpringBoot

Startup class

//Remove auto configuration dataSource
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@ServletComponentScan
public class TestApplication {
	public static void main(String[] args) {
		SpringApplication.run(TestApplication.class, args);
	}
}

Concrete implementation

@RestController
@RequestMapping("/test")
public class Test1 {
	@PostMapping("/a")
	public void A() {
		System.out.println("aaa");
	}
}

@WebListener
class ContextListener implements ServletContextListener{
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("web The app started!");
		ServletContextListener.super.contextInitialized(sce);
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("web App closed!");
		ServletContextListener.super.contextDestroyed(sce);
	}
}

@WebListener
class requestListener implements ServletRequestListener{

	@Override
	public void requestDestroyed(ServletRequestEvent sre) {
		System.out.println("User request completed!");
		ServletRequestListener.super.requestDestroyed(sre);
	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		System.out.println("Received user request!");
		ServletRequestListener.super.requestInitialized(sre);
	}
	
}

Interceptor

1. Overview

1. Concept
The interceptor in java is an object that dynamically intercepts the call of an Action. It provides a mechanism for developers to execute a piece of code before and after the execution of an Action, or to prevent the execution of an Action before the execution. At the same time, it also provides a way to extract the reusable part of the code in the Action. In AOP, interceptors are used to intercept a method or field before it is accessed, and then add some operations before or after it. At present, what we need to master is mainly the interceptor of Spring. The interceptor of struts 2 doesn't need to go deep into it.
2. To customize the interceptor
Step 1: customize a class that implements the Interceptor interface, or inherit the abstract class AbstractInterceptor.
Step 2: register the defined interceptor in the configuration file.
Step 3: the interceptor defined above needs to be referenced in the Action. For convenience, the interceptor can also be defined as the default interceptor. In this way, all interceptors can be used without special instructions
Action s are blocked by this interceptor.
3. Difference between filter and interceptor
The filter can be simply understood as "take what you want". The filter focuses on web requests; Interceptors can be simply understood as "reject what you want". Interceptors focus on method calls, such as intercepting sensitive words.
3.1. The interceptor is implemented based on java reflection mechanism, while the filter is implemented based on function callback. (some people say that interceptors are implemented based on dynamic agents)
3.2. The interceptor does not depend on the servlet container, and the filter depends on the servlet container.
3.3. Interceptors only work on actions, and filters can work on all requests.
3.4. The interceptor can access the objects in the Action context and value stack, but the filter cannot.
3.5 in the life cycle of Action, the interceptor can be called multiple times, while the filter can only be called once when the container is initialized.

2. Based on SpringBoot example

Startup class

//Remove auto configuration dataSource
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@ServletComponentScan
public class TestApplication {
	public static void main(String[] args) {
		SpringApplication.run(TestApplication.class, args);
	}
}

Concrete implementation

@RestController
@RequestMapping("/test")
public class Test1 {
	@PostMapping("/a")
	public void A() {
		System.out.println("aaa");
	}
}


class InterceptorTest extends HandlerInterceptorAdapter{
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("preHandle");
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("postHandle");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("afterCompletion");
	}
}

//Register in container
@Configuration
class InterceptorConfig implements WebMvcConfigurer{
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new InterceptorTest()).addPathPatterns("/**");
	}
	
}

Tags: Spring

Posted by T.Stedel on Mon, 23 May 2022 13:04:46 +0300