添加:显示上次访问时间的cookies

This commit is contained in:
2025-03-24 14:05:22 +08:00
parent 4f4664995c
commit 255c56378d
3 changed files with 106 additions and 25 deletions
@@ -0,0 +1,67 @@
package com.msksbr.test.servlet.servlet.cookies;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
@WebServlet(
name = "lastAccessServlet",
urlPatterns = "/cookies/last-access-servlet"
)
public class LastAccessServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
Cookie[] cookies = request.getCookies();
boolean flag = false;
if (cookies.length > 0 && cookies != null) {
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");
cookie.setValue("解码后:" + value);
response.getWriter().write("欢迎回来,您上次访问时间" + "为:" + value);
Date date = new Date();
SimpleDateFormat timesdf = new SimpleDateFormat("yyyy年MM" + "月dd日 HH:mm:ss");
String str_time = timesdf.format(date);
System.out.println("编码前:" + str_time);
str_time = URLEncoder.encode(str_time, "UTF-8");
System.out.println("编码后:" + str_time);
cookie.setValue(str_time);
cookie.setMaxAge(60 * 60 * 24 * 30);
response.addCookie(cookie);
break;
}
}
if (cookies == null || cookies.length == 0 || !flag) {
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("您好,欢迎您首次访问");
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}