JavaScript+Cookie记住账号密码,登录页面的实现
作者:互联网
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<title>Signin Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/login.css" rel="stylesheet">
<script>
//点击更换验证码图片
function changeImg(img) {
//html中元素的属性发生改变的时候,浏览器自动刷新
var time = new Date().getTime()
img.src = "CodeServlet?time=" + time
}
</script>
</head>
<body>
<div class="container">
<form class="form-signin" action="LoginServlet" method="POST" id="loginForm">
<div class="text-center">
<h2 class="form-signin-heading">登录页面</h2>
<span style="color: red">
${loginError}
</span>
</div>
<label for="user" class="sr-only">用户名</label>
<input type="text" id="user" name="username"
value = ""
class="form-control" placeholder="用户名" required autofocus>
<label for="pswd" class="sr-only">密码</label>
<input type="password" id="pswd" name="password"
value = ""
class="form-control" placeholder="密码" required>
<input type="text" id="checkcode" name="checkcode" class="form-control" placeholder="验证码">
<img src="CodeServlet" οnclick="changeImg(this)">
<div class="checkbox">
<label>
<input type="checkbox" id="remember" name="remember" value="yes" > 记住账号密码
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
</form>
</div>
</body>
<script>
window.onload = function(){
var oForm = document.getElementById('loginForm');
var oUser = document.getElementById('user');
var oPswd = document.getElementById('pswd');
var oRemember = document.getElementById('remember');
//页面初始化时,如果帐号密码cookie存在则填充
if(getCookie('user') && getCookie('pswd')){
oUser.value = getCookie('user');
oPswd.value = getCookie('pswd');
oRemember.checked = true;
}
//复选框勾选状态发生改变时,如果未勾选则清除cookie
oRemember.onchange = function(){
if(!this.checked){
delCookie('user');
delCookie('pswd');
}
};
//表单提交事件触发时,如果复选框是勾选状态则保存cookie
oForm.onsubmit = function(){
if(remember.checked){
setCookie('user',user.value,7); //保存帐号到cookie,有效期7天
setCookie('pswd',pswd.value,7); //保存密码到cookie,有效期7天
}
};
};
//设置cookie
function setCookie(name,value,day){
var date = new Date();
date.setDate(date.getDate() + day);
document.cookie = name + '=' + value + ';expires='+ date;
};
//获取cookie
function getCookie(name){
var reg = RegExp(name+'=([^;]+)');
var arr = document.cookie.match(reg);
if(arr){
return arr[1];
}else{
return '';
}
};
//删除cookie
function delCookie(name){
setCookie(name,null,-1);
};
</script>
</html>
标签:function,name,JavaScript,cookie,var,Cookie,pswd,document,账号密码 来源: https://blog.csdn.net/qq_43493747/article/details/120184870