Java:Cookie實現記住使用者名稱、密碼

來源:互聯網
上載者:User

標籤:stringbu   factory   tty   需要   cookies   div   idt   詳細資料   split   

package com.gamecenter.api.util;import java.io.IOException;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import com.gamecenter.api.common.UserInfo;/** * 類說明 * @author chitu* @version 建立時間:2016年11月21日 下午1:39:51 */public class CookieUtil {    //儲存cookie時的cookieName    private final static String cookieDomainName = "gamecenter";    //加密cookie時的網站自定碼    private final static String webKey = "gamecenter";    //設定cookie有效期間是兩個星期,根據需要自訂    private final static long cookieMaxAge = 60 * 60 * 24 * 7 * 2;    //儲存Cookie到用戶端-------------------------------------------------------------------------    //在CheckLogonServlet.java中被調用    //傳遞進來的user對象中封裝了在登陸時填寫的使用者名稱與密碼    public static void saveCookie(String username,String password, HttpServletResponse response) throws Exception {           //cookie的有效期間           long validTime = System.currentTimeMillis() + (cookieMaxAge * 5000);           //MD5加密使用者詳細資料           String cookieValueWithMd5 =getMD5(username + ":" + password+ ":" + validTime + ":" + webKey);           //將要被儲存的完整的Cookie值           String cookieValue = username + ":" + validTime + ":" + cookieValueWithMd5;           //再一次對Cookie的值進行BASE64編碼           String cookieValueBase64 = new String(Base64Util.encode(cookieValue.getBytes()));           //開始儲存Cookie           Cookie cookie = new Cookie(cookieDomainName, cookieValueBase64);           //存兩年(這個值應該大於或等於validTime)           cookie.setMaxAge(60 * 60 * 24 * 365 * 2);           //cookie有效路徑是網站根目錄           cookie.setPath("/");           //向用戶端寫入           response.addCookie(cookie);    }    //讀取Cookie,自動完成登陸操作----------------------------------------------------------------    //在Filter程式中調用該方法,見AutoLogonFilter.java    public static void readCookieAndLogon(HttpServletRequest request, HttpServletResponse response,FilterChain chain) throws IOException, ServletException,UnsupportedEncodingException{    //根據cookieName取cookieValue    Cookie cookies[] = request.getCookies();        String cookieValue = null;        if(cookies!=null){             for(int i = 0; i < cookies.length; i++){                    if (cookieDomainName.equals(cookies[i].getName())) {                           cookieValue = cookies[i].getValue();                           break;                    }             }       }       //如果cookieValue為空白,返回,       if(cookieValue==null){             return;       }       //如果cookieValue不為空白,才執行下面的代碼       //先得到的CookieValue進行Base64解碼       String cookieValueAfterDecode = new String (Base64Util.decode(cookieValue),"utf-8");       //對解碼後的值進行分拆,得到一個數組,如果數組長度不為3,就是非法登陸       String cookieValues[] = cookieValueAfterDecode.split(":");       if(cookieValues.length!=3){              response.setContentType("text/html;charset=utf-8");              PrintWriter out = response.getWriter();              out.println("你正在用非正常方式進入本站...");              out.close();              return;       }       //判斷是否在有效期間內,到期就刪除Cookie       long validTimeInCookie = new Long(cookieValues[1]);       if(validTimeInCookie < System.currentTimeMillis()){              //刪除Cookie              clearCookie(response);              response.setContentType("text/html;charset=utf-8");              PrintWriter out = response.getWriter();              out.println("你的Cookie已經失效,請重新登陸");              out.close();              return;       }       //取出cookie中的使用者名稱,併到資料庫中檢查這個使用者名稱,       String username = cookieValues[0];       //根據使用者名稱到資料庫中檢查使用者是否存在       UserDAO ud = DaoImplFactory.getInstance();       User user = ud.selectUserByUsername(username);       //如果user返回不為空白,就取出密碼,使用使用者名稱+密碼+有效時間+ webSiteKey進行MD5加密       if(user!=null){              String md5ValueInCookie = cookieValues[2];              String md5ValueFromUser =getMD5(user.getUserName() + ":" + user.getPassword()                            + ":" + validTimeInCookie + ":" + webKey);              //將結果與Cookie中的MD5碼相比較,如果相同,寫入Session,自動登陸成功,並繼續使用者請求              if(md5ValueFromUser.equals(md5ValueInCookie)){                     HttpSession session = request.getSession(true);                     session.setAttribute("user", user);                     chain.doFilter(request, response);              }       }else{       //返回為空白執行              response.setContentType("text/html;charset=utf-8");              PrintWriter out = response.getWriter();              out.println("cookie驗證錯誤!");              out.close();        return;      }    }    //使用者登出時,清除Cookie,在需要時可隨時調用-----------------------------------------------------public static void clearCookie( HttpServletResponse response){       Cookie cookie = new Cookie(cookieDomainName, null);       cookie.setMaxAge(0);       cookie.setPath("/");       response.addCookie(cookie);}       //擷取Cookie組合字元串的MD5碼的字串----------------------------------------------------------------       public static String getMD5(String value) {              String result = null;              try{                     byte[] valueByte = value.getBytes();                     MessageDigest md = MessageDigest.getInstance("MD5");                     md.update(valueByte);                     result = toHex(md.digest());              } catch (NoSuchAlgorithmException e){                     e.printStackTrace();              }              return result;       }       //將傳遞進來的位元組數群組轉換成十六進位的字串形式並返回       private static String toHex(byte[] buffer){              StringBuffer sb = new StringBuffer(buffer.length * 2);              for (int i = 0; i < buffer.length; i++){                     sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));                     sb.append(Character.forDigit(buffer[i] & 0x0f, 16));              }              return sb.toString();       }}

  

Java:Cookie實現記住使用者名稱、密碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.