Interceptors in spring MVC framework

Come on, new era worker!

Spring MVC detailed environment configuration and introduction
Spring MVC response data and results view
Spring MVC implements three file upload methods
Exception handling and friendly pages of Spring MVC

Before implementation, configure the Spring MVC environment. Refer to the above article

1. Overview of interceptors

  1. Interceptors in spring MVC framework are used to preprocess and post process processors.
  2. The interceptor chain can be defined. The connector chain is to form a chain of interceptors in a certain order. When accessing the intercepted methods, the interceptor chain
    Interceptors in are executed in a defined order.
  3. The functions of interceptors and filters are similar and different
    1. Filters are part of the Servlet specification, and any framework can use filter technology.
    2. Interceptors are unique to the spring MVC framework.
    3. The filter is configured with / *, which can intercept any resource.
    4. The interceptor will only intercept the methods in the controller.
  4. Interceptor is also an implementation of AOP
  5. To customize the interceptor, you need to implement the HandlerInterceptor interface.

2. Custom interceptor

The code is as follows:

package com.itboy.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
        import org.springframework.web.servlet.ModelAndView;

        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;

/**custom interceptor 
 * @author wh
 * @date 2021 22:03, November 19
 */
public class MyInterceptor1 implements HandlerInterceptor{
    /**
     *
     * preHandle Method preprocessing intercepts before the controller
     * You can log in and jump successfully
     * return true Release and execute the next interceptor. If not, select the controller
     * return false No release, the controller will not execute later, but you can use request and response to call to other pages
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor Performed 1,,,,Front 111");
        // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);
        return true;
    }

    /**Post execution method
     *  postHandle The method is executed after the controller
     *  Can handle
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor1 Yes,,,,Rear 111");
        //  request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);
    }

    /** Resources can be released
     *  afterCompletion The method is to run after all pages are executed
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor1 Yes,,,,Last run 111");
    }
}

Spring mvc.xml configuration interceptor

    <!--Configuring Interceptors -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--Method to intercept
            /**: Intercept all-->
            <mvc:mapping path="/user/*"/>
            <!--Don't intercept-->
            <!--<mvc:exclude-mapping path=""></mvc:exclude-mapping>-->
            <!--Configure interception object-->
            <bean class="com.itboy.interceptor.MyInterceptor1"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

3. usercontroller controller

package com.itboy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * @author wh
 * @date 2021 21:27, November 19
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    @RequestMapping("/interecptor")
    public String interecptor() {
        System.out.println("interecptor Method is executed...");
        return "success";
    }
}

An interceptor execution process

1. First, request the page to pass through the interceptor. The preHandle method of the custom class MyInterceptor1 returns true, and then execute the UserController. If false is returned, the following UserController will not be executed
2. The posthandle method is executed after the UserController is executed
3. The aftercompletion method is executed after all pages are executed, that is, the final execution. It can release resources, such as stream s

4. Configure the second interceptor

Just copy a copy of the custom interceptor

package com.itboy.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**custom interceptor 
 * @author wh
 * @date 2021 22:03, November 19
 */
public class MyInterceptor2 implements HandlerInterceptor{
    /**
     *
     * preHandle Method preprocessing intercepts before the controller
     * You can log in and jump successfully
     * return true Release and execute the next interceptor. If not, select the controller
     * return false No release, the controller will not execute later, but you can use request and response to call to other pages
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor2 Yes,,,,Front 222");
      // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);
        return true;
    }

    /**
     *  The postHandle method is executed after the controller
     *  Can handle
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor2 Yes,,,,Rear 222");
      //  request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);
    }

    /**
     * Resources can be released. The success after completion method runs after all pages are executed
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor2 Yes,,,,Last run 222");
    }
}

Configure an interceptor in springmvc.xml

  <!--Configure the second interceptor-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--Method to intercept
            /**: Intercept all-->
            <mvc:mapping path="/user/*"/>
            <!--Don't intercept-->
            <!--<mvc:exclude-mapping path=""></mvc:exclude-mapping>-->
            <!--Configure interception object-->
            <bean class="com.itboy.interceptor.MyInterceptor2"></bean>
        </mvc:interceptor>

Two interceptor execution processes:

1. Execute the preHandle() of the first interceptor before executing the second preHandle()
2. Then execute the method of the controller
3. Execute the second interceptor postHandle(), and execute the first postHandle()
4. Execute the second interceptor after completion(), and execute the first after completion()

Running screenshot

Keywords: Java Spring MVC

Added by Reaper0167 on Fri, 19 Nov 2021 18:39:28 +0200