Cookie 和 Session

41 篇文章 2 订阅

目录

1. Cookie

2. Session

3. Cookie 和 Session 的联系

4. Cookie 和 Session 的区别

5. Cookie 和 Session 的应用


回顾HTTP协议:

HTTP的5个特点:

        1. 简单快速:客户端向服务器发送请求的时候,只需传递请求方法、路径和请求参数,因为协议简单,所以使得HTTP服务器的程序规模小,因为通信速度很快。

        2. 无连接:每次连接只处理一个请求。当服务器处理完客户端的请求之后,会立即断开连接。

        3. 无状态:HTTP不会记录每次请求的身份信息,因此前一次请求和后一次请求相互“不认识”。

        4. 可传递任意数据类型:HTTP允许传输任意数据类型,只需要在请求头中表示数据类型content-type。

        5. 一对一通讯:每次HTTP请求,都是一个客户端对应一个服务器端。

MS 

1. Cookie

HTTP协议是无状态的协议,前一次通信与后一次通信没有直接的联系。但在成功登陆网站之后,就可以知道之前是否登陆过。

 此时服务器这边需要有一个记录令牌信息以及令牌所对应客户的信息的机制,这个机制就是Session机制。

2. Session

 服务器在同一时间会接受到许多的请求,服务器需要区分这条请求是属于哪个用户的,因此,就需要在服务器端记录每个用户的令牌以及用户的信息的对应关系。

每个Session都有一个SessionId,这个SessionId保存在客户端的Cookie中,数据存储到服务器端。之后每一次请求request都会携带Cookie到服务器端,服务器端会根据Cookie中保存的SessionId来判断属于哪个会话。

会话的本质就是一个 哈希表 ,存储的是键值对结构,key就是令牌的ID(token / sessionId) , value 就是用户信息。

当用户登录的时候,服务器端在Session 中新增一个记录,并把SessionId / token 返回给客户端。

客户端后续再给服务器发送请求的时候,需要在请求中带上SessionId / token。

服务器端收到请求之后,会跟就请求中的SessionId / token 在Session 信息中获取到相应的用户信息,再进行后续的操作。

3. Cookie 和 Session 的联系

Session 会将SessionId 存储在Cookie 中

4. Cookie 和 Session 的区别

1. Cookie 是客户端的机制, Session 是服务器端的机制。

2. Cookie 和 Session 惊颤在一起配合使用,但是不是必须配合。

        a. 可以用Cookie 来保存数据在客户端,这些数据不一定就是用户身份信息或者 token / SessionId 。

         b.  Session 中的  token / SessionId 也不需要非得通过Cookie 来传递。

5. Cookie 和 Session 的应用

HttpServletRequest 类中的相关⽅法 :

HttpServletResponse 类中的相关⽅法

 

HttpSession 类中的相关⽅法 : 

Cookie 类中的相关⽅法  

1. HTTP 的 Cooke 字段中存储的实际上是多组键值对. 每个键值对在 Servlet 中都对应了⼀          个 Cookie 对象.
2. 通过 HttpServletRequest.getCookies() 获取到请求中的⼀系列 Cookie 键值对.
3. 通过 HttpServletResponse.addCookie() 可以向响应中添加新的 Cookie 键值对

 

Cookie 的 读 和 写: 

// cookie 的 读 和 写
@WebServlet("/cookie")
public class CookieServlet extends HttpServlet {
    /**
     * 写入到服务器端的内容(给客户端一个指令)
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("myCookie","Bite" + LocalDate.now());
        //发送给前端
        resp.addCookie(cookie);
        resp.setContentType("text.html;charset=utf-8");
        resp.getWriter().println("Cookie添加成功!");

    }

    /**
     * 读取
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        StringBuilder builder = new StringBuilder();
        if(cookies != null && cookies.length > 0) {
            for (Cookie item : cookies) {
                builder.append(item.getName() + ":" + item.getValue() + "<br>");
            }
        }
        resp.setContentType("text.html;charset=utf-8");
        resp.getWriter().println(builder.toString());
    }
}

Session 的 读 和 写:

session的 读 和 写
@WebServlet
public class SessonServlet extends HttpServlet {
    private  static final String SESSION_USER_KEY = " SESSION_USER_KEY";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String result = "操作失败";
        //1. 得到Session(false表示有会话返回session对象,没有返回null) (true 表示有会话返回session对象,没有会话创建一个会话)
        HttpSession session = req.getSession(true);
        if(null != session) {
            //得到(或创建)会话
            //将用户存储到Session
            User user = new User();
            user.setName("admin");
            user.setPassword("admin");
            // 1. 生成 token(SessionId)
            // 2. token 关联到用户用户对象
            // 3. 发送存储cookie信息到客户端(token)
            session.setAttribute(SESSION_USER_KEY,user);
            result = "Session写入成功!";
        }
        resp.getWriter().println(result);
    }


    /**
     * 读 session
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 得到Session(false表示有会话返回session对象,没有返回null) (true 表示有会话返回session对象,没有会话创建一个会话)
        HttpSession session = req.getSession(false);
        if(null == session) {
            //没有登录
            resp.getWriter().println("尚未登录!");
        } else {
            //已登录,打印用户信息
            // 2. 从session中得到关联的对象
            
            //1. 得到所有的cookie
            //2. 匹配token
            //3. 根据value 匹配映射对象
             User user = (User) session.getAttribute(" SESSION_USER_KEY");
            resp.getWriter().println("登录成功 " + user);
        }
    }
}

 

 

 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值