<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>cookie测试</title>
</head>
<body>
<form method="post" name="form">
<table>
<tr>
<td>
用户名:<input type="text" name="user">
</td>
</tr>
<tr>
<td>
<input type="submit" value="登录">
</td>
</tr>
</table>
</form>
<%
Cookie[] c = request.getCookies();
Cookie c1;
if (c != null)
{
for (int i = 0; i < c.length; i++)
{
c1 = c[i];
String a = c1.getName();
String b = c1.getValue();
if (a.equals("1"))
{
if (b != null && !b.trim().isEmpty())
{
response.sendRedirect("success.jsp");
}
}
}
}
%>
<%
String user = request.getParameter("user");
Cookie cuser=new Cookie("1",user);
cuser.setMaxAge(20);
response.addCookie(cuser);
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>success</title>
</head>
<body>
<h1>登录成功</h1>
<%
Cookie[]t=request.getCookies();
for(int i=0;i<t.length;i++)
{
Cookie t1=t[i];
String s=t1.getName();
if(s.equals("1"))
{
out.println("欢迎"+t1.getValue());
}
}
%>
</body>
</html>
cuser.setMaxAge(20); 更改cookie存在时间,0表示存放浏览器后立即失效,负数表示关闭浏览器后立即失效。单位为秒
运行效果
20秒内重新访问该网址可以不用登录,直接到欢迎界面