Servlet笔记(9):Cookie处理
一、Cookies处理
1、Cookies概念
Cookies是存储在客户端计算机上的文本文件,并保留各种跟踪信息。
识别返回用户的三个步骤
- 服务器脚本向浏览器发送一组Cookies。例如姓名、年龄或识别号码等。
- 浏览器将这些信息存储在本地计算机上。
- 当下一次浏览器向Web服务器发送任何请求时,浏览器会把这些Cookies信息发送到服务器,服务器将使用这些来识别用户。
中文的编码与解码
String str = java.net.URLEncoder.encode("中文"); //编码
String str = java.net.URLDecoder.decode("编码后的字符串"); // 解码
2、Cookies 剖析
Set-Cookie头包含一个键值对、一个有效期【expires】、一个路径【文件路径】和一个域【主机地址】
获取Cookies
Cookie[] HttpServletRequest.getCookies();
3、Cookies操作方法
序号 | 方法 & 描述 |
---|---|
1 | public void setDomain(String pattern) 该方法设置 cookie 适用的域,例如 w3cschool.cn。 |
2 | public String getDomain() 该方法获取 cookie 适用的域,例如 w3cschool.cn。 |
3 | public void setMaxAge(int expiry) 该方法设置 cookie 过期的时间(以秒为单位)。如果不这样设置,cookie 只会在当前 session 会话中持续有效。 |
4 | public int getMaxAge() 该方法返回 cookie 的最大生存周期(以秒为单位),默认情况下,-1 表示 cookie 将持续下去,直到浏览器关闭。 |
5 | public String getName() 该方法返回 cookie 的名称。名称在创建后不能改变。 |
6 | public void setValue(String newValue) 该方法设置与 cookie 关联的值。 |
7 | public String getValue() 该方法获取与 cookie 关联的值。 |
8 | public void setPath(String uri) 该方法设置 cookie 适用的路径。如果您不指定路径,与当前页面相同目录下的(包括子目录下的)所有 URL 都会返回 cookie。 |
9 | public String getPath() 该方法获取 cookie 适用的路径。 |
10 | public void setSecure(boolean flag) 该方法设置布尔值,表示 cookie 是否应该只在加密的(即 SSL)连接上发送。 |
11 | public void setComment(String purpose) 该方法规定了描述 cookie 目的的注释。该注释在浏览器向用户呈现 cookie 时非常有用。 |
12 | public String getComment() 该方法返回了描述 cookie 目的的注释,如果 cookie 没有注释则返回 null。 |
4、设置Cookies的步骤
(1) 创建Cookie对象
Cookie cookie = new Cookie("key","value");
key与value不能包含以下字符
[ ] ( ) = , " / ? @ : ;
(2)设置最大生存周期
使用 setMaxAge 方法来指定 cookie 能够保持有效的时间(以秒为单位)。
cookie.setMaxAge(60*60*24);
(3)发送Cookie到HTTP响应头
response.addCookie(cookie);
5、Cookie实例
HelloForm.java
/*** 包名:SelectTest* 作者:章恩光* 时间:2023/2/24 1:38 周五*/import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;public class HelloForm extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {Cookie firstName = new Cookie("first_name",req.getParameter("first_name"));Cookie lastName = new Cookie("last_name",req.getParameter("last_name"));firstName.setMaxAge(60*60*24);lastName.setMaxAge(60*60*24);resp.addCookie(firstName);resp.addCookie(lastName);resp.setContentType("text/html;charset=UTF-8");PrintWriter out = resp.getWriter();String title = "设置 Cookies 实例";String docType ="<!doctype html public \\"-//w3c//dtd html 4.0 " + "transitional//en\\">\\n";out.println(docType +"<html>\\n" +"<head><title>" + title + "</title></head>\\n" +"<body bgcolor=\\"#f0f0f0\\">\\n" +"<h1 align=\\"center\\">" + title + "</h1>\\n" +"<ul>\\n" +" <li><b>名字</b>:"+ req.getParameter("first_name") + "\\n" +" <li><b>姓氏</b>:"+ req.getParameter("last_name") + "\\n" +"</ul>\\n" +"</body></html>");}
}
ReadForm.java
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;/*** 包名:SelectTest* 作者:章恩光* 时间:2023/2/24 19:11 周五*/
public class ReadForm extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {Cookie cookie = null;Cookie[] cookies = null;cookies = req.getCookies();resp.setContentType("text/html;charset=UTF-8");PrintWriter out = resp.getWriter();String title = "Reading Cookies Example";String docType ="<!doctype html public \\"-//w3c//dtd html 4.0 " + "transitional//zh\\">\\n";out.println(docType +"<html>\\n" +"<head><title>" + title + "</title></head>\\n" +"<body bgcolor=\\"#f0f0f0\\">\\n" );if( cookies != null ) {out.println("<h2>查找 Cookies 名称和值</h2>");for (int i = 0; i < cookies.length; i++){cookie = cookies[i];out.print("名称:" + cookie.getName() + ",");out.print("值:" + cookie.getValue()+" <br/>");}} else {out.println("<h2 class=\\"tutheader\\">未找到 Cookies</h2>");}out.println("</body>");out.println("</html>");}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"><servlet><servlet-name>HelloForm</servlet-name><servlet-class>HelloForm</servlet-class></servlet><servlet-mapping><servlet-name>HelloForm</servlet-name><url-pattern>/HelloForm</url-pattern></servlet-mapping><servlet><servlet-name>ReadForm</servlet-name><servlet-class>ReadForm</servlet-class></servlet><servlet-mapping><servlet-name>ReadForm</servlet-name><url-pattern>/ReadForm</url-pattern></servlet-mapping>
</web-app>
效果图
6、删除Cookies
步骤:
- 读取现有cookie,并创建Cookie对象
- 使用setMaxAge()方法设置cookie周期为0
- 添加cookie添加到响应头
实例:
// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;// 扩展 HttpServlet 类
public class DeleteCookies extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {Cookie cookie = null;Cookie[] cookies = null;// 获取与该域相关的 Cookies 的数组cookies = request.getCookies();// 设置响应内容类型response.setContentType("text/html");PrintWriter out = response.getWriter();String title = "Delete Cookies Example";String docType = "<!doctype html public \\"-//w3c//dtd html 4.0 " + "transitional//en\\">\\n";out.println(docType +"<html>\\n" +"<head><title>" + title + "</title></head>\\n" +"<body bgcolor=\\"#f0f0f0\\">\\n" );if( cookies != null ){out.println("<h2>Cookies 名称和值</h2>");for (int i = 0; i < cookies.length; i++){cookie = cookies[i];//会话中。firstname不一致时删除cookie,并添加删除的cookie到响应头,以修改浏览器中的cookie状态if((cookie.getName()).compareTo("first_name") == 0 ){cookie.setMaxAge(0);response.addCookie(cookie);out.print("已删除的 cookie:" + cookie.getName() + "<br/>");}out.print("名称:" + cookie.getName() + ",");out.print("值:" + cookie.getValue()+" <br/>");}}else{out.println("<h2 class="tutheader">No cookies founds</h2>");}out.println("</body>");out.println("</html>");}
}