Java Web 从入门到退坑 —— 第十一章 Cookie
By -gregPerlinLi-
1. 什么是 Cookie
Cookie 翻译过来是饼干的意思
Cookie 是服务器通知客户端保存键值对的一种技术
客户端有了 Cookie 后,每次请求都发送给服务器
每个 Cookie 的大小不能超过 4KB
2. 如何创建 Cookie
示例代码:
protected void createCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. Create Cookie object
Cookie cookie = new Cookie("key1", "value1");
// 2. Notify client to save Cookie
response.addCookie(cookie);
response.getWriter().write("Create Cookie successful!\n成功创建Cookie!");
}
效果:
3. 服务器如何获取 Cookie
服务器获取客户端的 Cookie 只需要一行代码:request.getCookies():Cookie[]
示例代码:
protected void getCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
// getName() is return the key (name) of Cookie
// getValue() is return the value of Cookie
response.getWriter().write("Cookie[ " + cookie.getName() + " = " + cookie.getValue() + "] <br/>");
}
// Get specific cookies
Cookie iWantCookie = null;
for ( Cookie cookie : cookies ) {
if ( "key2".equals(cookie.getName()) ) {
iWantCookie = cookie;
break;
}
}
// If it is not equal to null, it indicates that the value has been assigned, that is, the required cookie has been found
if (iWantCookie != null) {
response.getWriter().write("<br/> iWantCookie[ " + iWantCookie.getName() + " = " + iWantCookie.getValue() + "] <br/>");
}
}
4. Cookie 值的修改
方案一:
1. 先创建一个要修改的同名的 Cookie 对象
2. 在构造器中同时赋予新的 Cookie 值
3. 调用 response.addCookie(Cookie);
通知客户端保存修改
示例代码:
protected void updateCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. Create a cookie object with the same name to modify
// 2. Assign a new cookie value to the constructor at the same time
Cookie cookie = new Cookie("key1", "newValue1");
// 3. Call response.addCookie(Cookie); Notify client to save changes
response.addCookie(cookie);
response.getWriter().write("The Cookie key1 is updated");
}
方案二:
1. 先查找到需要修改的 Cookie 对象
2. 调用 setValue()
方法赋予新的 Cookie 值
3. 调用 response.addCookie(Cookie);
通知客户端保存修改
示例代码:
protected void updateCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. Find the cookie object that needs to be modified
Cookie updateCookie = null;
for ( Cookie cookie : cookies ) {
if ( "key2".equals(cookie.getName()) ) {
updateCookie = cookie;
}
}
if ( updateCookie != null ) {
// 2. Call the setValue() method to give a new cookie value
cookie.setValue("newValue2");
// 3. Call response.addCookie(Cookie); Notify client to save changes
response.addCookie(updateCookie);
}
response.getWriter().write("The Cookie key2 is updated");
}
注意⚠️:对于 Cookie,值不应包含空格、方括号、圆括号、等号、逗号、双引号、斜杠、问号、@符号、冒号和分号,而空值在所有的浏览器上的行为不一定相同,若真的需要,请使用 BASE64 编码!
5. 浏览器查看 Cookie
5.1. Chrome 浏览器如何查看 Cookie
1. 按下 F12 按键,打开开发者工具
2. 点击 Application
选项卡
3. 点击左侧的 Cookies
按钮,然后选中想要查看的网站,即可查看该网页的 Cookie
4. 在该界面中,你可以更改 Cookie 的值,并将其删除
5.2. Firefox 浏览器如何查看 Cookie
1. 按下 F12 按键,打开开发者工具
2. 点击 存储
选项卡
3. 点击左侧的 Cookies
按钮,然后选中想要查看的网站,即可查看该网页的 Cookie
4. 在该界面中,你可以新增、更改 Cookie 的值,并将其删除
5.3. Safari 浏览器如何查看 Cookie
1. 按下 ⌘+⌥+I 快捷键,打开开发者工具
2. 点击 储存空间
选项卡
3. 点击左侧的 Cookies
按钮,然后选中想要查看的网站,即可查看该网页的 Cookie
4. 在该界面中,你可以新增、更改 Cookie 的值,并将其删除
6. Cookie 生命控制
Cookie 的生命控制指的是如何管理 Cookie 什么时候被销毁(删除)
setMaxAge()
设置 Cookie 的最大生存时间
正值表示 Cookie 将在该值表示的秒数后过期(注意⚠️:该值是 Cookie 过期的最大生存时间,不是 Cookie 的当前生存时间)。
负值意味着 Cookie 不会被永久储存,将在 Web 浏览器退出后删除(默认值是 -1
)。
0
值会导致马上删除 Cookie。
示例代码:
protected void defaultLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("defaultLife", "defaultLife");
// Set survival time
cookie.setMaxAge(-1);
response.addCookie(cookie);
}
protected void deleteNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// First find the cookie object to delete
Cookie iWantCookie = null;
for ( Cookie cookie : cookies ) {
if ( "key2".equals(cookie.getName()) ) {
iWantCookie = cookie;
break;
}
}
if (iWantCookie != null ) {
// Call setMaxAge(0) Delete now, don't wait for browser to close
iWantCookie.setMaxAge(0);
// Call response.addCookie(cookie);
response.addCookie(iWantCookie);
response.getWriter().write("Cookie defaultLifetime was deleted");
}
}
protected void life3600(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("life3600", "life3600");
// The cookie was deleted after one hour
cookie.setMaxAge(60 * 60);
response.addCookie(cookie);
response.getWriter().write("Created a Cookie that survived for one hour");
}
7. Cookie 有效路径 path
的设置
Cookie 的 path
属性可以有效地过滤哪些 Cookie 可以发送给服务器,哪些不可以。
path
属性是通过请求的地址来进行有效的过滤。
示例:
CookieA path=/projectName
CookieB path=/projectName/abc
请求地址如下:http://ip:port/projctName/a.html
这时候,CookieA 发送,CookieB 不发送
若请求地址如下:http://ip:port/projctName/abc/a.html
则在这时候,CookieA 发送,CookieB 发送
示例代码:
protected void testPath(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("path1", "path1");
// request.getContextPath() ==> Get the project path
// ==> /projectName/abc
cookie.setPath(request.getContextPath() + "/abc");
response.addCookie(cookie);
response.getWriter().write("A Cookie with path is created");
}