1

从原理带你掌握Spring MVC拦截处理器知识

 2 years ago
source link: https://my.oschina.net/u/4526289/blog/5313229
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

摘要:SpringWebMVC的处理器拦截器,类似于Servlet开发中的过滤器Filter,用于处理器进行预处理和后处理。

本文分享自华为云社区《不讲废话,全程干货,0基础带你学习SpringMVC拦截处理器》,作者:JavaEdge 。

1 工作原理流程图

v2-7102648c796d198b71261b1b078133f6_720w.jpg

2 Spring Web MVC 的处理器拦截器

  • HandlerInterceptor

v2-b816c204ec4783e2897b0947d0f8ddc6_720w.jpg

类似Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理。

HandlerInterceptor接口定义了如下方法:

2.1 preHandle

该方法将在请求处理之前进行调用,只有当该方法返回true时,才会继续调用下一个Interceptor的preHandle(),如果已是最后一个Interceptor就会是调用当前请求的Controller

2.2 postHandle

该方法将在请求处理后,DispatcherServlet进行视图返回渲染之前进行调用,可以在这个方法中对Controller处理之后的ModelAndView对象进行操作(比如这里加入公用信息以便页面显示)

2.3 afterCompletion

该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行,该方法将在整个请求结束之后,也就是在DispatcherServlet 渲染了对应的视图之后执行,用于资源清理。

3 拦截器配置

3.1 针对某种mapping拦截器配置

 <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"/> 

3.2 针对所有mapping配置全局拦截器

<!--拦截器 -->  
<mvc:interceptors>  
   <!--多个拦截器,顺序执行 -->  
   <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>  

用户访问其他页面时,从Seesion中获取到用户,未登录则重定向到登录页面。

Public class LoginInterceptor implements HandlerInterceptor{   
    @Override  
    Public boolean preHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler) throws Exception {  
 
        //如果是登录页面则放行  
        if(request.getRequestURI().indexOf("login.action")>=0){  
            return true;  
        }  
        HttpSession session = request.getSession();  
        //如果用户已登录也放行  
        if(session.getAttribute("user")!=null){  
            return true;  
        }  
        //用户没有登录挑战到登录页面  
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);  
 
        return false;  
    }  

点击关注,第一时间了解华为云新鲜技术~


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK