Add some common conditional judgments to normal business logic; The conditional judgment itself is completely separate from the business logic and has nothing to do with it; Implementation of AOP ideas;

Business scenarios:

  1. Logging: Records request informationThe log, so that information monitoring, information statistics, calculationPV(Page View), etc.
  2. Permission check: For example, enter the processor check to check whether you have logged in. If you do not directly return to the login page;
  3. Performance monitoring: Sometimes the system is inexplicably slow for a certain period of time. The interceptor can record the start time of the request before it enters the processor and the end time after the processing is complete to obtain the processing time of the request (if there is a reverse proxy, such asapacheCan automatically record);
  4. Common behavior: ReadcookieGet the user information and put the user object into the request for easy use by subsequent processes, such as extractionLocale,ThemeInformation, and so on, can be implemented using interceptors if more than one processor needs it.
  5. OpenSessionInView:Hibernate, before entering the processor openSessionAnd close after completionSession.

Introduction to SpringMVC interceptor

The Interceptor Interceptor in SpringMVC is also very important and useful. Its main function is to intercept user requests and process them accordingly. It can be used for logging, for permission verification, or to determine whether a user has logged in.

The SpringMVC Interceptor intercepts requests through the HandlerInterceptor. Defining an Interceptor in SpringMVC is very simple. There are two main ways to define an Interceptor class. The first way is to define an Interceptor class that implements the Spring **HandlerInterceptor** interface. Or is this class implements HandlerInterceptor interface classes, such as the Spring has been HandlerInterceptor interface provided by the abstract class HandlerInterceptorAdapter * * * *. The second way is to implement Spring’s WebRequestInterceptor interface, or to inherit a class that implements WebRequestInterceptor.

2. SpringMVC interceptor usage steps

2.1 Defines a class for interceptors

Let this class inherit from other classes or implement interfaces associated with interceptors; Rewrite the method inside, which implements the HandlerInterceptor interface:

public class MyInterceptor01 implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        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); }}Copy the code
  • PreHandle () : This method is called before the business processor processes the request, in which the user requests the request. Returns true if the programmer decides that the interceptor will call another interceptor, or the business handler, after intercepting the request; If the programmer decides that no other component needs to be called to handle the request, return false;

  • PostHandle () : this method ** is called after the business processor has processed the request but before the DispatcherServlet returns the response to the client. ** In this method the user requests the request.

  • AfterCompletion () : This method is called ** after the DispatcherServlet has completed processing the request, and you can perform some resource cleanup operations in this method;

2.2 Configuring Interceptors:

Configure the interceptor in the springMVC configuration file, create the interceptor class bean, and configure where to use the interceptor (Controller)

<! -- Configure interceptor -->
<! What resources did you intercept with that interceptor? -->
<mvc:interceptors>
    <mvc:interceptor>
        <! /** contains subdirectories -->
        <mvc:mapping path="/ * *"/>
        <! Access to API/url will not be blocked -->
        <mvc:exclude-mapping path="/api/*"/>
        <bean class="com.singerw.interceptor.MyInterceptor01"></bean>
    </mvc:interceptor>
</mvc:interceptors>
Copy the code

3. Order of execution of multiple interceptors

<! -- Configure interceptor -->
<! What resources did you intercept with that interceptor? -->
<mvc:interceptors>
    <mvc:interceptor>
        <! /** contains subdirectories -->
        <mvc:mapping path="/ * *"/>
        <! The url to API/will not be blocked.
        <mvc:exclude-mapping path="/api/*"/>
        <bean class="com.singerw.interceptor.MyInterceptor01"></bean>
    </mvc:interceptor>
</mvc:interceptors>

<! -- Configure interceptor -->
<! What resources did you intercept with that interceptor? -->
<mvc:interceptors>
    <mvc:interceptor>
        <! /** contains subdirectories -->
        <mvc:mapping path="/ * *"/>
        <! The url to API/will not be blocked.
        <mvc:exclude-mapping path="/api/*"/>
        <bean class="com.singerw.interceptor.MyInterceptor02"></bean>
    </mvc:interceptor>
</mvc:interceptors>
Copy the code

4. Intercept user login authentication simulation

4.1 Administrator back-end Request Interceptor:

All requests about the admin backend are intercepted, for example: /admin/ getUser

Example: AdminInterceptor

/ * * *@Author: CodeSleep
 * @Date: 2021/8/23 15:55
 * @Description: //TODO administrator backend request interceptor */
public class AdminInterceptor implements HandlerInterceptor {
    public AdminInterceptor(a) {
        System.out.println("AdminInterceptor() Constructor");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("****************AdminInterceptor_preHandle*****************");
        // Check whether user login information exists in the Httpsession if the user information is stored during the user login service.
        if (request.getSession().getAttribute("user") = =null) {
            System.out.println("User not logged in, please return to log in!");
            response.sendRedirect(request.getContextPath() + "/back/login.html");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("****************AdminInterceptor_postHandle*****************");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("****************AdminInterceptor_afterCompletion*****************");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex); }}Copy the code

[Example] SpringmVC-servlet.xml interceptor configuration:

ArticleController will intercept all requests about admin, open the way for *.html and component CSS, JS, etc., no longer intercept. Using com. Singerw. Interceptor. AdminInterceptor interceptors. After interception, the user returns to the login page. After login, the user can access the system normally.

[Example of configuring interceptor 1]

<! Configure interceptor 1-->
<mvc:interceptors>
    <mvc:interceptor>
        <! All requests to admin in ArticleController will be intercepted, /** contains subdirectories -->
        <mvc:mapping path="/admin/**"/>

        <! Open *.html and component CSS, JS, etc., no longer block -->
        <mvc:exclude-mapping path="/back/*.html"/>
        <mvc:exclude-mapping path="/component/**"/>

        <! --AdminInterceptor interceptor -->
        <bean class="com.singerw.interceptor.AdminInterceptor"></bean>
    </mvc:interceptor>
</mvc:interceptors>
Copy the code

4.2 Administrator back-end Static Resource Interceptor

All static resources on the admin backend are intercepted, such as /back/index.html, etc.

[Example] BackInterceptor

/ * * *@Author: CodeSleep
 * @Date: 2021/8/23 15:55
 * @DescriptionTODO administrator back-end access interceptor */
public class BackInterceptor implements HandlerInterceptor {

    public BackInterceptor(a) {
        System.out.println("BackInterceptor() constructor");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("****************BackInterceptor_preHandle*****************");
        // Check whether user login information exists in the Httpsession if the user information is stored during the user login service.
        if (request.getSession().getAttribute("user") = =null) {
            System.out.println("User not logged in, please return to log in!");
            response.sendRedirect(request.getContextPath() + "/back/login.html");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("****************BackInterceptor_preHandle*****************");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("****************BackInterceptor_preHandle*****************");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex); }}Copy the code

[Example] SpringmVC-servlet.xml interceptor configuration:

Springmvc-servlet. XML is configured with an administrator backend static resource interceptor, which will intercept all access to the administrator backend resources under the back path, and open the way for *.html and component CSS, JS, etc. Using com. Singerw. Interceptor. BackInterceptor interceptors, intercept after return to the login interface, can be normal access after login.

[Example of configuring interceptor 2]

<! Configure interceptor 2-->
<mvc:interceptors>
    <mvc:interceptor>
        <! -- Admin backend resources will block all access to the back path, including subdirectories -->
        <mvc:mapping path="/back/**"/>

        <! Open *.html and component CSS, JS, etc., no longer block -->
        <mvc:exclude-mapping path="/back/login.html"/>
        <mvc:exclude-mapping path="/component/**"/>

        <! BackInterceptor -->
        <bean class="com.singerw.interceptor.BackInterceptor"></bean>
    </mvc:interceptor>
</mvc:interceptors>
Copy the code

5. The difference between SpringMVC interceptors and filters in servlets

SpringMVC Interceptor: Interceptor The Servlet: Filter Remark
org.springframework.web. Servlet. HandlerInterceptor interface Javax.mail. Servlet. Filter interface Interface definition location
Java-based reflection mechanism is an implementation of AOP ideas The javaEE standard is based on function callbacks and is an implementation of AOP ideas
Spring configuration file In web.xml or at @webfilter configuration
The interceptor intercepts the entire request lifecycle before and after the specific method Filters work only around and around servlets and depend on servlets
Aop implementation and support for Spring Servlet specification and support
You can use any of Spring’s resources, business objects, data source access, etc., just by injecting objects into the interceptor Filters cannot use Spring resources directly
Called by the Spring container, instantiated by the container Is called a tomcat Spring interceptors execute later than filters