1. Cookie简介
Cookie 由服务器创建,保存到浏览器
保存用户信息
服务器端的Cookie对象,具有name属性,和value属性
浏览器端的Cookie,默认类似于Cookie Map,可以通过 cookie[name].value取值
2. Cookie的运行原理
客户端往服务器发送第一次请求的时候,
在服务器创建一个cookie对象
服务器会把这个cookie对象发送给浏览器
浏览器每次发送请求的时候都会携带这个cookie对象
3. Cookie的创建、获取与修改
3.1 创建
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.创建Cookie对象
// Cookie(属性, 值) 属性必须写英文,值最好也存英文
Cookie cookie = new Cookie("name", "tomcat");
// 2.响应给浏览器
response.addCookie(cookie);
// request.getContextPath() => /当前项目名称java
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
3.2 获取
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
System.out.println(cookie.getName() + ": " + cookie.getValue());
}
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}
3.3 修改
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 修改名称为name的cookie属性
// 方法一: 覆盖
Cookie cookie = new Cookie("name", "wyCookie");
response.addCookie(cookie);
// 方法二: 找到指定的Cookie,然后修改
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie1 : cookies) {
if (cookie1.getName().equals("name")) {
cookie1.setValue("yName");
response.addCookie(cookie1);
}
}
}
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
4. 持久化Cookie
生命周期:默认当前对话
cookie.setMaxAge(time);
time的单位是秒
如果time = 0, 瞬间消亡
time < 0 当前会话
time > 0 time 秒后消亡
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = new Cookie("wy", "now1542"); cookie.setMaxAge(30); response.addCookie(cookie); //给指定的cookie设置有效时间 Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie1 : cookies) { if (cookie1.getName().equals("name")) { cookie1.setMaxAge(60); response.addCookie(cookie1); } } } response.sendRedirect(request.getContextPath() + "/index.jsp"); }
5. Cookie的有效路径
浏览器通过 url 地址栏给服务器发送请求的时候,并不是携带了浏览器中保存的所有的cookie对象,而是在发送指定的url请求的时候,携带对应的 cookie对象,,cookie默认保存在项目的根路径下,也可以通过 setPath(path) 指定 cookie的有效路径
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置Cookie的有效路径 Cookie cookie = new Cookie("url", "www.baidu.com"); cookie.setPath("/wy"); // 由浏览器解析 /代表主机地址 response.addCookie(cookie); response.sendRedirect(request.getContextPath() + "index.jsp"); }
6. Cookie的弊端
明文显示,不安全
只能存储字符串,不能存储对象
每次请求都要携带Cookie,耗费流量
补充
在浏览器中获取Cookie名称
在Servlet中,将Cookie的名称存在 session中
HttpSession session = request.getSession(); session.setAttribute("CookieName", "wy");
在浏览器端读取
value="${cookie[sessionScope.password].value}
利用cookie,实现记住账号功能
在LoginServlet下获取当前Cookie中的 id 和 password的 值
如果Cookie中不存在,就从输入栏中获取id 和password的值,并将值添加到Cookie中
跳转到login.jsp页面
在jsp页面点击登陆跳转到success.html 页面
LoginServlet
package com.example; /** * @author HelloWorld * @create 2021-05-27-18:51 * @email 154803771@qq.com */ import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; @WebServlet(name = "LoginServlet", value = "/LoginServlet") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = "", password = ""; Cookie[] cookies = request.getCookies(); // 1.Cookie不为空时遍历 if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("id")) { id = cookie.getValue(); if (!password.equals("")) { break; } } if (cookie.getName().equals("password")) { password = cookie.getValue(); if (!id.equals("")) { break; } } } } System.out.println("cookie中的id" + id); if (id.equals("") && password.equals("")) { id = request.getParameter("id"); password = request.getParameter("password"); System.out.println("输入的id" + id); } response.addCookie(new Cookie("id", id)); response.addCookie(new Cookie("password", password)); HttpSession session = request.getSession(); session.setAttribute("id", "id"); session.setAttribute("password", "password"); response.sendRedirect(request.getContextPath() + "/login.jsp"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = "", password = ""; Cookie[] cookies = request.getCookies(); // 1.Cookie不为空时遍历 if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("id")) { id = cookie.getValue(); if (!password.equals("")) { break; } } if (cookie.getName().equals("password")) { password = cookie.getValue(); if (!id.equals("")) { break; } } } } System.out.println("cookie中的id" + id); if (id.equals("") && password.equals("")) { id = request.getParameter("id"); password = request.getParameter("password"); System.out.println("输入的id" + id); } response.addCookie(new Cookie("id", id)); response.addCookie(new Cookie("password", password)); HttpSession session = request.getSession(); session.setAttribute("id", "id"); session.setAttribute("password", "password"); request.getRequestDispatcher("/success.html").forward(request, response); } }
login.jsp
<%-- Created by IntelliJ IDEA. User: wy155 Date: 2021/5/27 Time: 17:30 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="LoginServlet" method="post"> <table> <tr> <th>账号: </th> <td><input type="text" name="id" value="${cookie[sessionScope.id].value}"></td> </tr> <tr> <th>密码: </th> <td><input type="password" name="password" value="${cookie[sessionScope.password].value}"></td> </tr> <tr> <th colspan="2"><input type="submit" value="登陆"></th> </tr> </table> </form> </body> </html>
success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Success!</h1>
</body>
</html>