一. cookie简介
Cookie 存储于本地浏览器中的一些数据。当 web 服务器向浏览器发送 web 页面时,Cookie 可以解决 “如何记录客户端的用户信息”等问题。比如
二. 添加cookie
@WebServlet("/s1") public class SetCookie extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie cookie = new Cookie("A", "a"); cookie.setMaxAge(10);//10秒后过期 resp.addCookie(cookie); } }
添加cookie后,我们可以通过application的Cookie或者网址左边的按钮来查看我们的cookie
三. 读取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; import java.util.Arrays; @WebServlet("/s2") public class GetCookie extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie[] cookies = req.getCookies(); for (Cookie cookie:cookies) { System.out.println(cookie.getName() + ":" + cookie.getValue()); } } }
接下来我们先访问s1,再访问s2,则控制台输出:
JSESSIONID:24D09D61602B05829FA33C37731CD65D
A:a
请登录之后再进行评论