import javax.servlet.ServletException;
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.text.SimpleDateFormat;
import java.util.Date;
public class LastTimeServlet extends HttpServlet {
private Cookie cookie;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
//第一次访问
Cookie[] cookies = req.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("lastTime")) {
Cookie cookieNew = new Cookie("lastTime", System.currentTimeMillis() + "");
cookieNew.setMaxAge(60 * 60);
resp.addCookie(cookieNew);
resp.getWriter().print("上次访问时间" + getFormatDateString(Long.valueOf(cookie.getValue())));
}
}
} else {
long mills = System.currentTimeMillis();
cookie = new Cookie("lastTime", String.valueOf(mills));
cookie.setMaxAge(60 * 60);
resp.addCookie(cookie);//给响应数据包(响应头 SetCookie: xxx)设置数据
resp.getWriter().write("第一次访问: 访问时间为 " + getFormatDateString(mills));
}
}
/**
* 把时间戳格式化为自定义的格式
*
* @param mills
* @return
*/
private String getFormatDateString(long mills) {
Date date = new Date(mills);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
}
Cookies应用之上一次访问时间
最新推荐文章于 2019-09-18 10:36:10 发布