Spring Web MVC 的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理。
HandlerInterceptor接口主要定义了三个方法:
1. boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handle)方法:该方法将在请求处理之前进行调用,只有该方法返回true,才会继续执行后续的Interceptor和Controller,当返回值为true 时就会继续调用下一个Interceptor的preHandle 方法,如果已经是最后一个Interceptor的时候就会是调用当前请求的Controller方法;
2. void postHandle (HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView)方法:该方法将在请求处理之后,DispatcherServlet进行视图返回渲染之前进行调用,可以在这个方法中对Controller 处理之后的ModelAndView 对象进行操作。(这里可在返回用户前对模型数据进行加工处理,比如这里加入公用信息以便页面显示)
3. void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex)方法:该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行,该方法将在整个请求结束之后,也就是在DispatcherServlet 渲染了对应的视图之后执行。用于进行资源清理。
1.拦截器配置
1.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"/>
1.2针对所有mapping配置全局拦截器
<!--拦截器 --> <mvc:interceptors> <!--多个拦截器,顺序执行 --> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="cn.keduox.filter.HandlerInterceptor1"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="cn.keduox.filter.HandlerInterceptor2"></bean> </mvc:interceptor> </mvc:interceptors>
2.拦截器Handler
用户访问其他页面时,从seesion中获取到用户,未登录则重定向到登录页面。
3.用户登录ControllerPublic 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; }
//登陆提交 //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"; }