0 目录





1 Spring MVC拦截器流程图

2 Spring Web MVC 的处理器拦截器

类似于Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理
HandlerInterceptor接口主要定义了三个方法:
2.1 boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handle)
该方法将在请求处理之前进行调用,只有当该方法返回true时,才会继续调用下一个Interceptor的preHandle(),如果已是最后一个Interceptor就会是调用当前请求的Controller
2.2 void postHandle (HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView)
该方法将在请求处理之后,DispatcherServlet进行视图返回渲染之前进行调用,可以在这个方法中对Controller处理之后的ModelAndView对象进行操作(比如这里加入公用信息以便页面显示)
2.3 void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex)
该方法也是需要当前对应的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>
4 拦截器Handler
用户访问其他页面时,从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;
}3.用户登录Controller
//登陆提交
//userid:用户账号,pwd:密码
@RequestMapping("/login")
public String loginsubmit(HttpSession session,String userid,String pwd)throws Exception{
//向session记录用户身份信息
session.setAttribute("activeUser", userid);
return "redirect:item/queryItem.action";
}
//退出
@RequestMapping("/logout")
public String logout(HttpSession session)throws Exception{
//session过期
session.invalidate();
return "redirect:item/queryItem.action";
}
作者:芥末无疆sss
链接:https://www.jianshu.com/p/680f378c5e94
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
随时随地看视频