利用html5的本地存储功能实现登录用户信息保存

在HTML5中,本地存储是一个window的属性,包括localStorage和sessionStorage,从名字应该可以很清楚的辨认二者的区别,前者是一直存在本地的,后者只是伴随着session,窗口一旦关闭就没了。二者用法完全相同,这里以localStorage为例。

用户名、密码保存,自动登录等,可以通过设置cookie实现,第一次登录网站后在本地计算机的中写入cookie,之后再次登录此网站查看cookie中现有的值,用cookie值进行网站登录即可。但是 cookie 不适合大量数据的存储,因为它们由每个对服务器的请求来传递,这使得 cookie 速度很慢而且效率也不高。

HTML5提供了一个此类问题比较方便的解决方案,就是localstorage。数据不是由每个服务器请求传递的,而是只有在请求时使用数据。它使在不影响网站性能的情况下存储大量数据成为可能。对于不同的网站,数据存储于不同的区域,并且一个网站只能访问其自身的数据。HTML5 使用 JavaScript 来存储和访问数据。

下面是一个登录保存用户名密码的实例:


<!DOCTYPE html>
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie6 lt8"> <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="no-js ie7 lt8"> <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="no-js ie8 lt8"> <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="no-js ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!-->
<html lang="en" class="no-js">
<!--<![endif]-->
<head>
<meta charset="UTF-8" />
<!-- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">  -->
<title>图书销售管理系统</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description"
	content="Login and Registration Form with HTML5 and CSS3" />
<meta name="keywords"
	content="html5, css3, form, switch, animation, :target, pseudo-class" />
<meta name="author" content="Codrops" />
<link rel="shortcut icon" href="../favicon.ico">

<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<script>
	//先查看是否有本地数据(记住密码)
	/* function myfunction(){
		var email = localStorage.getItem("email");
		var password = localStorage.getItem("password");
		if(email!=null&&password!=null){
			alert("邮箱:"+email+"密码:"+password);
			$.ajax({
				url : '../servlet/LoginServlet?choose=login',
				data : {
					email : email,
					password : password
				},
				dataType : 'json',
				success : function(data) {
					if (data.msg == "") {
						alert("用户名或密码错误");
					} else {
					//登录成功后保存session,如果选择了记住密码,再保存到本地
						//window.location.href ='../index/index.jsp';
					}
				},
				error : function() {
					alert("系统错误");
				}
			});
		}else{
			//alert("没有信息");
			
		}
	}
	function saveStorage(){
		var email = document.getElementById("email").value;
		localStorage.setItem("email",email);
		var password = document.getElementById("password").value;
		localStorage.setItem("password",password);
	
	}
	function login(){
		$.ajax({
			url : '../servlet/LoginServlet?choose=login',
			data : {
				email : $('#loginform input[name=email]').val(),
				password : $('#loginform input[name=password]').val()
			},
			dataType : 'json',
			success : function(data) {
				if (data.msg == "") {
					alert("用户名或密码错误");
				} else {
				//登录成功后保存session,如果选择了记住密码,再保存到本地
					window.location.href ='../index/index.jsp';
				}
			},
			error : function() {
				alert("系统错误");
			}
	   });
    }
	function reg(){
		$.ajax({
			url : 'servlet/LoginServlet?choose=reg',
			data : {
				username : $('#regform input[name=username]').val(),
				password : $('#regform input[name=password]').val(),
				email : $('#regform input[name=email]').val(),
			},	
			dataType : 'json',
			success : function(data) {
				if(data.msg == false){
					alert("注册失败");
				}else{
					alert("注册成功请返回登录");
				}
			},
			error : function() {
				alert("系统错误");
			}
		});
	} */
$(document).ready(function(){  
  //读取 localStage 本地存储,填充用户名密码,如果自动登录有值直接跳转;  
  //相反,跳转到本页面,等待登陆处理  
  var storage = window.localStorage;  
    var getEmail = storage["email"];  
    var getPwd = storage["password"];  
    var getisstroepwd = storage["isstorePwd"];  
    var getisautologin = storage["isautologin"];  
    if("yes" == getisstroepwd)  
    {  
        if("yes" == getisautologin)  
        {  
            if(( ("" != getEmail) ||(null != getEmail)) && (("" != getPwd) ||(null != getPwd)))  
            {  
                //lacoste  已经保存 登陆信息 直接登陆  
                // alert('正在自动登录');
                $("email").val(getEmail);
                $("#password").val(getPwd);  
               // window.location="";   
               //加载时显示:正在自动登录
                $.ajax({
					url : '../servlet/LoginServlet?choose=login',
					data : {
						email :  getEmail,
						password : getPwd 
					},
					dataType : 'json',
					success : function(data) {
						if (data.msg == "") {
							alert("账号信息异常,请核实后重新登录");
						} else {
						//登录成功后保存session,如果选择了记住密码,再保存到本地
							//window.location.href ='../index/index.jsp';
						}
					},
					error : function() {
						alert("系统错误");
					}
	   			});
            }  
        }  
        else  
        {     
                $("#email").val(getEmail);  
                $("#password").val(getPwd);  
                document.getElementById("isRemberPwdId").checked = true;  
        }  
    }  
 });  
function login(){
	 var userEmail=$("#email").val();  
    var userPassWord=$("#password").val();  
  
    var storage = window.localStorage;  
    //记住密码  
    if(document.getElementById("isRemberPwdId").checked)  
    {  
        //存储到loaclStage    
  
        storage["email"] = userEmail;  
        storage["password"] =  userPassWord;  
        storage["isstorePwd"] =  "yes";  
    }  
    else  
    {  
        storage["email"] = userEmail;  
        storage["isstorePwd"] =  "no";  
    }  
  
    //下次自动登录  
    if(document.getElementById("isAutoLoginId").checked)  
    {  
        //存储到loaclStage    
        storage["email"] = userEmail;  
        storage["password"] =  userPassWord;  
        storage["isstorePwd"] =  "yes";  
        storage["isautologin"] =  "yes";  
    }  
    else  
    {  
        storage["email"] = userEmail;  
        storage["isautologin"] =  "no";  
    } 
     $.ajax({
			url : '../servlet/LoginServlet?choose=login',
			data : {
				email : userEmail,
				password : userPassWord
			},
			dataType : 'json',
			success : function(data) {
				if (data.msg == "") {
					alert("用户名或密码错误");
				} else {
				//登录成功后保存session,如果选择了记住密码,再保存到本地
					window.location.href ='../index/index.jsp';
				}
			},
			error : function() {
				alert("系统错误");
			}
	   }); 
	   alert("登录成功");
}
</script>
<body>
	<div class="container">
		<header>

		</header>
		<section>
			
			<div id="container_demo">
				<a class="hiddenanchor" id="toregister"></a> <a class="hiddenanchor"
					id="tologin"></a>
				<div id="wrapper">
					<div id="login" class="animate form">
						<form id="loginform" name="loginform" autocomplete="on" method="post">
							<h1>登录</h1>
							<p>
								<label for="username" class="uname" data-icon="u"> 邮箱  </label>
								<input id="email" name="email" required="required"
									type="text" placeholder="请输入邮箱" autofocus />
							</p>
							<p>
								<label for="password" class="youpasswd" data-icon="p">
									密码</label> <input id="password" name="password" required="required"
									type="password" placeholder="请输入密码?" />
							</p>
							<p class="keeplogin">
								<input type="checkbox" name="isRemberPwdId" id="isRemberPwdId"
									 /> <label for="loginkeeping">记住密码 ?</label>
							</p>
							<p class="keeplogin">
								<input type="checkbox" name="isAutoLoginId" id="isAutoLoginId"
									 /> <label for="autologin">自动登录 ?</label>
							</p>
							<p class="login button">
								<input type="button" value="登录" onclick="login()" />
							</p>
							<p class="change_link">
								没有账号? <a href="#toregister" class="to_register">前去注册</a>
							</p>
						</form>
					</div>
				</div>
			</div>
		</section>
	</div>
</body>
</html>


利用html5的本地存储功能实现登录用户信息保存,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。