16.6 会话技术_Cookie案例_记住上一次访问时间
16.6.1 需求
- 1.访问一个Servlet,如果是第一次访问,则提示:您好,欢迎您首次访问。
- 2.如果不是第一次访问,则提示:欢迎回来,您上次访问时间为:显示时间字符串
16.6.2 分析
- 1.可以采用Cookie来完成;
- 2.在服务器中的Servlet判断是否有一个名为lastTime的cookie 。
- 有:不是第一次访问
- 1.响应数据:欢迎回来,您上次访问时间为:2021年02月09日 21:04:32
- 2.写回 Cookie:lastTime=2021年02月09日 21:04:33
- 没有:是第一次访问
- 1.响应数据:您好,欢迎您首次访问
- 2.写回 Cookie:lastTime=2021年02月09日 21:04:32
16.6.3 示例
package com.xww.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("/CookieTestt")
public class CookieTestt 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);
response.getWriter().write("<h1>欢迎回来,您上次访问时间为:"+value+"</h1>");
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);
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);
}
}