服务端 Session

前言

: 为什么需要 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=商品类路径");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值