[SpringMVC] SpringMVC Interceptor Summary

[SpringMVC] SpringMVC interceptor

The interceptor (interceptor) in SpringMVC is similar to the filter (Filter) in Servlet, which is mainly used to intercept user requests and process them. For example, permission verification, judging login status, etc.


Note: If you are also a beginner in SSM, I personally recommend the book "Spring+SpringMVC+MyBatis Learning from Scratch" (Tsinghua University Press). This book can be a good introduction to the SSM framework with some video tutorials on Bilibili.

1. Implementation of SpringMVC interceptor

  • Interceptors using SpringMVC are usually implemented in the following two ways:

    • One is defined by implementing the HandlerInterceptor interface or an implementation class that inherits the HandlerInterceptor interface.
    • The other is defined by implementing the WebRequestInterceptor interface or an implementation class that inherits the WebRequestInterceptor interface.
  • In practical applications, it is usually implemented by inheriting the HandlerInterceptor interface, as follows:

    package com.Etui.interceptor;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class LoginInterceptor implements HandlerInterceptor {
          
          
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          
          
    
            if(request.getSession().getAttribute("user") == null) {
          
          
                request.setAttribute("msg", "登录失败,请重新登录!");
                request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
            }
    
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
          
          
            HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
          
          
            HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        }
    }
    
  • As can be seen from the above code, the custom interceptor class implements the HandlerInterceptor interface and implements the three methods in the interface. The details of these three methods are as follows:

    • preHandler() method: This method is executed before the controller method , and the return value is Boolean, indicating whether to interrupt subsequent operations. When the return value is true, continue to execute downward; when the return value is false, interrupt all operations (including calling the next interceptor and method execution in the controller class, etc.).
    • postHandler() method: This method is executed after the controller method and before parsing the view . Further modifications to models and views in the request domain can be made through this method.
    • afterCompletion() method: This method is executed after the entire request is completed and the view rendering is completed. You can use this method to achieve some resource cleaning, log information and other tasks.

2. Configure the interceptor in the springmvc configuration file

Before the custom interceptor takes effect, it needs to be configured in the SpringMVC configuration file.

<!-- 注册拦截器 -->
<mvc:interceptors>
    <mvc:interceptor>
        <bean class="com.Etui.interceptor.UserInterceptor" ></bean>
        <mvc:mapping path="/**"/>
        <mvc:exclude-mapping path="/showLogin"/>
        <mvc:exclude-mapping path="/login"/>
        <bean class="com.Etui.interceptor.LoginInterceptor"></bean>
    </mvc:interceptor>
</mvc:interceptors>
  • Parse:

    • The sub-element <bean> of <mvc:interceptors> defines a global interceptor that intercepts all requests;
    • < mvc:interceptor > defines the interceptor of the specified path, which will take effect on the request under the specified path.
    • The sub-element <mvc:mapping> of <mvc:interceptor> is used to configure the path of the interceptor, and the path is defined in its path attribute;
    • The sub-element <mvc:exclude-mapping> of <mvc:interceptor> is used to configure paths that do not need to be intercepted;
    • The sub-element <bean> of <mvc:interceptor> is used to specify the target of the current interceptor.
  • Note :

    The elements in < mvc:interceptor > must be in the order of < mvc:mapping > ... < mvc:exclude-mapping > ... < bean >, otherwise the file will report an error.

3. The execution process of the interceptor

(1) Execution process of a single interceptor

  • If only one interceptor is defined in the project, the program will first execute the preHandle() method in the interceptor class. If the return value is true, the program will continue to execute the method in the processor, otherwise it will not execute downward; After the processing of the business processor is completed, the postHandler() method will be executed, and then the response will be returned to the client through the DispatcherServlet; the afterCompletion() method will be executed only after the DispatcherServlet has processed the request.
    insert image description here

(2) Execution process of multiple interceptors

  • When there are multiple interceptors working at the same time, their preHandler() methods will be executed in accordance with the configuration order of the interceptors in the configuration file, and their postHandler() method and afterCompletion() method will be executed in accordance with the reverse configuration order.
    insert image description here

Over!

Guess you like

Origin blog.csdn.net/m0_47015897/article/details/124566372