zoukankan      html  css  js  c++  java
  • spring mvc 用cookie和拦截器实现自动登录(/免登录)

    Cookie/Session机制详解:http://blog.csdn.net/fangaoxin/article/details/6952954

    SpringMVC记住密码功能:http://blog.csdn.net/liupeng_family/article/details/38420963?utm_source=tuicool&utm_medium=referral

    SpringMVC中使用Interceptor拦截器:http://elim.iteye.com/blog/1750680


    登录Controller中,通过登录验证后:

    1. if(autoLoginTimeout > 0){  
    2.     //自动登录cookie  
    3.     Cookie userNameCookie = new Cookie("loginUserName", user.getUserName());  
    4.     Cookie passwordCookie = new Cookie("loginPassword", user.getPassword());  
    5.     userNameCookie.setMaxAge(autoLoginTimeout);  
    6.     userNameCookie.setPath("/");  
    7.     passwordCookie.setMaxAge(autoLoginTimeout);  
    8.     passwordCookie.setPath("/");  
    9.     response.addCookie(userNameCookie);  
    10.     response.addCookie(passwordCookie);  
    11. }  

    (注:如果不设置cookie的path,会默认设为当前路径,所以最好统一设置一个path,否则登出时可能会发现并没有删除登录时的cookie。

        附:Cookie跨域操作 http://www.iteye.com/topic/34400

    若退出登录,则删除cookie:

    1. @RequestMapping("/logout")  
    2. public String logout(HttpServletRequest request, HttpServletResponse response, Model model){  
    3.     User loginUser = (User) request.getSession().getAttribute("loginUser");  
    4.       
    5.     //删除登录cookie  
    6.     Cookie userNameCookie = new Cookie("loginUserName", loginUser.getUserName());  
    7.     Cookie passwordCookie = new Cookie("loginPassword", loginUser.getPassword());  
    8.     userNameCookie.setMaxAge(0);  
    9.     userNameCookie.setPath("/");  
    10.     passwordCookie.setMaxAge(0);  
    11.     passwordCookie.setPath("/");  
    12.     response.addCookie(userNameCookie);  
    13.     response.addCookie(passwordCookie);  
    14.       
    15.     request.getSession().removeAttribute("loginUser");  
    16.       
    17.     return "redirect:xxx";  
    18. }  


    拦截器——用户未登录时检查cookie并实现自动登录(/免登录):

    1. public class LoginInterceptor implements HandlerInterceptor {  
    2.       
    3.     @Resource    
    4.     private UserService userService;  
    5.       
    6.     /**  
    7.      * preHandle方法是进行处理器拦截用的,该方法将在Controller处理之前进行调用,SpringMVC中的Interceptor拦截器是链式的,可以同时存在  
    8.      * 多个Interceptor,然后SpringMVC会根据声明的前后顺序一个接一个的执行,而且所有的Interceptor中的preHandle方法都会在  
    9.      * Controller方法调用之前调用。SpringMVC的这种Interceptor链式结构也是可以进行中断的,这种中断方式是令preHandle的返  
    10.      * 回值为false,当preHandle的返回值为false的时候整个请求就结束了。  
    11.      */    
    12.     @Override  
    13.     public boolean preHandle(HttpServletRequest request,  
    14.             HttpServletResponse response, Object handler) throws Exception {  
    15.         User loginUser = (User) request.getSession().getAttribute("loginUser");  
    16.           
    17.         if(loginUser == null){  
    18.             String loginCookieUserName = "";  
    19.             String loginCookiePassword = "";  
    20.               
    21.             Cookie[] cookies = request.getCookies();  
    22.             if(null!=cookies){    
    23.                 for(Cookie cookie : cookies){    
    24.                     //if("/".equals(cookie.getPath())){ //getPath为null  
    25.                         if("loginUserName".equals(cookie.getName())){  
    26.                             loginCookieUserName = cookie.getValue();  
    27.                         }else if("loginPassword".equals(cookie.getName())){  
    28.                             loginCookiePassword = cookie.getValue();  
    29.                         }  
    30.                     //}  
    31.                 }    
    32.                 if(!"".equals(loginCookieUserName) && !"".equals(loginCookiePassword)){  
    33.                     User user = userService.getUserByName(loginCookieUserName);  
    34.                     if(loginCookiePassword.equals(user.getPassword())){  
    35.                         request.getSession().setAttribute("loginUser", user);  
    36.                     }  
    37.                 }  
    38.             }   
    39.         }  
    40.         return true;  
    41.     }  
    42.   
    43.     /**  
    44.      * 这个方法只会在当前这个Interceptor的preHandle方法返回值为true的时候才会执行。postHandle是进行处理器拦截用的,它的执行时间是在处理器进行处理之  
    45.      * 后,也就是在Controller的方法调用之后执行,但是它会在DispatcherServlet进行视图的渲染之前执行,也就是说在这个方法中你可以对ModelAndView进行操  
    46.      * 作。这个方法的链式结构跟正常访问的方向是相反的,也就是说先声明的Interceptor拦截器该方法反而会后调用,这跟Struts2里面的拦截器的执行过程有点像,  
    47.      * 只是Struts2里面的intercept方法中要手动的调用ActionInvocation的invoke方法,Struts2中调用ActionInvocation的invoke方法就是调用下一个Interceptor  
    48.      * 或者是调用action,然后要在Interceptor之前调用的内容都写在调用invoke之前,要在Interceptor之后调用的内容都写在调用invoke方法之后。  
    49.      */  
    50.     @Override  
    51.     public void postHandle(HttpServletRequest request,  
    52.             HttpServletResponse response, Object handler,  
    53.             ModelAndView modelAndView) throws Exception {  
    54.         // TODO Auto-generated method stub  
    55.           
    56.     }  
    57.   
    58.     /**  
    59.      * 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行。该方法将在整个请求完成之后,也就是DispatcherServlet渲染了视图执行,  
    60.      * 这个方法的主要作用是用于清理资源的,当然这个方法也只能在当前这个Interceptor的preHandle方法的返回值为true时才会执行。  
    61.      */   
    62.     @Override  
    63.     public void afterCompletion(HttpServletRequest request,  
    64.             HttpServletResponse response, Object handler, Exception ex)  
    65.             throws Exception {  
    66.         // TODO Auto-generated method stub  
    67.           
    68.     }  
    69.       
    70. }  

    (注:从浏览器获取cookie时getPath会是null,后台只能得到cookie的name和value。

        附:cookie.getPath Domain MaxAge 为null的问题:http://blog.csdn.net/eunyeon/article/details/52931370


    spring mvc配置文件:

      1. <mvc:interceptors>  
      2.     <bean class="com.interceptor.LoginInterceptor" />  
      3. </mvc:interceptors
  • 相关阅读:
    php服务器安装memcache
    [PHP脚本]安装及使用
    [PHP]针对外服务器mail函数的php.ini配置
    [COBOL]安装配置及大型机模拟Hercules配置
    [Sqlite3].help中的命令介绍
    [NavigatLite4Mysql]DB管理工具使用
    [MS-SQLserver2005]Windows64位安装问题
    [MS-SQL]20130806_LocalDB_DOS命令使用
    [MS-SQL]20130806_LocalDB安装
    [MS]Microsoft SQL Server 2008 R2 开发版/企业版/标准版
  • 原文地址:https://www.cnblogs.com/qianzf/p/7473890.html
Copyright © 2011-2022 走看看