JSP中创建与使用Cookie
- 实现记忆用户名和密码功能
login.jsp
<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
%><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登录界面</title>
</head>
<body>
<h1>用户登录</h1>
<hr>
<%
request.setCharacterEncoding("utf-8");
String username="";
String password="";
Cookie[] cookies = request.getCookies();
if(cookies!=null && cookies.length>0)
{
for(Cookie c:cookies)
{
if(c.getName().equals("username"))
{
username = URLDecoder.decode(c.getValue(),"utf-8");
}
if(c.getName().equals("password"))
{
password = URLDecoder.decode(c.getValue(),"utf-8");
}
}
}
%>
<form action ="dologin.jsp" name = "loginForm" method = "post">
<table>
<tr>
<td>用户名:</td>
<td><input type = "text" name = "username" value="<%=username %>"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type = "password" name = "password" value="<%=password %>"/></td>
</tr>
<tr>
<td colspan = "2"><input type="checkbox" name="isUserCookie" checked="checked"/>十天内记住我的登陆状态</td>
</tr>
<tr>
<td colspan = "2"><input type="submit" value = "登录"/></td>
</tr>
</table>
</form>
</body>
</html>
dologin.jsp
<%@ page language="java" import="java.util.*,java.net.* " contentType="text/html; charset=utf-8"
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登录成功界面</title>
</head>
<body>
<h1>登陆成功</h1>
<hr>
<%
request.setCharacterEncoding("utf-8");
//首先判断用户是否选择了记住登陆状态
String[] isUserCookie = request.getParameterValues("isUserCookie");
if(isUserCookie!=null && isUserCookie.length>0)
{
//把用户名和密码保存在cookie对象里
String username = URLEncoder.encode(request.getParameter("username"),"utf-8");
//使用URLEncoding解决无法在cookie中保存中文问题
String password = URLEncoder.encode(request.getParameter("password"),"utf-8");
Cookie usernameCookie = new Cookie("username",username);
Cookie passwordCookie = new Cookie("password",password);
usernameCookie.setMaxAge(864000);
passwordCookie.setMaxAge(864000);
response.addCookie(usernameCookie);
response.addCookie(passwordCookie);
}
else
{
Cookie[] cookies = request.getCookies();
if(cookies!=null && cookies.length>0)
{
for(Cookie c:cookies)
{ if(c.getName().equals("username")||c.getName().equals("password"))
{
c.setMaxAge(0);//设置Cookie失效
response.addCookie(c);//重新保存
}
}
}
}
%>
<a href="users.jsp" >查看用户信息</a>
</body>
</html>
users.jsp
<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>用户信息界面</title>
</head>
<body>
<h1>用户信息</h1>
<hr>
<%
request.setCharacterEncoding("utf-8");
String username="";
String password="";
Cookie[] cookies = request.getCookies();
if(cookies!=null && cookies.length>0)
{
for(Cookie c:cookies)
{
if(c.getName().equals("username"))
{
username = URLDecoder.decode(c.getValue(),"utf-8");
}
if(c.getName().equals("password"))
{
password = URLDecoder.decode(c.getValue(),"utf-8");
}
}
}
%>
用户名:<%=username %><br>
密码:<%=password %><br>
</body>
</html>