第四部分 第十一章 2.Cookie案例
2019-08-26
| Java | 阅读 | 650 字 | 3 分钟11.2 案例:记住上一次访问时间
需求
- 访问一个Servlet,如果是第一次访问,则提示:您好,欢迎您首次访问。
- 如果不是第一次访问,则提示:欢迎回来,您上次访问时间为:显示时间字符串
分析
可以采用Cookie来完成
在服务器中的Servlet判断是否有一个名为lastTime的cookie
- 有:不是第一次访问
- 响应数据:
欢迎回来,您上次访问时间为:2018年6月10日11:50:20
- 写回Cookie:
lastTime=2018年6月10日11:50:01
- 没有:是第一次访问
- 响应数据:
您好,欢迎您首次访问
- 写回Cookie:
lastTime=2018年6月10日11:50:01

代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| package com.foreversfj.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.net.URLDecoder; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date;
@WebServlet("/cookieTest") public class CookieTest 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; Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); System.out.println("编码前:"+str_date); str_date = URLEncoder.encode(str_date,"utf-8"); System.out.println("编码后:"+str_date); cookie.setValue(str_date); cookie.setMaxAge(60 * 60 * 24 * 30); response.addCookie(cookie); String value = cookie.getValue(); System.out.println("解码前:"+value); value = URLDecoder.decode(value,"utf-8"); System.out.println("解码后:"+value); response.getWriter().write("<h1>欢迎回来,您上次访问时间为:"+value+"</h1>"); break; } } }
if(cookies == null || cookies.length == 0 || flag == false){
Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); System.out.println("编码前:"+str_date); str_date = URLEncoder.encode(str_date,"utf-8"); System.out.println("编码后:"+str_date);
Cookie cookie = new Cookie("lastTime",str_date); 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); } }
|
本文标题:第四部分 第十一章 2.Cookie案例
文章作者:foreverSFJ
发布时间:2019-08-26 19:11:07
最后更新:2019-08-26 19:11:07
原始链接:Notes/Java/JavaWeb/11_2 Cookie案例.html
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明出处!
分享