package it.com.cookie;
import java.io.IOException;
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 LastTimeCServlet extends HttpServlet {
//显示用户上次访问时间
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//检测当前访问中有没有lasttime cookie
Cookie cs[]=request.getCookies();
Cookie findC=null;
if(cs!=null)
{
for(Cookie c:cs)
{
if("lasttime".equals(c.getName()))
{
findC=c;
break;
}
}
}
if(findC==null)
{
//如果没有,则打印 您是第一次访问网站
response.getWriter().write("您是第一次访问本网站!");
}
else
{
//如果有,则获取其中信息,打印 您上次访问的时间是xxxx
Long time=Long.parseLong(findC.getValue());
Date date=new Date(time);
response.getWriter().write("上次访问时间为:"+date.toLocaleString());
}
//发送cookie保存最新时间
Cookie lasttimeC=new Cookie("lasttime",new Date().getTime()+"");
lasttimeC.setMaxAge(3600*24*30);
lasttimeC.setPath(request.getContextPath());
response.addCookie(lasttimeC);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Cookie应用:显示用户上次访问时间
最新推荐文章于 2023-03-17 16:06:37 发布