关于Cookie的一些小饼干
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解决中文乱码问题 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); javax.servlet.http.Cookie[] cookies = req.getCookies();//服务器端从客户端获取饼干 //判断cookies是否存在 if(cookies!=null){ out.write("上次登录的时间为:"); for(int i=0;i<cookies.length;i++){ Cookie cookie=cookies[i]; if(cookie.getName().equals("lasttime")){ long lasttime = Long.parseLong(cookie.getValue()); Date date = new Date(lasttime); out.write(date.toLocaleString()); } } }else { out.write("你好,这是您第一次登录本站"); } //服务器端给客户端响应一个cookie Cookie cookie = new Cookie("lasttime", System.currentTimeMillis()+""); cookie.setMaxAge(24*60*60);//设置cookie的生命周期为一天 resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
还有如果用Cookie传递中文数据的要编码解码:
Cookie cookie = new Cookie("name", URLEncoder.encode("撒旦","utf-8"));//编码 out.write(URLDecoder.decode(cookie.getValue(),"utf-8"));//解码
标签:
JavaWeb
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义