步骤分析
第一步. 服务器Servlet获得从客户浏览器带过来的所有的Cookie:
第二步.从所有的Cookie中查找指定名称的Cookie对象信息:
第三步.获取cookie保存的用户上次登录时间,判断是否是第一次访问:
如果是第一次访问网站:显示欢迎登录。
如果用户不是第一次访问望着那:显示欢迎 同时显示上次访问时间.
第四步.更新当前的时间,将当前系统时间以Cookie将时间回写到浏览器端.
@WebServlet(name = "RememberTimeServlet", urlPatterns = "/RememberTimeServlet")
public class RememberTimeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 模拟数据库 lisi 123
String name = request.getParameter("name");
String password = request.getParameter("password");
if ("lisi".equals(name)&&"123".equals(password)){
long currentTime = System.currentTimeMillis();
//登陆成功,根据cookie判断是是不是第一次登陆
Cookie[] cookies = request.getCookies();
Cookie cookie = findCookieByName("lasttime",cookies);
if (null!=cookie) {
//存在lasttime 获取对应的cookie值 String类型的毫秒数
String lasttime = cookie.getValue();
// 浏览器 找到保存时间cookie 第二次登录 更新cookie时间值 显示 登录上次时间
cookie.setPath("/");
cookie.setMaxAge(3600*24*30);
// 13788821312832832更新cookie值
cookie.setValue(String.valueOf(currentTime));
//重设
response.addCookie(cookie);
// Timestamp(long currentTime).toString -> yyyy-mm-dd hh:mm:ss.fffffffff 格式的 String 对象
// 2018-07-07 21:31:14.592
response.getWriter().print("恭喜您登陆成功,上次登陆的时间为:"+new Timestamp(Long.valueOf(lasttime)).toString());
Timestamp timestamp = new Timestamp(Long.valueOf(lasttime));
//timestamp = 2018-07-07 21:37:35.188
System.out.println("timestamp = " + timestamp);
}
else {
// 第一次登陆不存在lasttime 那就设置一个时间戳的cookie
//设置字符串类型的时间毫秒值
Cookie lasttime = new Cookie("lasttime", String.valueOf(currentTime));
lasttime.setMaxAge(3600*24*30);
lasttime.setPath("/");
response.addCookie(lasttime);
response.getWriter().print("恭喜您登陆成功");
}
}
else {
response.getWriter().print("账号或者密码错误登陆失败");
}
}
//遍历判断是否有cookieName为lasttime的cookie
private Cookie findCookieByName(String lasttime, Cookie[] cookies) {
for (Cookie cookie : cookies) {
if (lasttime.equals(cookie.getName())){
return cookie;
}
}
return null;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
doPost(request, response);
}
}
Cookie案例-记住用户上次登录时间
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。