您的位置:首页 > Web前端 > JQuery

使用Jquery cookie插件实现用户名和密码的保存

2017-08-18 10:52 791 查看
Demo中用到的jquery类库和jquery cookie插件可以自己在网上下载。

Demo项目结构如下图所示:



index.html的页面代码如下:

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="jquery-3.2.1.min.js"></script>
<script src="jquery.cookie.js"></script>
<script>

$(function(){
if($.cookie("userName")){
$("#username").val($.cookie("userName"));
}
if($.cookie("passWord")){
$("#password").val($.cookie("passWord"));
}
$("#submit").click(function(){
console.log("123456");
if($("#checkbox").is(":checked")){
console.log("666");
$.cookie("userName",$("#username").val(),{
path: "/", expires: 7
});
$.cookie("passWord",$("#password").val(),{
path: "/", expires: 7
});
}else{
$.cookie("userName",null,{
path: "/"
});
$.cookie("passWord",null,{
path: "/"
});
}
});
})
</script>
</head>
<body>
<form method="post" action="#">
<div>用户名:<input type="username" name="username" id="username"></div>
<div>密 码:<input type="password" name="password" id="password"></div>
<div>
<input type="checkbox" name="checkbox" id="checkbox">保存用户名和密码
</div>
<div>
<input type="button" name="submit" value="登录" id="submit">
</div>
</form>
</body>
</html>


4.把demo布署到tomcat中启动以后,启动浏览器访问index.html,效果图如下:



我这里在web.xml中配置了欢迎页面,所以直接访问到项目名就可以:http://localhost:8080/jq-cookie/,web.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>jq-cookie</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>


5.总结:

使用jquery cookie插件来实现用户名和密码的保存相比起使用javaee cookie api要简单许多,但是这里有一点需要注意:要测试用户名和密码的保存功能的话,需要将demo布署到测试服务器或者localhost服务器上才可以看到效果,直接在本地打开一个index.html页面是无法实现这个功能的,因为cookie是在服务器创建的,而保存是在浏览器中的,以下是cookie在服务器端的创建以及保存到浏览器的代码:

Cookie c = new Cookie("cookie--key", "cookie—value");
c.setMaxAge(3600);//表示3600秒
c.setDomain("localhost");//设置cookie的域,域与当前项目的域不一样是不能写回到浏览器的,一般不用设置,默认就是当前项目的域名
c.setPath("/");//路径,/表示根目录,默认是"/项目名"
response.addCookie(c);//添加cookie到response中
response.sendRedirect(request.getContextPath()+"/index.jsp");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: