【Session详解】

什么是Session?

  1. 当用户通过浏览器访问一个网页时,网页在服务器里面配置,服务器会给每一个用户(浏览器)创建一个Session对象。
  2. 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就存在。
  3. 用户登陆之后,整个网站用户都可以访问,因为网站的不同网页都共享一个Session,识别了用户。–>保存用户信息;保存购物车的信息…
  4. Session不仅能存字符串,还能存用户的信息,
  5. 用户拿到的是服务器给的sessionID,每个用户的SessionID唯一,服务器的Session存放东西;

Session和Cookie的区别?

  • Cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
  • Session把用户的数据写到用户独占的Session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
  • Session对象由服务创建,无需手动生成;

Session使用场景

  • 保存一个登陆用户的信息;
  • 可以用于保存购物车信息;
  • 在整个网站中经常会使用的数据,我们将他保存在Session中方便每次获取,可以减少服务器的资源浪费

  • Session创建的时候做了什么?
    session创建的时候会把SessionID添加到Cookie里面输出
Cookie cookie = new Cookie("JSESSIONID",sessionId);
resp.addCookie(cookie);
  • Session的获取,Session会自动创建
//获取Session
HttpSession session = req.getSession();
//往网页Session中存放名字,并获取Session的ID
public class SessionDemo01 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");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        //得到Session
        HttpSession session = req.getSession();

        //给Session中存储东西
        session.setAttribute("name","哈哈怪");

        //获取Session的ID
        String sessionId = session.getId();

        //判断Session是否为新创建的
        if (session.isNew()){
    
    
            //如果为新建的,则response返回的响应中输出ID
            resp.getWriter().write("Session创建成功,Session的ID为"+sessionId);
        }else{
    
    
            resp.getWriter().write("Session已经在服务器中创建存在了,Session的ID为"+sessionId);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doGet(req, resp);
    }
}
  • Web.xml设置Session的过期时间
<!--设置Session的失效时间-->
    <session-config>
        <!--15分钟后过期-->
        <session-timeout>15</session-timeout>
    </session-config>
  • 手动注销Session
//手动注销当前SessionID
session.invalidate();

猜你喜欢

转载自blog.csdn.net/kelekele111/article/details/123736646
今日推荐