前言
: 为什么需要 Cookie 和 Session,你必须了解 会话 和 http 协议;
概述
: Session 是将会话中产生的数据保存在了服务器端,是服务器端技术(Session是一个域对象)。
范围
: 当前会话范围
主要功能
: 保存当前会话相关的数据
生命周期
创建:当第一次调用 request.getSession()方法时创建Session;
超时:如果一个Session超时30分钟未被使用,则认为Session超时,销毁session
自杀:当调用session.invalidate()方法时session立即销毁;
意外身亡:当服务器非正常关闭时,随着应用的销毁,session销毁,当服务器正常关闭,则未超时的session会以文件的形式保存在tomcat服务器work目录下,这个过程叫做session的钝化,当服务器再次启动时,钝化着的session还可以恢复过来,这个过程叫做session的活化。
Session的原理
: session 是基于一个 JSESSIOINID的 Cookie 工作的
商品类
//我们在这里进行的是页面内容的编辑
//a href 是一个 点击 的内容
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>自定义标题</title>
</head>
<body>
<a href="购买类代码路径?prod=名字">名字</a><br/>
<a href="购买类代码路径?prod=名字">名字</a><br/>
<a href="购买类代码路径?prod=名字">名字</a><br/>
<a href="购买列代码路径?prod=名字">名字</a><br/>
<a href="购买类代码路径?prod=名字">名字</a><br/>
<a href="支付类路径?">支付</a>
</body>
</html>
购买类
//解决乱码
response.setContentTyoe("text/html;charset=utf-8");
//获取参数
//获取参数的方法:
//request.getParameter("参数的名字");
String prodName = request.getParameter("prod");
//将商品添加到 session 当中
//获取 Session
//想想 Session 的生命周期
//创建: 当第一次调用 request.getSession方法时创建 session;
HttpSession session = request.getSession();
//创建成功后,开始添加
session.setAttribute("prod",prodName);
//返回给用户
//创建一个cookie对象
Cookie cookie = new Cookie("JSESSIONID",session.getId());
cookie.setMaxAge(60*60);
response.addCookie(cookie);
response.getWriter().writer("您已经成功添加"+prodName+”商品,请去完成支付“);
response.setHeader("refresh","3;url=/商品类路径");
支付类
//处理乱码
response.setContentType("text/html;charset=utf-8");
//获取session的对象
HttpSession session = request.getSession(false);
//获取session里面的商品名称
String prodName = (String)session.getAttribute("prod");
if(session == null || session.getAttribute("prod")==null){
//返回提示信息
response.getWriter().write("购物车里没有商品,请去添加购物车");
}else{
//实行支付逻辑
response.getWriter().writer(prodName+"支付成功");
response.setHeader("refresh","3;url=商品类路径");
}