会话-cookie
Posted newcityboy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了会话-cookie相关的知识,希望对你有一定的参考价值。
package com.hopetesting.cookie;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author newcityman
* @date 2019/9/2 - 21:35
*/
@WebServlet("/cookieDemo01")
public class CookieDemo04 extends HttpServlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
//1、创建cookie对象
Cookie c1 = new Cookie("msg", "hellocookie");
//2、设置cookie的存活时间
c1.setMaxAge(30);//持久化到硬盘,30秒后自动删除
c1.setPath("/"); //设置跨项目访问cookie
// c1.setMaxAge(-10); //默认把数据存放到浏览器内存中,浏览器关闭后,cookie消失
// c1.setMaxAge(0); //删除cookie
//3、发送cookie
response.addCookie(c1);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
this.doPost(request, response);
package com.hopetesting.cookie;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author newcityman
* @date 2019/9/2 - 21:36
*/
@WebServlet("/cookieDemo02")
public class CookieDemo02 extends HttpServlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
Cookie[] cookies = request.getCookies();
if (cookies != null)
for (Cookie cookie : cookies)
String name = cookie.getName();
String value = cookie.getValue();
System.out.println(name + "==" + value);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
this.doPost(request, response);
以上是关于会话-cookie的主要内容,如果未能解决你的问题,请参考以下文章
Node.js/Express.js 会话管理 cookie 为会话 cookie