推荐答案
在 JSP 中使用 Cookie 的步骤如下:
创建 Cookie:
Cookie cookie = new Cookie("username", "JohnDoe");设置 Cookie 属性:
cookie.setMaxAge(60 * 60 * 24); // 设置 Cookie 有效期为 1 天 cookie.setPath("/"); // 设置 Cookie 的路径将 Cookie 添加到响应中:
response.addCookie(cookie);
读取 Cookie:
// www.javascriptcn.com code example Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie c : cookies) { if ("username".equals(c.getName())) { String username = c.getValue(); out.println("Username: " + username); } } }删除 Cookie:
Cookie cookie = new Cookie("username", ""); cookie.setMaxAge(0); // 设置 Cookie 有效期为 0,表示删除 response.addCookie(cookie);
本题详细解读
1. 创建 Cookie
在 JSP 中,可以通过 javax.servlet.http.Cookie 类来创建 Cookie。创建时需要指定 Cookie 的名称和值。
Cookie cookie = new Cookie("username", "JohnDoe");2. 设置 Cookie 属性
创建 Cookie 后,可以设置其属性,如有效期、路径、域名等。
setMaxAge(int expiry):设置 Cookie 的有效期,单位为秒。设置为0表示删除该 Cookie。setPath(String uri):设置 Cookie 的路径,只有在该路径下的请求才会携带该 Cookie。
cookie.setMaxAge(60 * 60 * 24); // 1 天
cookie.setPath("/"); // 根路径3. 将 Cookie 添加到响应中
通过 HttpServletResponse 的 addCookie(Cookie cookie) 方法将 Cookie 添加到响应中,发送给客户端。
response.addCookie(cookie);
4. 读取 Cookie
在后续的请求中,可以通过 HttpServletRequest 的 getCookies() 方法获取客户端发送的所有 Cookie。然后遍历这些 Cookie,找到需要的 Cookie 并读取其值。
// www.javascriptcn.com code example
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if ("username".equals(c.getName())) {
String username = c.getValue();
out.println("Username: " + username);
}
}
}5. 删除 Cookie
要删除一个 Cookie,可以创建一个同名的 Cookie,并将其有效期设置为 0,然后将其添加到响应中。
Cookie cookie = new Cookie("username", "");
cookie.setMaxAge(0); // 删除 Cookie
response.addCookie(cookie);通过以上步骤,你可以在 JSP 中有效地使用 Cookie 来存储和读取用户信息。