什么是Cookie
Cookie:客户端会话技术,将数据保存到客户端,以后每次请求都携带Cookie数据进行访问
Cookie 数据存放在浏览器端(客户端)
创建Cookie
1.创建Cookie
Cookie cookie = new Cookie("key","value");
2.使用response响应Cookie给客户端(浏览器)
response.addCookie(cookie);
java
/*
* Copyright (c) 2020, 2023, All rights reserved.
*
*/
package cn;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Retention;
/**
* <p>Project: scl-cookie - AddCookie</p>
* <p>Powered by scl On 2023-09-04 16:36:59</p>
* <p>描述:<p>
*
* @author 孙臣龙 [1846080280@qq.com]
* @version 1.0
* @since 17
*/
@WebServlet("/addCookie")
public class AddCookie extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//创建Cookie
Cookie cookie = new Cookie("meite","scl");
//设置存活时间
cookie.setMaxAge(60);
//添加Cookie
resp.addCookie(cookie);
}
}
3.获取Cookie
Cookie[] cookies = request.getCookies();
for(Cookie str : cookies){
System.out.println(str.getName()+str.getValue());
}
java
/*
* Copyright (c) 2020, 2023, All rights reserved.
*
*/
package cn;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* <p>Project: scl-cookie - GetCookie</p>
* <p>Powered by scl On 2023-09-04 16:43:04</p>
* <p>描述:<p>
*
* @author 孙臣龙 [1846080280@qq.com]
* @version 1.0
* @since 17
*/
@WebServlet("/getCookie")
public class GetCookie extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取Cookie
Cookie[] cookies = req.getCookies();
for(Cookie str : cookies){
System.out.println(str.getName()+str.getValue());
}
}
}
Cookie过期时间
setMaxAge(int seconds):设置Cookie存活时间
1.正数:将Cookie写入浏览器所在的电脑硬盘,持久化存储,到期自动删除
2.负数:默认值,Cookie存储在浏览器内存中,当浏览器关闭,内存释放,则Cookie被销毁。
3.零:删除对应Cookie
java
//创建Cookie
Cookie cookie = new Cookie("meite","scl");
//设置存活时间
cookie.setMaxAge(60);
//添加Cookie
resp.addCookie(cookie);