Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

During project development, we may encounter the need to intercept certain browsing permissions of users, such as some public pages that do not require access permissions, and some specific pages that require login to access. This scenario can usually be handled by interceptors.

Spring MVC interceptor and Java Servlet filter function type, it is mainly to process user requests, usually in the permission verification, logging, user login status judgment and other functional scenarios.

Note: Base environment JDK 17, Spring 6.x, Tomcat 10.x

Definition of interceptor

It is usually possible to customize the interceptor definition by implementing the HandlerInterceptor interface.

HandlerInterceptor

Example code is as follows (note that my servlet is jakarta.servlet) :

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class TestInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
		The afterCompletion method is executed after the controller's processing request method has completed, that is, after the view has been rendered
        System.out.println("======= >>>> afterCompletion method execution");

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		The postHandle method is executed after the controller's processing request method call and before the view is parsed
		System.out.println("======= >>>> postHandle method execution");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// The preHandle method is executed after the controller's processing request method call and before the view is parsed
		System.out.println("======= >>>> preHandle method execution");
        return false; }}Copy the code

In the definition of the interceptor, the HandlerInterceptor interface is implemented, and three methods in the interface are implemented. The three methods are described below.

  • PreHandle method: This method is executed before the controller’s request processing method. Its return value indicates whether to interrupt subsequent operations, true indicates to continue, and false indicates to interrupt subsequent operations.
  • PostHandle method: This method is executed after the controller handles the request method call, but before the view is parsed, and allows you to make further changes to the model and view in the request domain.
  • AfterCompletion method: This method is executed after the controller’s processing request method is completed, that is, after the rendering of the view is completed. You can use this method to clean up resources and log information.

Configuration of interceptors

To make a custom interceptor work, you need to configure it in the Spring MVC configuration file. Example configuration code is as follows:

XML way

<! < MVC :interceptors> <! Configure a global interceptor to intercept all requests --> <beanclass="interceptor.TestInterceptor"/> <mvc:interceptor> <! MVC :mapping path="/ * *"/ > <! --> < MVC :exclude-mapping path=""/ > <! < MVC :interceptor> defines the < MVC :interceptor> element that intercepts only requests that match the specified pathclass="interceptor.Interceptor1"/> </mvc:interceptor> <mvc:interceptor> <! MVC :mapping path="/gotoTest"/ > <! -- Defined in the < MVC: interceptor> element, intercepting only requests that match the specified path --> <beanclass="interceptor.Interceptor2" />
    </mvc:interceptor>
</mvc:interceptors>
Copy the code

In the sample code above, the < MVC: Interceptors > element is used to configure a set of interceptors, and its children define a global interceptor that intercepts all requests. The < MVC: interceptor> element defines an interceptor that specifies a path. Its child < MVC: Mapping > is used to configure the path that the interceptor uses, as defined in its attribute path. As in the example code above, the path attribute value “/**” means to intercept all paths, and “/gotoTest” means to intercept all paths ending in “/gotoTest”. If the request path contains something that does not need to be intercepted, you can configure it using the < MVC: exclude-mapping> child element.

Note that children of the < MVC: interceptor> element must be provided in accordance with < MVC: mapping… />, < MVC: exclude-mapping… / >, < bean… /> order configuration.

Annotation way

We annotate the configuration as follows:

/** * Note: The WebMvcConfigurerAdapter has been removed from Spring 6
@Configuration
public class TestConfiguration implements WebMvcConfigurer {

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new TestInterceptor()).addPathPatterns("/app/*"); }}Copy the code

The resources

  • C.biancheng.net/view/4431.h…
  • Gitee.com/zhengsh/spr…