• 入门JavaWeb之 Session 篇


    Session:

    服务器会给每个用户(浏览器)创建一个 Session 对象

    一个 Session 独占一个浏览器,只要浏览器没有关闭,这个 Session 就存在

    代码如下:

    1. package com.demo.cookie;
    2. import javax.servlet.ServletException;
    3. import javax.servlet.http.HttpServlet;
    4. import javax.servlet.http.HttpServletRequest;
    5. import javax.servlet.http.HttpServletResponse;
    6. import javax.servlet.http.HttpSession;
    7. import java.io.IOException;
    8. public class Session extends HttpServlet {
    9. @Override
    10. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    11. //解决中文乱码
    12. req.setCharacterEncoding("UTF-8");
    13. resp.setCharacterEncoding("UTF-8");
    14. resp.setContentType("text/html");
    15. //得到Session
    16. HttpSession session = req.getSession();
    17. //给Session中存东西
    18. session.setAttribute("name","hhh");
    19. //获取Session的ID
    20. String id = session.getId();
    21. //判断Session是否是新创建的
    22. if (session.isNew()){
    23. resp.getWriter().write("Session创建,ID:"+id);
    24. }else {
    25. resp.getWriter().write("Session已经在服务器存在,ID:"+id);
    26. }
    27. }
    28. @Override
    29. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    30. doGet(req, resp);
    31. }
    32. }

    web.xml 注册:

    1. <servlet>
    2. <servlet-name>seservlet-name>
    3. <servlet-class>com.demo.cookie.Sessionservlet-class>
    4. servlet>
    5. <servlet-mapping>
    6. <servlet-name>seservlet-name>
    7. <url-pattern>/seurl-pattern>
    8. servlet-mapping>

    运行后查看结果

    应用程序存入 SessionID

    请求头存入 SessionID

    注销 Session:

    1. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    2. HttpSession session = req.getSession();
    3. session.removeAttribute("name");
    4. //手动注销Session
    5. session.invalidate();
    6. }

    进入注销页再进入 SessionID 页,SessionID 改变

    还可以设置 Session 默认失效时间

    1. <session-config>
    2. <session-timeout>15session-timeout>
    3. session-config>

    Session 与 Cookie 的区别:

    1. Cookie 是把用户的数据写给用户的浏览器,浏览器保存,可以保存多个

    2. Session 把用户的数据写到用户独占 Session 中,服务器端保存(保存重要的信息,减少服务器资源的浪费)

    3. Session 对象由服务器创建

    服务器中的 Session 可以存东西,客户端向服务器发起请求,将登记一个 Session

    用户拿到的是 SessionID,每个用户唯一

  • 相关阅读:
    gitlab 设置 分支只读
    实验2 Python数字类型实验
    朋友圈大佬都去读研了,这份备考书单我码住了
    JWT(简介)
    SIP中继与VoIP:有何不同?
    超图s3m服务加载时添加token
    Java项目:SSM网上家具商城网站系统平台
    MyBatis 与 MyBatis-Plus 的区别
    02 记一次 netty 内存泄露
    基于PyTorch搭建你的生成对抗性网络
  • 原文地址:https://blog.csdn.net/m0_58838332/article/details/139938579