时间:2021-07-01 10:21:17 帮助过:15人阅读
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中,在js中获取到也没有作用;
然后考虑在js中存取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); }
setCookie(cname, cvalue, exdays)三个参数分别是存放的cookie名字、cookie值、cookie有效天数
由于cookie中不能包含等号、空格、分号等特殊字符,我在设置cookie时使用escape() 函数对字符串进行编码,获取cookie时使用unescape()函数解码。但是escape()函数不会对 ASCII 字母和数字进行编码,所以存放到cookie中的账号、密码是以明文存放的,不安全。于是上网找了一个对字符串加密解密算法,该算法需要传两个参数,一个需要加密的字符串,一个自定义加密密钥passKey。设置cookie时使用encrypt(value, passkey)加密,读取cookie时使用decrypt(value, passKey)解密,该算法附在本文最后。
存取cookie方法的调用:
1、定义checkbox
<input type="checkbox" id="rememberMe" checked="checked"/>记住密码
2、判断帐号密码输入无误后调用
if($('#rememberMe').is(':checked')){ setCookie('customername', $('#username').val().trim(), 7) setCookie('customerpass', $('#password').val().trim(), 7) }
3、进入登录界面后,判断cookie中是否有帐号密码,如果有就自动填充
$(function(){ //获取cookie var cusername = getCookie('customername'); var cpassword = getCookie('customerpass'); if(cusername != "" && cpassword != ""){ $("#username").val(cusername); $("#password").val(cpassword); } }