从请求中拿到cookie信息
服务器响应给客户端cookie
Cookie[] cookies = req.getCookies();//获取cookie cookie.getName();//获取cookie中的key cookie.getValue();//获取cookie中的value Cookie cookie = new Cookie("lastLoginTime", "" + System.currentTimeMillis());//新建一个cookie cookie.setMaxAge(24*60*60);//设置cookie的有效期 resp.addCookie(cookie);//响应给客户端一个cookie
cookie:一般会保存在本地的用户目录下/AppData下
一个网站cookie是否存在上限?
删除cookie
public class CookieDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解决中文乱码 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); PrintWriter writer = resp.getWriter(); //cookie,服务器从客户端中获取 Cookie[] cookies = req.getCookies();//这里返回的是数组,说明Cookie可能存在多个 if (cookies == null) { writer.print("这是您第一次访问本站!"); } else { writer.print("您上一次访问本站的时间是:" ); for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if ("lastLoginTime".equals(cookie.getName())) { long lastLoginTime = Long.parseLong(cookie.getValue()); Date date = new Date(lastLoginTime); SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); writer.print(sd.format(date)); } } } //添加 or 更新 Cookie cookie = new Cookie("lastLoginTime", "" + System.currentTimeMillis()); //设置cookie为1天 cookie.setMaxAge(24*60*60); resp.addCookie(cookie); writer.flush(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
public class CookieDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解决中文乱码 req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); PrintWriter writer = resp.getWriter(); //cookie,服务器从客户端中获取 Cookie[] cookies = req.getCookies(); if (cookies == null) { writer.print("这是您第一次访问本站!"); } else { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if ("name".equals(cookie.getName())) { //防止网络传输中文乱码问题 writer.print(URLDecoder.decode(cookie.getValue(), "UTF-8")); } } } //添加 or 更新 Cookie cookie = new Cookie("name", URLEncoder.encode("狂神", "UTF-8")); resp.addCookie(cookie); writer.flush(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }