-
cookie的概念
cookie是一种客户端会话技术将数据保存到客户端。
-
cookie的利弊:
1)将数据保存到客户端,十分方便,同时减轻服务器存储压力
2)对保存数据的个数(20)及大小有限制(4kb) -
作用
cookie用来保存少量及不太敏感的数据
可以在不登入的情况下,对客户端完成身份识别(即在客户端设置一个set-cookie的键值对,在访问的时候使用键值对来获取客户端的身份) -
使用Cookie
1)创建cookie对象
2)发送cookie对象
3)获取cookie对象由ServletDemo01设置cookie,ServletDemo02获取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; @WebServlet("/demo01") public class ServletDemo01 extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建cookie Cookie cookie = new Cookie("name", "zhangsan"); resp.addCookie(cookie); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } } 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; @WebServlet("/demo02") public class ServletDemo02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取cookie Cookie[] cookies = req.getCookies(); if (cookies!=null){ for (Cookie cookie : cookies) { //获取cookie值与名称 String value = cookie.getValue(); String name = cookie.getName(); System.out.println(name+":"+value); } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
-
其他问题
如何实现发送多个Cookie:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建cookie //创建第一个cookie Cookie cookie = new Cookie("name1", "zhangsan"); //发送第一个cookie resp.addCookie(cookie); //创建第二个cookie Cookie id = new Cookie("name2", "lisi"); //发送第二个cookie resp.addCookie(id); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); }
Cookie在浏览器中的保存多长时间:
默认情况下浏览器关闭后,Cookie数据被销毁
可以调用setmaxage(int seconds)方法来设置Cookie的存储时间- second为正数,将Cookie持久化写入硬盘,并且指定存储的时间,时间到了cookie自动失效
- second为零,删除cookie
- second小于零,默认值,即浏览器关闭后删除cookie
Cookie中如何保存中文:
在tomcat 8 之前 cookie中不能直接存储中文数据。
需要将中文数据转码--一般采用URL编码
在tomcat 8 之后,cookie支持中文数据。
特殊字符还是不支持,建议使用URL编码存储,URL解码解析//URL编码 name= URLEncoder.encode(name,"utf-8"); Cookie cookie = new Cookie("name", name); resp.addCookie(cookie); //解码 System.out.println(name+":"+ URLDecoder.decode(value,"utf-8"));