Cookie
Cookie
浏览器利用Cookie缓存数据 服务器往浏览器写入
浏览器在发送请求的时候 会把Cookie发送给服务器哪个服务器发送的Cookie 浏览器就发送给谁)
创建Cookie
在Servlet 创建Cookie 响应给浏览器
@WebServlet("/Test")
public class Test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("key", "Message");
cookie.setMaxAge(3600);//设置Cookie的存活时间 单位是 秒
resp.addCookie(cookie);
System.out.println("hello");
}
}
浏览器请求 访问

获取Cooke
@WebServlet("/GetCookie")
public class GetCookie extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Http请求获取cookie 的值
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
if ("key".equals(cookie.getName())) {
System.out.println(cookie.getValue());
}
}
}
}

浙公网安备 33010602011771号