Cookie快速入门

文章目录

            • 实现步骤
            • 代码展示
            • 运行截图

实现步骤
  1. 创建Cookie对象,绑定键值对
  2. 响应Cookie对象给客户端浏览器
  3. 获取Cookie,拿到键值对

代码展示

CookieDemo1

@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 {
        doPost(request, response);
    }
}

CookieDemo2

@WebServlet("/CookieDemo2")
public class CookieDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取Cookies数组
        Cookie[] cookies = request.getCookies();
        // 判断cookies数组是否为空
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                // 打印cookie
                System.out.println(cookie.getName() + ":" + cookie.getValue());
            }
        }
    }

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

运行截图

Cookie快速入门_第1张图片
Cookie快速入门_第2张图片

你可能感兴趣的:(JavaWeb)