原本以为还算简单的一个功能,但还是让初学者的我花费了不少时间.
先看代码:
1.初始登录页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
/* 关于记住密码的验证 */
String name = "";
String password = "";
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
/* 只有在index页面选中了记住密码,就可以在remembercookie页面创建cookie并存储数据,在这里就可以获取数据 */
if ("uname".equals(cookie.getName())) {;
name = cookie.getValue();
} else if ("password".equals(cookie.getName())) {
password = cookie.getValue();
}
}
%>
<form action="rememberCookie.jsp" method="post">
用户名: <input type="text" name="uname" value="<%=name%>" /> <br /> 密码:
<input type="password" name="password" value="<%=password%>" /> <br />
<input type="checkbox" name="remember" id="rem" />记住密码 <br /> <input
type="submit" value="登录" /> <input type="hidden" name="flag"
id="hid" value=""/>
</form>
</body>
<script type="text/javascript" src="../js/jquery-1.11.0.js"></script>
<script type="text/javascript">
var isChecked = $("#rem");
isChecked.click(function(){
if (isChecked.prop('checked')) {//用来判断是否选中记住密码,用来给remembercookie传递参数
$("#hid").val(1);
} else {
$("#hid").val(0);
}
});
</script>
</html>
2.cookie验证添加页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String name = request.getParameter("uname");
String password = request.getParameter("password");
String hidstr = request.getParameter("flag");
System.out.println(hidstr);
if("1".equals(hidstr))
{
Cookie cookname = new Cookie("uname",name);
Cookie cookpass = new Cookie("password",password);
response.addCookie(cookname);
response.addCookie(cookpass);
}
response.sendRedirect("show.jsp");
%>
</body>
</html>
3.登录成功页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
登陆成功.
</body>
</html>
其中遇到了不少问题:
1)使用jQuery获取复选框获取选中状态
我原来写的是:if($("#rem").checked),没有效果,后来又改成if($("#rem").attr('checked')),也不行
最后改成if($("#rem").prop('checked'))才可以了
2)使用jQuery修改隐藏域的value
我原来写的是:var flag = $("#hid").val();
但是必须这样写才能修改生效:$("#hid").val(id);
其中id填写要修改的值
最后再总结一下实现记住密码的思路:
在页面开头写上一段jsp代码,用来进行cookie验证,如果之前登陆过且记住过密码,则这时获取到的cookie是有name值和value值的,如果有,则自动填写到form表单的用户名和密码处.如果没有,则需要用户自己填写.
当用户填写完成以后,可以选择是否记住密码,点击登录以后,页面跳转到cookie验证添加页面,该页面用来判断前面是否选择了记住密码,如果选择记住,则创建cookie,并把通过request获取到的用户名和密码存储到cookie中(创建cookie对象,值为用户名和密码),不管选没选择记住密码,只要用户名和密码填写正确,就跳转到登陆成功页面.
反思:通过出现的问题可以看出来,自己对jQuery的部分知识还是不够了解,应该多加学习巩固jQuery有关知识.