通过设置cookie来记录上次访问时间
public class cookie extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8");//保证输出到页面的不是乱码 Cookie[] cookies = req.getCookies(); if(cookies!=null){ resp.getWriter().write("你上次的访问时间是:"); for (int i = 0; i <cookies.length ; i++) { Cookie cookie=cookies[i];//通过遍历将cookie转化为字符串 if (cookie.getName().equals("lastLoginTime")){ long lastLoginTime = Long.parseLong(cookie.getValue()); Date date = new Date(lastLoginTime); resp.getWriter().write(date.toString()); } } }else { resp.getWriter().write("这是你第一次访问本站"); } Cookie cookie=new Cookie("lastLoginTime",System.currentTimeMillis()+"");//设置cookie名与cookie值 cookie.setMaxAge(24*60*60); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }