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

The interceptor

The Interceptor Interceptor in SpringMVC is very important and quite useful. Its main function is to intercept the specified user request, and carry out the corresponding pre-processing and post-processing. The interception occurs when “the processor mapper maps the processor class to execute based on the request submitted by the user and also finds the processor adapter to execute the processor class before the processor adapter executes the processor.”

Of course, when the processor mapper maps the processor class to be executed, the interceptor and processor are already combined into a processor execution chain that is returned to the central scheduler.

Execution of an interceptor

Project: Interceptor. Custom interceptors

Custom interceptor, need to implement the HandlerInterceptor interface. This interface contains three methods:

  • PreHandle (Request, Response, Object Handler) : This method is executed before the handler method executes. The return value is Boolean; if true, the processor method is followed by execution and the afterCompletion() method is placed on a special method stack to wait for execution.
  • PostHandle (Request, Response, Object Handler,modelAndView) : This method is executed after the handler method executes. A processor method does not execute if it is not eventually executed. Since the method is executed after the processor method is executed and the method parameter contains ModelAndView, the method can modify the processing result data of the processor method and change the jump direction.
  • AfterCompletion (Request, Response, Object Handler, Exception ex) : When the preHandle() method returns true, it is placed on a special stack of methods and is not executed until all work has been done to respond to the request. That is, the method is executed after the central scheduler has rendered (populated) the response page, and operating on the ModelAndView does nothing for the response.

The last method performed by afterCompletion clears resources, such as adding data to the Controller method

Interceptor methods:

The sequence of methods and handler methods in the interceptor is shown below:

To put it another way, it can also be understood as follows:

(1) Register interceptors

MVC :mapping/ is used to specify the request path that the currently registered interceptor can intercept, and /** means to intercept all requests.

(2) Modify index page

(3) Modify the processor

(4) Modify the Show page

(5) Console output results