Cookie机制(会话cookie和持久化cookie)在客户端保持HTTP状态信息的方案

1. Cookie只有一个name和一个value,不同于map;购物车设计的时候需要cookie,获取购物车的cookie id,以便于将物品多次放入购物车;

2.cookie获取了其地址,并且可以设置再次打该开页面,coolie地址保持的时间,类似于,在网页上再次登录用户名,其用户名依然存在的时长;

--------------------------------------------------------------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
//在 JavaWEB 规范中使用 Cookie 类代表 cookie

//1. 获取 Cookie
Cookie [] cookies = request.getCookies();
if(cookies != null && cookies.length > 0){
for(Cookie cookie: cookies){
//2. 获取 Cookie 的 name 和 value
out.print(cookie.getName() + ": " + cookie.getValue());
out.print("<br>");
}
}else{
out.print("没有一个 Cookie, 正在创建并返回");
//1. 创建一个 Cookie 对象
Cookie cookie = new Cookie("name", "atguigu");
//setMaxAge: 设置 Cookie 的最大时效, 以秒为单位, 若为 0 , 表示立即删除该 Cookie
//若为负数, 表示不存储该 Cookie, 若为正数, 表示该 Cookie 的存储时间. 每次打开coolie保持的时间
cookie.setMaxAge(30);

//2. 调用 response 的一个方法把 Cookie 传给客户端.
response.addCookie(cookie);
}
%>

</body>
</html>

-------------------------------------------------------------------------------------------

例二:自动登录,不需要填写用户名和密码,点击登录就成功了;

login.jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<form action="index.jsp" method="post">

name: <input type="text" name="name"/>

<input type="submit" value="Submit"/>

</form>

</body>
</html>

index.jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
//若可以获取到请求参数 name, 则打印出欢迎信息。把登录信息存储到 Cookie 中,并设置 Cookie 的最大时效为 30S
String name = request.getParameter("name");
if(name != null && !name.trim().equals("")){
Cookie cookie = new Cookie("name", name);
cookie.setMaxAge(30);
response.addCookie(cookie);
}else{
//从 Cookie 中读取用户信息,若存在则打印欢迎信息
Cookie [] cookies = request.getCookies();
if(cookies != null && cookies.length > 0){
for(Cookie cookie : cookies){
String cookieName = cookie.getName();
if("name".equals(cookieName)){
String val = cookie.getValue();
name = val;
}
}
}
}

if(name != null && !name.trim().equals("")){
out.print("Hello: " + name);
}else{
//若既没有请求参数,也没有 Cookie,则重定向到 login.jsp
response.sendRedirect("login.jsp");
}

%>

</body>
</html>

原文地址:https://www.cnblogs.com/lxnlxn/p/5821700.html