目录
Cookie:
1.概念:客户端会话数据技术,将数据保存到客户端。
2.快速入门:
3.实现原理:
使用步骤:
①创建Cookie对象,绑定数据
new Cookie(String name,String value)
②发送Cookie对象
response.addCookie(Cookie cookie)
③获取Cookie,拿到数据
Cookie[] request.getCookies()
CookieDemo1类:
package jason.lh.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;
//Cookie快速入门
@WebServlet("/CookieDemo1")
public class CookieDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//①创建Cookie对象
Cookie c = new Cookie("msg","Hello");
//②发送Cookie
response.addCookie(c);
//
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
CookieDemo2类:
package jason.lh.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;
//Cookie快速入门
@WebServlet("/CookieDemo2")
public class CookieDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//③获取Cookie
Cookie[] cs = request.getCookies();
//④获取数据,遍历Cookies
if (cs != null) {
for (Cookie c : cs) {
String name = c.getName();
String value = c.getValue();
System.out.println(name + ":" + value);
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
this.doPost(request, response);
}
}
虚拟目录位/day16
控制台输出:
基于响应set-cookie和请求头cookie实现