其他分享
首页 > 其他分享> > 会话技术的概述以及Cookie的快速入门

会话技术的概述以及Cookie的快速入门

作者:互联网

会话技术的概述

  1、会话:一次会话中包含多次请求和响应

    一次会话:浏览器第一次给服务器资源发送请求,会话建立,直到有一方断开为止

  2、功能:再一次会话的范围内的多次请求间,共享数据

  3、方式:

    1、客户端会话技术:Cookie

    2、服务端会话技术:Session

 

 

 

 

 

Cookie的快速入门

使用步骤:

  1、创建Cookie对象,绑定数据

    new Cookie(String name,String value);

  2、发送Cookie对象

    response.addCookie(Cookie cookie);

  3、获取Cookie,拿到数据

    Cookie[] request.getCookies();

创建和发送Cookie:

/**
 * Cookie快速入门
 */
@WebServlet("/CookieDemo1")
public class CookieDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建Cookie对象
        Cookie cookie = new Cookie("msg", "hello");
        //发送Cookie
        response.addCookie(cookie);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

获取和遍历Cookie:

/**
 * Cookie快速入门
 */
@WebServlet("/CookieDemo1")
public class CookieDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取Cookie
        Cookie[] cookies = request.getCookies();
        //获取数据,遍历Cookies
        if (cookies!=null){
            for (Cookie c : cookies) {
                String name = c.getName();
                String value = c.getValue();
                System.out.println(name+":"+value);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

 

标签:入门,void,request,HttpServletResponse,会话,Cookie,response
来源: https://www.cnblogs.com/xjw12345/p/16572327.html