Cookie获取上次登陆时间

显示最近访问的时间。

1. 判断账号是否正确

2. 如果正确,则获取cookie。 但是得到的cookie是一个数组, 我们要从数组里面找到我们想要的对象。

3. 如果找到的对象为空,表明是第一次登录。那么要添加cookie

4. 如果找到的对象不为空, 表明不是第一次登录。 

response.setContentType("text/html;charset=UTF-8");

String name = request.getParameter("username");
String password = request.getParameter("password");

if ("admin".equals(name) && "123".equals(password)) {

	//获取cookie  last--name
	Cookie[] cookies = request.getCookies();
			
	//从数组中找到我们想要的cookie
	Cookie cookie = CookieUtil.findCookie(cookies, "last");

	//第一次登陆,没有cookie
	if (cookie == null) {
		Cookie c = new Cookie("last",System.currentTimeMillis()+"");
		c.setMaxAge(60*60);//一个小时
		response.addCookie(c);
				
		response.getWriter().write("登陆成功!欢迎您" + name);
	} else {
		//有cookie,去以前的cookie第二次登陆
		long lastTime = Long.parseLong(cookie.getValue());
			
		//输出到界面
		response.getWriter().write("欢迎您:" + name + "上次登录时间是:" + new Date(lastTime));
				
		//重置登陆时间
		cookie.setValue(System.currentTimeMillis()+"");
		response.addCookie(cookie);
	}
} else {
	response.getWriter().write("登陆失败!");
}

从Cookie数组中找到目标cookie对象代码如下: 

/*
 * 从cookies数组中找到具体我们想要的cookie对象
 */
public static Cookie findCookie(Cookie[] cookies, String name) {

	if (cookies != null) {
		for (Cookie cookie : cookies) {
			if ((cookie.getName()).equals(name)) {
				return cookie;
			}
		}
	}

	return null;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值