Cookie :不属于内置对象
需要会:新增 读取 删除
应用:自动登录
前端界面:
<body>
<a href="CookieAddServlet">新增Cookie</a>
<a href="CookieReadServlet">读取Cookie</a>
<a href="CookieDeleteServlet">删除Cookie</a>
</body>
1、新增
CookieAddServlet.java
@WebServlet("/CookieAddServlet")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 完成Cookie的新增
// cookie name 一般使用项目的域名,cookie是写在浏览器上
Cookie cookie = new Cookie("www.situ.lession01","这是cookie的内容");
// 设置cookie的过期时间the maximum age in seconds for this Cookie.
cookie.setMaxAge(60*60*24*7);
// 写出cookie 向浏览器端写出Cookie
response.addCookie(cookie);
System.out.println("cookie写出成功!");
}
执行结果:
2、读取
CookieReadServlet.java
@WebServlet("/CookieReadServlet")
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 读取cookie
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
String name = cookie.getName();
if ("www.situ.lession01".equals(name)) {
String value = cookie.getValue();
System.out.println("读取到Cookie的信息=" + value);
}
}
}
结果:
3、删除
CookieDeleteServlet.java
@WebServlet("/CookieDeleteServlet")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 删除Cookie,将相同名称的Cookie的声明周期,设置为0,向浏览器重新写出
// 浏览器得到这个声明周期为0的Cookie,则浏览器会马上将其删除
Cookie cookie = new Cookie("www.situ.lession01", "");
cookie.setMaxAge(0);
response.addCookie(cookie);
System.out.println("删除成功");
}
结果: