SpringMVC记住密码功能

CookieTool(Cookie帮助类):

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.utcsoft.common.cookie;  
  2. import java.util.HashMap;  
  3. import java.util.Map;  
  4. import javax.servlet.http.Cookie;  
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7.   
  8. public class CookieTool {  
  9.   
  10.     /** 
  11.     * 设置cookie(接口方法) 
  12.     * @author 刘鹏 
  13.     * @param response 
  14.     * @param name  cookie名字 
  15.     * @param value cookie值 
  16.     * @param maxAge cookie生命周期  以秒为单位 
  17.     */  
  18.     public static void addCookie(HttpServletResponse response,String name,String value,int maxAge){  
  19.         Cookie cookie = new Cookie(name,value);  
  20.         cookie.setPath("/");  
  21.         if(maxAge>0){    
  22.             cookie.setMaxAge(maxAge);  
  23.         }  
  24.         response.addCookie(cookie);  
  25.         }  
  26.       
  27.     /** 
  28.     * 根据名字获取cookie(接口方法) 
  29.     * @author 刘鹏 
  30.     * @param request 
  31.     * @param name cookie名字 
  32.     * @return 
  33.     */  
  34.     public static Cookie getCookieByName(HttpServletRequest request,String name){  
  35.         Map<String,Cookie> cookieMap = ReadCookieMap(request);  
  36.         if(cookieMap.containsKey(name)){  
  37.           Cookie cookie = (Cookie)cookieMap.get(name);  
  38.           return cookie;  
  39.         }else{  
  40.           return null;  
  41.         }   
  42.         }  
  43.       
  44.     /** 
  45.     * 将cookie封装到Map里面(非接口方法) 
  46.     * @author 刘鹏 
  47.     * @param request 
  48.     * @return 
  49.     */  
  50.     private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){   
  51.     Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();  
  52.     Cookie[] cookies = request.getCookies();  
  53.     if(null!=cookies){  
  54.       for(Cookie cookie : cookies){  
  55.        cookieMap.put(cookie.getName(), cookie);  
  56.       }  
  57.     }  
  58.     return cookieMap;  
  59.     }  
  60.       
  61.       
  62. }  

AuthorizedInterceptor(拦截器):

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.utcsoft.common.interceptor;  
  2. import java.io.IOException;  
  3. import java.io.PrintWriter;  
  4. import javax.servlet.http.Cookie;  
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7. import org.springframework.web.servlet.HandlerInterceptor;  
  8. import org.springframework.web.servlet.ModelAndView;  
  9. import com.utcsoft.common.cookie.CookieTool;  
  10. import com.utcsoft.pcapps.selfservice.dao.UtcUsersDao;  
  11. import com.utcsoft.pcapps.selfservice.entity.UtcUsers;  
  12.   
  13. public class AuthorizedInterceptor implements HandlerInterceptor {  
  14.   
  15.     /**  
  16.      * 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行。该方法将在整个请求完成之后,也就是DispatcherServlet渲染了视图执行,  
  17.      * 这个方法的主要作用是用于清理资源的,当然这个方法也只能在当前这个Interceptor的preHandle方法的返回值为true时才会执行。  
  18.      */   
  19.     public void afterCompletion(HttpServletRequest arg0,HttpServletResponse arg1, Object arg2, Exception arg3)  
  20.             throws Exception {  
  21.     }  
  22.   
  23.      /**  
  24.      * 这个方法只会在当前这个Interceptor的preHandle方法返回值为true的时候才会执行。postHandle是进行处理器拦截用的,它的执行时间是在处理器进行处理之  
  25.      * 后,也就是在Controller的方法调用之后执行,但是它会在DispatcherServlet进行视图的渲染之前执行,也就是说在这个方法中你可以对ModelAndView进行操  
  26.      * 作。这个方法的链式结构跟正常访问的方向是相反的,也就是说先声明的Interceptor拦截器该方法反而会后调用,这跟Struts2里面的拦截器的执行过程有点像,  
  27.      * 只是Struts2里面的intercept方法中要手动的调用ActionInvocation的invoke方法,Struts2中调用ActionInvocation的invoke方法就是调用下一个Interceptor  
  28.      * 或者是调用action,然后要在Interceptor之前调用的内容都写在调用invoke之前,要在Interceptor之后调用的内容都写在调用invoke方法之后。  
  29.      */    
  30.     public void postHandle(HttpServletRequest request, HttpServletResponse response,Object handler, ModelAndView modelAndView) throws Exception {  
  31.     }  
  32.   
  33.      /**  
  34.      * preHandle方法是进行处理器拦截用的,顾名思义,该方法将在Controller处理之前进行调用,SpringMVC中的Interceptor拦截器是链式的,可以同时存在  
  35.      * 多个Interceptor,然后SpringMVC会根据声明的前后顺序一个接一个的执行,而且所有的Interceptor中的preHandle方法都会在  
  36.      * Controller方法调用之前调用。SpringMVC的这种Interceptor链式结构也是可以进行中断的,这种中断方式是令preHandle的返  
  37.      * 回值为false,当preHandle的返回值为false的时候整个请求就结束了。  
  38.      */    
  39.     public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {  
  40.         String uri = request.getRequestURI();  
  41.         //登陆请求不拦截  
  42.         /*if(uri.indexOf("checkUser.do") != -1){ 
  43.             return true; 
  44.         }*/  
  45.          
  46.       //设置不拦截的对象  
  47.         String[] noFilters = new String[] {"logOn","index","supplier","innerChart"};  //对登录本身的页面以及业务不拦截  
  48.         boolean beFilter = true;   
  49.         for (String s : noFilters) {    
  50.             if (uri.indexOf(s) != -1) {    
  51.                 beFilter = false;    
  52.                 break;    
  53.             }    
  54.         }  
  55.           
  56.    if (beFilter==true) {//除了不拦截的对象以外  
  57.         String path = request.getContextPath();  
  58.         String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";  
  59.     /* 
  60.     注意:每次重新启动浏览器会重新启动一个sessionId和Cookie,之前设置的session会因为sessionId的变化而取不到,所以会出现用户明明已经登录,但是重开浏览器又需要登录. 
  61.         流程: 
  62.         1、用户选择记住密码:取出cookie中的用户名和密码查询,如果此用户已不存在,则清除cookie中的值,如果存在则判断用户是否重新登录,如果未重新登录则将cookie中用户信息设置到session中,如果用户重新登录了则判断登录用户是否与cookie中用户一致,一致则将cookie中用户信息设置到session中,不一致则将当前登录用户的信息设置到session中。 
  63.                 将用户信息放入session中是为了(通过cookie中的用户名密码可以得到用户信息): 
  64.                     1、重开浏览器的时候如果已经登录的用户可以直接进入 
  65.                     2、防止用户直接将执行方法的连接拷贝进地址栏,而方法中又需要在session中取用户信息的错误 
  66.         2、用户未选记住密码:判断session中是否存在用户信息,如果存在,则true,如果不存在则返回登录页面 
  67.     */  
  68.             Cookie cokLoginName = CookieTool.getCookieByName(request, "loginName");  
  69.             Cookie cokLoginPwd = CookieTool.getCookieByName(request, "loginPwd");  
  70.             //如果前面的人登录勾选了记住密码,cookie中存在上一个人的信息  
  71.             if (cokLoginName != null && cokLoginPwd != null && cokLoginName.getValue() != "" && cokLoginPwd.getValue() != "") {  
  72.                 String loginName = cokLoginName.getValue();  
  73.                 String loginPwd = cokLoginPwd.getValue();  
  74.                   
  75.                 // 检查到客户端保存了用户的密码,进行该账户的验证  
  76.                 UtcUsersDao usersDao = new UtcUsersDao();  
  77.                 UtcUsers users = usersDao.findByNameAndPwd(loginName, loginPwd);  
  78.                   
  79.                 //如果此人已经被管理员删除  
  80.                 if (users == null) {  
  81.                     CookieTool.addCookie(response, "loginName"null0); // 清除Cookie  
  82.                     CookieTool.addCookie(response, "loginPwd"null0); // 清除Cookie  
  83.                     try {  
  84.                         response.sendRedirect(basePath + "self/logOn.do");  
  85.                         return false;  
  86.                     } catch (IOException e) {  
  87.                         e.printStackTrace();  
  88.                     }  
  89.                     request.getSession().setAttribute("errorInfo""请登录!");  
  90.                 }  
  91.                 //如果存在此人  
  92.                 else {  
  93.                     UtcUsers utcUsers = (UtcUsers)request.getSession().getAttribute("utcUsers");  
  94.                     if (utcUsers==null) {//如果未登录而直接拷贝地址栏进入页面  
  95.                         request.getSession().setAttribute("utcUsers", users);  
  96.                     }else {//用户登录后  
  97.                         if (utcUsers.getUsername().equals(users.getUsername())) {//如果当前登录人与cookie中信息一致  
  98.                             request.getSession().setAttribute("utcUsers", users);  
  99.                         }else {//如果当前登录人与cookie中信息不一致  
  100.                             request.getSession().setAttribute("utcUsers", utcUsers);  
  101.                         }  
  102.                     }  
  103.                 }  
  104.             }  
  105.             //如果cookie中没有内容,即未勾选记住密码,或者是退出后清除了cookie  
  106.             else{  
  107.                 UtcUsers u = (UtcUsers)request.getSession().getAttribute("utcUsers");  
  108.                 if (u==null) {//如果未登录  
  109.                     response.sendRedirect(basePath + "self/logOn.do");  
  110.                      return false;  
  111.                 }else {//如果已经登录  
  112.                     //执行下一步  
  113.                 }  
  114.             }  
  115.               
  116.             /******退出的时候记得清除cookie中的内容,如果用户已经登录********/  
  117.           
  118.    }  
  119.         return true;  
  120.     }  
  121.   
  122. }  





登录验证的方法:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * 描述:登录验证 
  3.      * @param request 
  4.      * @param response 
  5.      * @return 
  6.      * @throws IOException 
  7.      */  
  8.     @RequestMapping(value="/index")  
  9.     public String index(HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws IOException{  
  10.         String user_name = httpRequest.getParameter("user_name");  
  11.         String user_pwd = httpRequest.getParameter("user_pwd");  
  12.         String str = null;  
  13.         UtcUsersDao usersDao = new UtcUsersDao();  
  14.         UtcUsers users = usersDao.findByNameAndPwd(user_name,user_pwd);  
  15.         if(users==null){//登录验证失败  
  16.             logger.info("登录失败");  
  17.             httpRequest.getSession().setAttribute("errorInfo","用户名或密码错误,请重新登录!");  
  18.             String path = httpRequest.getContextPath();  
  19.             String basePath = httpRequest.getScheme() + "://"+ httpRequest.getServerName() + ":" + httpRequest.getServerPort()+ path + "/";  
  20.             httpResponse.sendRedirect(basePath+"self/logOn.do");  
  21.         }else if ("10".equals(users.getUserrole())) {  
  22.             int  loginMaxAge = 30*24*60*60;   //定义账户密码的生命周期,这里是一个月。单位为秒  
  23.             String rememberPwd = httpRequest.getParameter("rememberPwd")==null?"":httpRequest.getParameter("rememberPwd").toString();  
  24.             if ("rememberPwd".equals(rememberPwd)) {  
  25.                 CookieTool.addCookie(httpResponse , "loginName" , user_name , loginMaxAge); //将姓名加入到cookie中  
  26.                 CookieTool.addCookie(httpResponse , "loginPwd" , user_pwd , loginMaxAge);   //将密码加入到cookie中  
  27.             }  
  28.             httpRequest.getSession().setAttribute("utcUsers", users);  
  29.             str = "/Administrator";  
  30.         }else {  
  31.             int  loginMaxAge = 30*24*60*60;   //定义账户密码的生命周期,这里是一个月。单位为秒  
  32.             String rememberPwd = httpRequest.getParameter("rememberPwd")==null?"":httpRequest.getParameter("rememberPwd").toString();  
  33.             if ("rememberPwd".equals(rememberPwd)) {  
  34.                 CookieTool.addCookie(httpResponse , "loginName" , user_name , loginMaxAge); //将姓名加入到cookie中  
  35.                 CookieTool.addCookie(httpResponse , "loginPwd" , user_pwd , loginMaxAge);   //将密码加入到cookie中  
  36.             }  
  37.             //将UtcUsers放到session中  
  38.             httpRequest.getSession().setAttribute("utcUsers", users);  
  39.             str = "self/index";  
  40.         }  
  41.         return str;  
  42.     }  

点击退出系统按钮的时候一定要记得清除cookie值()

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /**返回登录页面的中转方法,用于清除cookie中内容,不要在登录方法中清除,因为首次登录时候进入登录方法cookie是不需要清除的 
  2.      * @author liupeng 
  3.      * @param request 
  4.      * @param response 
  5.      * @return 
  6.      * @throws UnknownHostException 
  7.      */  
  8.     @RequestMapping(value="/logOnTransit")  
  9.     public void logOnTransit(HttpServletRequest request,HttpServletResponse response) throws Exception{  
  10.         CookieTool.addCookie(response, "loginName"null0); // 清除Cookie  
  11.         CookieTool.addCookie(response, "loginPwd"null0); // 清除Cookie  
  12.           
  13.         String path = request.getContextPath();  
  14.         String basePath = request.getScheme() + "://"  
  15.                 + request.getServerName() + ":" + request.getServerPort()  
  16.                 + path + "/";  
  17.         String finalPath = basePath+"self/logOn.do";  
  18.         response.sendRedirect(finalPath);  
  19.           
  20.     }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章