Spring MVC advanced - how to use interceptors correctly? Case explanation

Keywords: Java Spring JSP

Spring MVC: interceptor

Implemented the HandlerInterceptor interface.

Function: used to intercept the controller

 

2, Define an interceptor

1. Environment construction

@Component
public class Demo1Interceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return false;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}In addition, pay attention to: except SpringMvc. I've also put together the latest JAVA Architecture project practical course and large factory interview question bank, you can get 783802103 for free if you are interested in it. Do not enter without foundation!

 

2. Register interceptor

@Configuration
@ComponentScan(basePackages={"com.czxy"})
@EnableWebMvc
public class MVCConfiguration extends WebMvcConfigurerAdapter{

    /**
     * view resolver
     * @return
     */
    @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver(){
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/");
        internalResourceViewResolver.setSuffix(".jsp");
        return internalResourceViewResolver;
    }

    /*
    * Register interceptor
    * */
    //1. Define a member variable to get the interceptor object (variable name = class name small hump)
    @Resource
    private HandlerInterceptor demo1Interceptor;
    //2. Override register interceptor method, register interceptor
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //Add interceptor (register interceptor)
        InterceptorRegistration i1 = registry.addInterceptor(demo1Interceptor);
        //Set the interception path of the interceptor
        i1.addPathPatterns("/**");
    }
}

 

3. Code implementation

Demo1Interceptor:

@Component
public class Demo1Interceptor implements HandlerInterceptor {
    /*
    * Pretreatment method:
    *       Execute before executing a controller
    *       true:Execution controller method (release)
    *       false: Intercept, do not execute controller method (do not release, intercept)
    * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("demo1Interceptor-Pretreatment method");
        return true;
    }
    /*
    * Post processing method:
    *       After a controller method is executed
    *       ModelAndView: Used to modify the jump path of the controller
    * */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("demo1Interceptor-Post processing method");
    }
    /*
    * Completion method:
    *       After all functions are executed, the method is executed finally
    * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("demo1Interceptor-Completion method");
    }
}

 

 

4. Precautions: three methods of interceptors

  • preHandle: preprocessing method

Before the controller is executed.

Special: control whether the controller executes through the return value.

true: release, executed by controller

false: do not release or intercept, controller does not execute

Applicable environment: suitable for judgment before executing the controller.

 

  • postHandle: post processing method

Precondition: 1. Preprocessing method, return value true

2. The controller is normal

Execute after controller execution.

Applicable environment: applicable to modifying jump path / jump mode after executing controller

 

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    modelAndView.setViewName("errorMsg");
    System.out.println("demo1Interceptor-Post processing method");
}

 

  • afterCompletion: method after completion

Precondition: preprocessing method, return value true

After all processes are executed, they must be executed anyway, which is equivalent to finally

Applicable environment: if no exception handler is set, the method can handle exceptions after completion

 

/*
* Method after completion:
*       After all functions are executed, the method is executed finally
* */
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    System.out.println("The exception of the controller is:"+ex);
    System.out.println("demo1Interceptor-Completion method");
}

 

 

5. Precautions: execution sequence diagram

 

 

 

6. Precautions: difference between filter and interceptor

 

 

  • filter:

① Implemented the Filter interface

② It is used to intercept requests to the server, or request forwarding, including, and errors within the server

③ The filter executes before the servlet

④ Filters are web components that block all web resources

 

  • Interceptor:

① Implemented the HandlerInterceptor interface

② It is only used to intercept requests to the controller, or to jump the request forwarding of the controller within the server

③ The interceptor executes after the servlet and before the controller

④ Interceptor is the spring MVC component, which is responsible for intercepting the controller

 

 

 

3, Define multiple interceptors

1. Code implementation

Demo2Interceptor:

@Component
public class Demo2Interceptor implements HandlerInterceptor {
    /*
    * Pretreatment method:
    *       Execute before executing a controller
    *       true:Execution controller method (release)
    *       false: Intercept, do not execute controller method (do not release, intercept)
    * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("demo2Interceptor-Pretreatment method");
        return true;
    }
    /*
    * Post processing method:
    *       After a controller method is executed
    *       ModelAndView: Used to modify the jump path of the controller.
    * */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        modelAndView.setViewName("errorMsg");
        System.out.println("demo2Interceptor-Post processing method");
    }
    /*
    * Method after completion:
    *       After all functions are executed, the method is executed finally
    * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//         System.out.println("exception of controller:" + ex);
        System.out.println("demo2Interceptor-Completion method");
    }
}

 

MVC configuration class:

@Configuration
@ComponentScan(basePackages={"com.czxy"})
@EnableWebMvc
public class MVCConfiguration extends WebMvcConfigurerAdapter{

    /**
     * view resolver
     * @return
     */
    @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver(){
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/");
        internalResourceViewResolver.setSuffix(".jsp");
        return internalResourceViewResolver;
    }

    /*
    * Register interceptor
    * */
    //1. Define a member variable to get the interceptor object (variable name = class name small hump)
    @Resource
    private HandlerInterceptor demo1Interceptor;
    @Resource
    private HandlerInterceptor demo2Interceptor;
    //2. Override register interceptor method, register interceptor
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //Add interceptor (register interceptor)
        InterceptorRegistration i1 = registry.addInterceptor(demo1Interceptor);
        //Set the interception path of the interceptor
        i1.addPathPatterns("/**");

        //Add interceptor (register interceptor)
        InterceptorRegistration i2 = registry.addInterceptor(demo2Interceptor);
        //Set the interception path of the interceptor
        i2.addPathPatterns("/**");
    }
}

 

 

2. Flow chart

The first to register, the first to implement.

 

 

 

 

IV. springMVC advanced interceptor wildcard settings

 

wildcard

explain

**

Any 0 ~ characters or any multi-level directory

For example, / user/**

/user/a/b/c/run1.action

/user/run1.action

 

*

Any 0 to more than one character

For example, / user/*

/user/run1.action

/user/run2.action

 

 

?

Any character

For example, / user/**

/userA/run1.action

/userb/run1.action

/userc/run1.action

 

 

Summary:

Interceptor: implements the HandlerInterceptor interface.

Interceptor: intercepts only controllers.

 

  • Pretreatment method:

Execute before the controller executes.

True: release.

False: intercept.

 

  • Post processing method:

After normal execution of the controller.

Premise: ① preprocessing method returns true

② The controller cannot throw an exception

 

  • Method after completion:

After the end of the process.

Premise: preprocessing method returns true


Last note: in addition to SpringMvc. I also collated the latest JAVA architecture project practical course and large factory interview question bank. Those who are interested can get 783802103 free of charge. Do not enter without foundation!

The text and pictures of this article come from the Internet and my own ideas. They are only for learning and communication. They have no commercial use. The copyright belongs to the original author. If you have any questions, please contact us in time for handling

Posted by emma57573 on Wed, 20 May 2020 23:03:42 -0700