# 用Cookie记录上次的访问时间
/**
- 思路:
- 先判断是否是第一次进入该页面
- 如果是,则响应: 欢迎您首次访问
- 如果不是,则响应: 上次的访问时间
- 具体步骤:
- 1.遍历所有的Cookie,看有没有该Cookie(事先设定一个Cookie)
- 2 如果有,则说明不是第一次登录
- 2.1 获取上次登录时的Cookie值,响应: 上次的访问时间
- 2.2记录本次的登录时间
- 3.如果没有,说明是第一次登录,记录当下的时间,存入Cookie
- 3.1响应: 欢迎您首次访问
*/
@WebServlet("/cookieTest")
public class CookieTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求和响应编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//创建一个布尔值
boolean flag = false;
//获取所有cookie
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
//遍历cookie
for (Cookie cookie : cookies) {
//判断是否是第一次进入
if ("lastTime".equals(cookie.getName())) {
flag = true;
//说明不是第一次进入
//获取上次的访问时间
String value = cookie.getValue();
//URL解码
value = URLDecoder.decode(value, "utf-8");
//响应页面
response.getWriter().write("<h1>"+"你上次的访问时间为:" + value+"</h1>");
//记录本次的访问时间
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
String format = sdf.format(date);
//URL编码
format = URLEncoder.encode(format, "utf-8");
//用cookie记录
cookie.setValue(format);
//设置时间为1个月
cookie.setMaxAge(60 * 60 * 24 * 30);
//发送cookie
response.addCookie(cookie);
}
}
}
if (cookies == null || cookies.length == 0 || flag == false) {
//说明是第一次访问
//记录本次的访问时间
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
String format = sdf.format(date);
//URL编码
format = URLEncoder.encode(format, "utf-8");
//创建cookie
Cookie cookie = new Cookie("lastTime", format);
//用cookie记录
cookie.setValue(format);
//设置时间为1个月
cookie.setMaxAge(60 * 60 * 24 * 30);
//发送cookie
response.addCookie(cookie);
//响应页面
response.getWriter().write("欢迎您首次访问");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}