1. Interceptor
1. Interceptor configuration
- Interceptors in SpringMVC are used to intercept the execution of controller methods
- Interceptors in SpringMVC need to implement HandlerInterceptor
- The SpringMVC interceptor must be configured in the SpringMVC configuration file
① Create an interceptor and inherit the interface HandlerInterceptor.
@Component
public class FirstInterceptor 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 {
}
}
② Configure the interceptor in the springMVC configuration file
<!--拦截器1 拦截所有的请求-->
<mvc:interceptors>
<bean class="com.atguigu.interceptor.FirstInterceptor"></bean>
</mvc:interceptors>
<!-- Intercept all requests except /-->
<!--拦截器2 拦截所有的请求-->
<mvc:interceptors>
<mvc:interceptor>
<!--拦截所有的请求,除了/-->
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/"/>
<ref bean="firstInterceptor"></ref>
</mvc:interceptor>
</mvc:interceptors>
2. Three abstract methods of interceptors
① preHandle : Execute preHandle() before the controller method is executed. The preHandle method returns true to release and call the controller method. Return False to intercept and not call the controller method.
②postHandle: Execute postHandle() after the controller method is executed
③afterComplation: After processing the view and model data, execute afterComplation after rendering the view
3. Execution order of multiple interceptors
If preHandle() of each interceptor returns true
At this time, the execution order of multiple interceptors is related to the configuration order of the interceptors in the SpringMVC configuration file:
preHandle() will be executed in the order of configuration, while postHandle() and afterComplation() will be executed in reverse order of configuration
If preHandle() of an interceptor returns false
preHandle() returns false and preHandle() of its previous interceptor will be executed, postHandle() will not be executed, and afterComplation() of the interceptor before the interceptor returning false will be executed