The configuration and application of Springmvc interceptor

introduces the interceptor in springmvc learning. We often intercept when we access the project to determine whether the user is logged in, etc. It is similar to the filter filter we use in servlet

@@1. So where is the springmvc interceptor intercepted (execution rules)? How is the

2.springmvc interceptor applied in the project?

We define an interceptor class, implement the HandlerInterceptor interface:

Then we configure the interception in the springmvc configuration file

Only when the interceptor method preHandle returns true, You can execute the following two methods

So if we configure multiple interceptors, then how about his running rules, let's configure multiple interceptor tests

<!-- SPringmvc interceptor , you can put more than one interceptor -->
       <mvc:interceptors>
       <mvc:interceptor>
         <!-- Intercepted path -->
           <mvc:mapping path="/**" />
         <!-- Defined interceptor class -->
           <bean class="com.itheima.springmvc.interceptor.interceptor3"/>
       </mvc:interceptor>
           <mvc:interceptor>
         <!-- Intercepted path -->
           <mvc:mapping path="/**" />
         <!-- Defined interceptor class -->
           <bean class="com.itheima.springmvc.interceptor.interceptor4"/>
       </mvc:interceptor>
       </mvc:interceptors>
package com.itheima.springmvc.interceptor;

Import javax.servlet.http.HttpServletRequest;
Import javax.servlet.http.HttpServletResponse;

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

Public class interceptor4 implements HandlerInterceptor {
Public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
System.out.println("preHandle4 method is executed before the execution of the controller method");
Return true;
}
Public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
Throws Exception {
System.out.println("postHandle4 method is executed after the execution of the method");

}
Public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
Throws Exception {
System.out.println("afterCompletion4 method is executed after the jsp-->html page is rendered");

}}

We look at the results of the run

summary:

preHandle in the order of the interceptor definition call

postHandler according to the interceptor definition reverse order

afterCompletion press the interceptor definition reverse order call

postHandler in the interceptor chain all interceptors returned successfully

afterCompletionpreHandle