springmvc拦截器的配置

登陆认证拦截实现

 代码实现

 1 @Controller
 2 public class LoginController {
 3     @RequestMapping("/login")
 4     public String login(HttpSession session,String username,String password) throws Exception {
 5         
 6          session.setAttribute("username", username);
 7          return "redirect:items/queryItems.action";
 8     }
 9     
10     @RequestMapping("/logout")
11     public String logout(HttpSession session) throws Exception {
12         session.invalidate();
13         return "redirect:/items/queryItems.action";
14     }
15 }

LoginInterceptor.java

 1 public class LoginInterceptor implements HandlerInterceptor {
 2     
 3     //在进入handler方法之前执行
 4     //用于身份认证,身份授权 认认证不通过,拦截,不再向下执行
 5     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 6         
 7         String url = request.getRequestURI();
 8         //判断url是否是公开地址 在这里就是登录提交的地址
 9         if(url.indexOf("login.action") >= 0){
10             //放行
11             return true;
12         }
13         
14         HttpSession session = request.getSession();
15         String username = (String) session.getAttribute("username");
16         if(username != null){
17             return true;
18         }
19         //失败,跳转登录页面
20         request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
21         //false表示拦截 true表示放行
22         return false;
23     }
24     
25     //进入handler方法之后,返回modelandview之前执行
26     //将公用的模型数据传到视图,也可以在这里统一视图
27     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
28             throws Exception {
29         System.out.println("Interceptor......postHandle");
30     }
31 
32     //执行完handler方法之后执行
33     //使用统一的异常处理,统一的日志处理
34     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
35             throws Exception {
36         System.out.println("Interceptor......afterCompletion");
37     }
38     
39 }

 拦截器配置

 1 <!--拦截器 -->
 2 <mvc:interceptors>
 3     <!--多个拦截器,顺序执行 -->
 4     <!-- 登陆认证拦截器 -->
 5     <mvc:interceptor>
 6         <mvc:mapping path="/**"/>
 7         <bean class="cn.cuibusi.ssm.interceptor.LoginInterceptor"></bean>
 8     </mvc:interceptor>
 9 </mvc:interceptors>

 

posted @ 2017-05-22 20:05  崔布斯  阅读(314)  评论(0编辑  收藏  举报