The interceptor

The most typical use of an interceptor is to check whether the user is logged in. After logging in, the target handler method can be executed. If not, the interceptor is redirected to the login page. Such operations would be too cumbersome to write inside each interceptor, so it would be wise to extract them uniformly. 1.HandlerInterceptor ①preHandle(

Signature: Boolean preHandle(HttpServletRequest, HttpServletResponse, Object) executes before executing the target handler method. If true, subsequent interceptor and target handler methods continue; If false is returned, it is not executed. Note: When false is returned, it is best to provide the client with a response page by way of forwarding or redirecting. (2) postHandle () method

Signature: void postHandle(HttpServletRequest, HttpServletResponse, Object, ModelAndView) executes after executing the target handler method but before rendering the view. (3) afterCompletion () method

Executed after rendering the view but before returning the response. 2. HandlerInterceptorAdapter class

Implement HandlerInterceptor interfaces need to implement all abstract methods, and can selectively override inherited HandlerInterceptorAdapter class need method, more convenient, it is recommended to use.

3. Configuration method 1 Intercept all requests

<mvc:interceptors>
    <bean class="com.interceptor.FirstInterceptor"/>
    <bean class="com.interceptor.SecondInterceptor"/>
</mvc:interceptors>
Copy the code

② Specify exactly which requests to intercept

<mvc:interceptors>
    <bean class="com.interceptor.FirstInterceptor"/>
    <bean class="com.interceptor.SecondInterceptor"/>
    <mvc:interceptor>
        <mvc:mapping path="/*"/>
        <mvc:exclude-mapping path="/specailPath"/>
        <bean class="com.interceptor.SpecialInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>
Copy the code

4. Execution order of multiple interceptors

Call the preHandle() method in positive order, execute the target handler method, call the postHandle() method, and call the afterCompletion() method in reverse order