0 directory
1 Spring MVC interceptor flowchart
2 Processor interceptor for Spring Web MVC
Similar to the Filter in Servlet development, it is used for pre-processing and post-processing of the processor
The HandlerInterceptor interface defines three methods
2.1 preHandle
This method will be called before the request is processed, and only when it returns true will it continue calling the next Interceptor’s preHandle(), or the Controller calling the current request if it is already the last Interceptor
2.2 postHandle
This method will be called after the request has been processed and before the DispatcherServlet has rendered the view back. You can operate on the ModelAndView object after the Controller has processed it in this method (for example, adding public information here for page display).
2.3 afterCompletion
This method is executed only when the corresponding Interceptor’s preHandle method returns true. This method is executed after the entire request is complete, after the DispatcherServlet has rendered the corresponding view
3 Interceptor configuration
3.1 Configuration for a Mapping interceptor
<bean
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="handlerInterceptor1"/>
<ref bean="handlerInterceptor2"/>
</list>
</property>
</bean>
<bean id="handlerInterceptor1"class="springmvc.intercapter.HandlerInterceptor1"/>
<bean id="handlerInterceptor2"class="springmvc.intercapter.HandlerInterceptor2"/>
Copy the code
3.2 Configuring global Interceptors for all Mapping
<! -- Interceptor -->
<mvc:interceptors>
<! -- Multiple interceptors executed in sequence -->
<mvc:interceptor>
<mvc:mapping path="/ * *"/>
<bean class="com.sss.filter.HandlerInterceptor1"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/ * *"/>
<bean class="com.sss.filter.HandlerInterceptor2"></bean>
</mvc:interceptor>
</mvc:interceptors>
Copy the code
4 practice
When a user accesses another page, the user is obtained from Seesion. If the user does not log in, the user is redirected to the login page.
Public class LoginInterceptor implements HandlerInterceptor{
@Override
Public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// If the login page is displayed, the login page is allowed
if(request.getRequestURI().indexOf("login.action") > =0) {return true;
}
HttpSession session = request.getSession();
// If the user is already logged in, the system permits the login
if(session.getAttribute("user")! =null) {return true;
}
// The user did not login to the login page
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
return false;
}
Copy the code