当前位置: 首页 > article >正文

Java Session 会话技术

一、Session简介

Session技术是将数据存储在服务器端的技术,会每个客户端都创建一块内存空间存储客户的数据,但客户端需要都携带一个标识ID去服务器中寻找属于自己的内存空间。所以说Session的实现是基于Cookie,Session需要借助于Cookie存储客户的唯一性标识JSESSIONID

二、Session获取

1、获得Session对象

HttpSession session = request.getSession();

此方法会获得专属于当前会话的Session对象,如果服务器端没有该会话的Session对象会创建一个新的Session返回,如果已经有了属于该会话的Session直接将已有的Session返回(实质就是根据JSESSIONID 判断该客户端是否在服务器上已经存在 Session) 

三、Session存取数据&生命周期

1、怎样向session中存取数据(session也是一个域对象),有如下三个方法

session.setAttrbute(String name, Object obj);

session.getAttrbute(String name);

session.removeAttrbute(String name);

2、Session对象的生命周期

  • 创建:第一次执行 request.getSession()时创建
  • 销毁:
    服务器(非正常)关闭时
    session过期/失效(默认30分钟) 

可以在工程的web.xml中进行配置

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config> 

四、Session的持久化

由于Session的创建和获取是取决于Cookie中的JSESSIONID决定的,所以如果Cookie被清除了,服务器就无法找到对应的Session了,因此如果想要持久化Session就必须对Cookie中的JSESSIONID进行持久化

五、Java Servlet Session 实例

1、创建Session

@WebServlet(name = "SessionServlet",urlPatterns = "/session")
public class SessionServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//第一次访问时没有session,服务器会自动创建一个session对象//之后再次访问的时候已经存在了session对象,这个直接获取这个对象HttpSession session = request.getSession();String sessionId = session.getId();response.getWriter().write("JESSIONID="+sessionId);}
}

2、保存Session

@WebServlet(name = "SaveSessionServlet",urlPatterns = "/saveSession")
public class SaveSessionServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session = request.getSession();//创建一个cookie覆盖之前服务器自动生成的JSESSIONIDCookie cookie = new Cookie("JSESSIONID", session.getId());//设置持久化时间cookie.setMaxAge(60*60);response.addCookie(cookie);session.setAttribute("goods","cup");}
}

3、获取Session

@WebServlet(name = "GetSessionServlet",urlPatterns = "/getSession")
public class GetSessionServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获取sessionHttpSession session = request.getSession();String goods = (String) session.getAttribute("goods");response.getWriter().write(goods+"");}
}

六、购物车的简单应用 

1、添加购物车

@WebServlet(name = "AddCartServlet",urlPatterns = "/addCart")
public class AddCartServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1 获取到商品的信息String name = request.getParameter("name");// 2 需要保存商品信息到sessionHttpSession session = request.getSession();List list = (List) session.getAttribute("list");//第一次访问的时候list不存在,需要创建一个listif (list==null){list=new ArrayList();}list.add(name);session.setAttribute("list",list);// session的持久化操作,也就是持久化JSESSIONIDCookie cookie = new Cookie("JSESSIONID", session.getId());cookie.setMaxAge(60*60*24);cookie.setPath("/hello");response.addCookie(cookie);}
}

2、前端简单展示

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center><h1>商品列表</h1><a href="/hello/addCart?name=杯子">杯子</a><br><a href="/hello/addCart?name=书包">书包</a><br><a href="/hello/addCart?name=笔记本">笔记本</a><br></center>
</body>
</html>

3、获取购物车数据

@WebServlet(name = "GetCartServlet",urlPatterns = "/getCart")
public class GetCartServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session = request.getSession();List<String> list= (List<String>) session.getAttribute("list");response.setContentType("text/html;charset=utf-8");for (String s : list) {response.getWriter().write(s+"<br/>");}}
}
http://www.lryc.cn/news/2418027.html

相关文章:

  • Linux搭建Hyperledger Fabric区块链框架 - Hyperledger Fabric模型概念
  • 上网行为管理系统推荐(这六款上网行为管理软件值得收藏)
  • Superset【部署 01】在线安装数据可视化图表工具 Superset(Python虚拟环境部署+问题解决+WEB登录配置+官方图表展示)
  • 《挪威的森林》
  • VoIP协议分析
  • 解释一下HTTP/2中的服务器推送(Server Push)机制及其优势。
  • C语言详解 FILE文件操作
  • 【ChatGPT实践】联网插件以及常见问题处理方案
  • 世界编辑器WorldEditor 1.2版本发布,八大功能强化易用性和自动化效率【文末有彩蛋】
  • Linux下的SVN服务器搭建
  • FLV封装格式解析
  • WMI Provider Host(wmiprvse.exe)占用CPU高的解决方案
  • 【Go语言入门教程】Go语言简介
  • 有趣的网站分享——pornhub风格生成器
  • Android系统广播大全
  • 如何使用阿里云GPU云服务器进行深度学习训练?
  • 03 外贸各国有效黄页搜索渠道【重要渠道资源】
  • BIOS 设置详解
  • 夜色空间轻装影院震撼发布,开启影音定制新纪元
  • 1024分辨率《变形金刚3》BD中英双字 高清 1080P 9G   720P 6G 下载
  • yoyo跑_yoyo主持人5岁女儿照片曝光 其老公魏哲浩个人资料简介
  • iphone、ipad备份还原ios降级SHSH篇,转载
  • lm80认证_什么是LM-80测试什么产品需要做LM-80测试
  • 【Jenkins】2022版Jenkins教程(从配置到实战)-尚硅谷
  • RemoteViews用法一:widget简单用法
  • 环境搭建 ubuntu下TFTP、 NFS启动环境搭建
  • Minus 在oracle 中的用法
  • 【学习笔记】——正则表达式从匹配qq邮箱开始
  • STM32F4+OLED 显示汉字、图片和动态图
  • 什么是勒索病毒以及怎么防勒索病毒