1. 程式人生 > >java實現密碼自動登入,記住密碼

java實現密碼自動登入,記住密碼

<pre name="code" class="java"><span style="font-size:18px;">1.身份加密
2.存入cookie
3.下次登入先判斷cookie,並取出cookieValue
4.cookieValue解密取出 使用者名稱,根據使用者名稱查詢
5.返回使用者資訊,講使用者資訊按照前面加密規則加密
6.加密後的資訊跟cookie中的資訊判斷
7.相等則預設自動登入
8.否則返回登入頁面</span>

使用者勾選自動登入,登入成功後,存入cookie

if(StringUtils.isNotBlank(freeLogin)&&"1"
.equals(freeLogin)){//判斷使用者是否選中免登入 String info=getEncryptionInfo(user.getShouji(), MD5Util.string2MD5(user.getPassword())); CookieUtils.addCookie(getResponse(), LOGIN_COOKIE_NAME, info, "/", 60*60*24*7); }
操作使用者資訊加密的方法
/**
 * 使用者資訊加密
* @param userName
* @param UserPassword
* @return 加密後的資訊
*/
public static final 
String getEncryptionInfo(String userName,String UserPassword){ String info=userName+UserPassword+FREE_LOGIN_TAG; String md5Str=MD5Util.string2MD5(info); String dBase64=getBase64(md5Str)+","+userName; return getBase64(dBase64); } /** * base64中解密獲取使用者名稱 * @return */ public static final String getBase64UserName
(String encryptionInfo){ //解密身份資訊; String userName=null; String str= getStrFromBase64(encryptionInfo); if(str==null||"".equals(str.trim())){ return null; } if(str.indexOf(",")>0){ String []arr=str.split(","); userName=arr[1]; } return userName; } // base64加密 public static final String getBase64(String str) { if(StringUtils.isBlank(str)){ return null; } byte[] b = null; try { b = str.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return new BASE64Encoder().encode(b); } // base64解密 public static final String getStrFromBase64(String str) { byte[] b = null; String result = null; if (str != null&&!"".equals(str.trim())) { BASE64Decoder decoder = new BASE64Decoder(); try { b = decoder.decodeBuffer(str); result = new String(b, "utf-8"); } catch (Exception e) { e.printStackTrace(); } } return result; }