Make writing a habit together! This is the 11th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

1. Interceptor

Spring MVC provides an interceptor mechanism that allows some interception before the target method is run, or some other processing after the target method is run

The interceptor in Spring MVC is the HandlerInterceptor interface, which contains three methods

  • PreHandler: This method is invoked before the business processing request, in the method to deal with the user requests, if you need the interceptors to intercept the request after also call other interceptors, or a processor for processing business, return True not only release request, if you don’t need to call other component returns false, does not release the request
  • PostHandler: This method is called after the business processor has processed the request, but before the DispatcherServlet returns the response to the client, in which the user requests the request
  • AfterCompletion: This method is called after the DispatcherServlet has fully processed the request, and you can perform some resource cleanup operations in this method

Custom interceptors

Copy the spring-MVC-Ajax project, rename it spring-MVC-Handler, and remove the classes and files except for the configuration.

The normal flow of interceptors

A new HandlerInterceptorSamplerController, defined in the Controller interceptor method, test the custom interceptors, and returns success page

@Controller
public class HandlerInterceptorSamplerController {

    @RequestMapping("/interceptor")
    public String interceptor(a){

        System.out.println("Interceptor method called");
        return "success"; }}Copy the code

Add a hyperlink to the index.jsp page

<a href="/interceptor"> Intercept the request </a>Copy the code

New Interceptor package, create a custom interceptor ZuluInterceptor, custom interceptor must implement the HandlerInterceptor interface, in the interceptor each method added log printing

public class ZuluInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println(this.getClass().getName() + "The preHandler method is running.");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println(this.getClass().getName() + "PostHandle method is running.");
        System.out.println(modelAndView.getViewName());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(this.getClass().getName() + "AfterCompletion method runs."); }}Copy the code

Register the interceptor in the Spring MVC configuration file and configure which requests the interceptor intercepts

<mvc:interceptors>
    <! The first way to configure an interceptor is to block all requests.
    <bean class="com.citi.interceptor.ZuluInterceptor"></bean>
</mvc:interceptors>
Copy the code

To launch the app, click the hyperlink on the home page

Based on the console output, the custom interceptor was successfully invoked

So the normal flow for an interceptor is: interceptor preHandler method -> target method -> interceptor postHandler method -> page render -> interceptor afterCompletion method

Exception flow for interceptors

Abnormal flow 1-preHandler returns false

Return false in the ZuluInterceptor preHandler method, start again, and click the hyperlink on the home pageThe console outputs only the execution of the preHandler method, so as long as preHandler returns false, there will be no further execution of the method without release.

Exception Flow 2 – Other exceptions

Keep the preHandler method returning true, and add exception code to the return page of the Interceptor method in the Controller

@RequestMapping("/interceptor")
public String interceptor(a){

    System.out.println("Interceptor method called");
    // Exception code
    int i = 10 / 0;
    return "success";
}
Copy the code

Restart the app again and click the hyperlink on the pageAn error occurs due to abnormal code on the page

The console now executes the afterCompletion method

Order of execution of multiple interceptors

Copy ZuluInterceptor into the interceptor package and rename it DeltaInterceptor. Register the newly defined interceptor in the Spring MVC configuration file

<mvc:interceptors>
    <! The first way to configure an interceptor is to block all requests.
    <bean class="com.citi.interceptor.ZuluInterceptor"></bean>
    <bean class="com.citi.interceptor.DeltaInterceptor"></bean>
</mvc:interceptors>
Copy the code

Log out of the interceptor method in the Controller, restart, and click the plug link on the page

It can be determined from the console output that the Zulu interceptor’s preHandler method is restricted, then the Delta interceptor’s preHandler method is executed, then the target method is executed, then the Delta interceptor’s postHandler is called, Execute the Zulu interceptor’s postHandler, execute the Delta interceptor’s afterCompletion method, and finally execute the Zulu interceptor’s afterCompletion method

Interception sequence: Interceptor interception sequence adjusts the configuration sequence of interceptors based on the configuration sequence

<mvc:interceptors>
    <! The first way to configure an interceptor is to block all requests.
    <bean class="com.citi.interceptor.DeltaInterceptor"></bean>
    <bean class="com.citi.interceptor.ZuluInterceptor"></bean>
</mvc:interceptors>
Copy the code

To launch again, click the hyperlink on the home pageAccording to the console output, the Delta interceptor configured first in the configuration file is executed first

Exception flow for multiple interceptors:

Keep Delta interceptors first and Zulu interceptors last in the Spring MVC configuration file. If the Delta interceptor does not pass, there are no subsequent calls; What happens if the Zulu interceptor is not cleared?

Return false in the Zulu interceptor, restart the application, and click the hyperlink on the home page

From the console output, it is clear that the Zulu interceptor is not cleared, but the Delta afterCompletion method will still execute.

The afterCompletion method of the released interceptor will always execute