目录
1 Cookie快速入门
概念:客户端会话技术,将数据保存到客户端
Cookie 使用步骤 | 1. 创建Cookie对象,绑定数据 * new Cookie(String name, String value) 2. 发送Cookie对象 * response.addCookie(Cookie cookie) 3. 获取Cookie,拿到数据 * Cookie[] request.getCookies() |
@WebServlet("/cookieDemo1")
public class CookieDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("cookie1","hello");//1 创建Cookie对象
resp.addCookie(cookie);// 2 发送Cookie
}
}
@WebServlet("/cookieDemo2")
public class CookieDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();//3 获取Cookie
if(cookies!=null){
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
System.out.println(name+value);
}
}
}
}
Cookie实现原理:基于响应头set-cookie和请求头cookie实现
2 创建多个Cookie并发送
可以创建多个Cookie对象