在登入介面加入記住密碼功能,我首先想到的是在java後台中呼叫cookie存放帳號密碼,大致如下:
HttpServletRequest request HttpServletResponse response Cookie username = new Cookie("username ","cookievalue"); Cookie password = new Cookie("password ","cookievalue"); response.addCookie(username ); response.addCookie(password );
但是為安全起見,我們在後台取得的密碼大多是在js中經過MD5加密後的密文,若將密文放到cookie,程式碼如下:
//设置cookie var passKey = '4c05c54d952b11e691d76c0b843ea7f9'; function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + encrypt(escape(cvalue), passKey) + "; " + expires; } //获取cookie function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) != -1){ var cnameValue = unescape(c.substring(name.length, c.length)); return decrypt(cnameValue, passKey); } } return ""; } //清除cookie function clearCookie(cname) { setCookie(cname, "", -1); }
if($('#rememberMe').is(':checked')){ setCookie('customername', $('#username').val().trim(), 7) setCookie('customerpass', $('#password').val().trim(), 7) }
$(function(){ //获取cookie var cusername = getCookie('customername'); var cpassword = getCookie('customerpass'); if(cusername != "" && cpassword != ""){ $("#username").val(cusername); $("#password").val(cpassword); } }
rrreee