案例需求
- 访问一个Servlet, 如果是第一次访问 , 则提示: 您好, 欢迎您首次访问.
- 如果不是第一次访问 , 则提示: 欢迎回来 , 您上次访问时间为 : 显示时间字符串
分析
- 可以采用Cookie来完成
- 在服务器中的Servlet来判断是否有一个名为LastTime的Cookie
有, 不是第一次访问
没有,第一次访问
![在这里插入图片描述](https://img-blog.csdnimg.cn/a94467639b0641eaa19b5d1447ac3aa2.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA56i755Sw6YeM5bGV5pyb6ICF,size_20,color_FFFFFF,t_70,g_se,x_16)
代码实现
@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 * 30 * 24 * 30);
response.addCookie(cookie);
String value = cookie.getValue();
System.out.println("解码前" + value);
value=URLEncoder.encode(value,"utf-8");
System.out.println("解码后" + value);
response.getWriter().write("欢迎回来,你上次访问的时间是:" + value);
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 * 30 * 24 * 30);
response.addCookie(cookie);
response.getWriter().write("欢迎您首次访问");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}