java spring實現記住賬號和密碼
jsp頁面:
js:
$(document).ready(function(){
//記住密碼功能
var str = getCookie("loginInfo");
str = str.substring(1,str.length-1);
var username = str.split(",")[0];
var password = str.split(",")[1];
//自動填充使用者名稱和密碼
$("#username").val(username);
$("#password").val(password);
});
//獲取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) return c.substring(name.length, c.length);
}
return "";
}
//記住密碼功能
function remember(){
var remFlag = $("input[type='checkbox']").is(':checked');
if(remFlag==true){ //如果選中設定remFlag為1
//cookie存使用者名稱和密碼,回顯的是真實的使用者名稱和密碼,存在安全問題.
var conFlag = confirm("記錄賬戶和密碼功能不宜在公共場所(如網咖等)使用,以防密碼洩露.您確定要使用此功能嗎?");
if(conFlag){ //確認標誌
$("#remFlag").val("1");
}else{
$("input[type='checkbox']").removeAttr('checked');
$("#remFlag").val("");
}
}else{ //如果沒選中設定remFlag為""
$("#remFlag").val("");
}
}
<div class="block">
<p class="block-heading">使用者登入</p>
<div class="block-body">
<form id="login_form"
action="${pageContext.request.contextPath}/platform/login.htm"
method="post">
<input type="hidden" name="remFlag" id="remFlag"/>
<label>使用者名稱</label>
<input autocomplete="off" id="username" name="username" value="${userName}" type="text" placeholder="請輸入使用者名稱" class="span12">
<label>密碼</label>
<input name="password" id="password" type="password" class="span12" autocomplete="off" value="${userPass}" placeholder="請輸入用密碼" >
<label>驗證碼</label>
<input autocomplete="off" style="width: 150px;" id="code" name="code" type="text" placeholder="請輸入驗證碼" class="span12" onblur="document.getElementById('enter').focus();">
<img alt="驗證碼" id="scode" style="width: 75px; height:30px; margin-bottom: 9px; " src="${pageContext.request.contextPath}/platform/getCode.htmc" >
<a href="#" onclick="javascript:flushCode();"><font style="font-style:italic;" size="1">看不清?換一張</font></a><br>
<input name="aaaa" type="checkbox" onclick="remember();">記住賬號和密碼
<a id="enter" href="#*" class="btn btn-primary pull-right" onclick="toLogin()">立即登入</a>
</form>
</div>
</div>
後臺controller:
String userName = RequestTools.getParameter(request,"username","");
String userPass = RequestTools.getParameter(request,"password","");
//記住使用者名稱、密碼功能(注意:cookie存放密碼會存在安全隱患)
String remFlag = request.getParameter("remFlag");
if("1".equals(remFlag)){
//"1"表示使用者勾選記住密碼
String loginInfo = userName+","+userPass;
Cookie userCookie=new Cookie("loginInfo",loginInfo);
userCookie.setMaxAge(30*24*60*60); //存活期為一個月 30*24*60*60
userCookie.setPath("/");
response.addCookie(userCookie);
}
request.setAttribute("userName", userName);
request.setAttribute("userPass", userPass);
就ok了