cooklie的特点和作用
1. cookie存储数据在客户端浏览器
2.浏览器对于单个cookie 的大小有限制(4kb)以及对同一个域名下的总cookie数量也有限制(2o个)
作用:
1. cookie—般用于存出少量的不太敏感的数据
2.在不登录的情况下,完成服务器对客户端的身份识别
会话技术_案例_分析和代码:
可以采用Cookie来完成
在服务器中的Servlet判断是否有一个名为lastTime的cookie
有:不是第一次访问。
响应数据:欢迎回来,您上次访问为2022年8月11日15:29:37
写回Cookie:lastTime2022年8月11日15:30:15
没有:是第一次访问
响应数据:您好,欢迎您首次访问。
写回Cookie:lastTime=2022年8月11日15:32:54
@WebServlet("/CookieDemo6") public class CookieDemo6 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); Cookie[] cookies = request.getCookies(); boolean flag = false; if (cookies !=null && cookies.length>0){ for (Cookie cookie : cookies) { String name = cookie.getName(); if ("lastTime".equals(name)){ flag = true; String value = cookie.getValue(); System.out.println("解码前:"+value); value = URLDecoder.decode(value, "utf-8"); System.out.println("解码后:"+value); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String format = sdf.format(date); System.out.println("编码前:"+format); format = URLEncoder.encode(format, "utf-8"); System.out.println("编码后:"+format); cookie.setValue(format); cookie.setMaxAge(60*60*24*30); response.addCookie(cookie); response.getWriter().write("<h1>欢迎回来,您上次访问时间为:"+value+"</h1>"); break; } } } if (cookies == null || cookies.length == 0 || flag == false){ Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String format = simpleDateFormat.format(date); System.out.println("编码前"+format); format = URLEncoder.encode(format,"utf-8"); System.out.println("编码后"+format); Cookie cookie = new Cookie("lastTime",format); cookie.setValue(format); cookie.setMaxAge(60*60*24*30); response.addCookie(cookie); response.getWriter().write("<h1>您好,欢迎您首页访问成功</h1>"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)