• session


    什么是session:

    • 服务器会给每一个用户(浏览器)创建一个session对象
    • 一个session独占一个浏览器,只要浏览器没关,这个session就存在
    • 用户登录之后,整个网站它都可以访问

    session和cookie的区别:

    • cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
    • session是把用户的数据写到用户独占的session中,在服务器端(保存重要的信息,减少服务器资源的浪费)

    session使用场景:

    • 保存用户登录信息;

    • 购物车信息;

    • 在整个网站中经常会使用的数据,我们将它保存在session中;

    使用session

    public class session extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            // 解决乱码问题
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=utf-8");
            // 得到session
            HttpSession session = req.getSession();
            // 向session存东西
            session.setAttribute("m", "mmm");
            session.setAttribute("mlx", new Person("mlx", 18));
    
            // 获取session 的ID
            String ID = session.getId();
            // 判断是否是新的session
            boolean isNew = session.isNew();
            if(isNew) {
                resp.getWriter().write("session创建成功, ID:" + ID);
            } else  {
                resp.getWriter().write("session已经在服务器中存在, ID:" + ID);
            }
    
            // session创建的时候做了什么事情
    //        Cookie cookie = new Cookie("JSESSIONID", ID);
    //        resp.addCookie(cookie);
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        }
    }
    
    public class session1 extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            // 解决乱码问题
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=utf-8");
            // 得到session
            HttpSession session = req.getSession();
            String m = (String) session.getAttribute("m");
            resp.getWriter().write("
    得到session Attribute:" + m);
    
            Person mlx =  (Person)session.getAttribute("mlx");
            resp.getWriter().write("
    得到mlx: name=" + mlx.getName() + "age=" + mlx.getAge());
    
    
            // 注销session
    //        HttpSession session = req.getSession();
            // 手动注销
            session.invalidate();
            //
        }
    }
    

    在web.xml中设置自动过期时间

    <!-- 设置session默认的失效时间 -->
      <session-config>
        <!--  15分钟后session自动失效  -->
        <session-timeout>15</session-timeout>
      </session-config>
    
  • 相关阅读:
    POJ3246
    .NetCore Docker一次记录
    asp.net利用SmtpClient发送邮件
    Assert类的静态方法
    ado.net 连接数据库
    虚拟目录
    web.config配置详细说明
    图片上传
    .NET操作Excel
    asp.net 数据绑定 -- 时间格式
  • 原文地址:https://www.cnblogs.com/menglingxu/p/13936735.html
Copyright © 2020-2023  润新知