Cookie:
1. 概念:客户端会话技术,将数据保存到客户端(客户再次和服务器通讯会将以前数据一起发送给服务器 )
2. 快速入门:
* 使用步骤:
1. 创建Cookie对象,绑定数据
* new Cookie(String name, String value)
2. 通过响应respond来发送Cookie对象
* response.addCookie(Cookie cookie) ---服务器发送Cookie给浏览器
3. 浏览器如果再次servlet,可以获取Cookie,拿到数据
* Cookie[] request.getCookies() ---获取浏览器返回的Cookie数据
注意:如果换一个浏览器获取关闭浏览器重启,回话就结束了,Cookie保存数据就失效。
3. 实现原理
* 基于响应头set-cookie和请求头cookie实现
CookieDemo1A.java
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("/CookieDemo1A")
public class CookieDemo1A extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("msg", "lisi");
response.addCookie(cookie);
}
}
CookieDemo1B.java
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("/CookieDemo1B")
public class CookieDemo1B extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cs = request.getCookies();
for (Cookie c : cs) {
String name = c.getName();
String value = c.getValue();
System.out.println(""+name+":"+value);
}
}
}
测试方法1:
在同一个浏览器地址栏里面先输入:http://localhost/cookie/CookieDemo1A
执行后再在该浏览器输入或者打开一个新页面输入:http://localhost/cookie/CookieDemo1B
输入如下内容:
JSESSIONID:DC1CAE64269A9F82DB7DED9FCB8BC887
msg:lisi
Idea-661643a5:f8768c12-dedd-49c0-abba-72c4a6d2af18
JSESSIONID:5347B7D7C7665B0DDECE5D006D1AF452
测试方法2:
关闭所有浏览器,直接在浏览器中输入:http://localhost/cookie/CookieDemo1B
这次只会输出Idea-661643a5:f8768c12-dedd-49c0-abba-72c4a6d2af18,我们设定的cookie不会输出