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.     }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章