cookie获取浏览器上次访问时间
程序员文章站
2022-03-15 09:47:21
...
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 记录上次访问时间
*/
public class RemServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码
response.setContentType("text/html;charset=utf-8");
PrintWriter w=response.getWriter();
//获取指定名称的cookie lastTime 当前时间
Cookie[] cookies=request.getCookies();
Cookie c=getCookieByName("lastTime",cookies);
//判断是否为空
if(c==null){
//cookie为空 提示:第一次访问
w.println("您是第一次访问,欢迎光临");
}else{
//cookie不为空 获取value 展示上一次访问的时间
String value=c.getValue();
long time=Long.parseLong(value);
Date date=new Date(time);
w.println("您上一次访问的时间:"+date.toLocaleString());
}
//将当前访问时间记录 创建cookie
c=new Cookie("lastTime",new Date().getTime()+"");
//持久化
c.setMaxAge(3600);
//设置路径
c.setPath(request.getContextPath()+"/");
//写回浏览器
response.addCookie(c);
}
private Cookie getCookieByName(String name, Cookie[] cookies) {
if(cookies!=null){
for(Cookie c:cookies){
if(name.equals(c.getName())){
return c;
}
}
}
return null;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}