Cookie 最后登录时间

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//解决中文乱码
		response.setContentType("text/html; charset=UTF-8");
		//获取username和password
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		//判断登陆是否成功
		if("wanglaowu".equals(username)&&"123456".equals(password)) {
			//获取cookies
			Cookie[] cookies = request.getCookies();
			//调用方法 找到所需要的cookie,判断是否为空
			Cookie cookie = CookieUtil.findCookie(cookies, "last");
			if(cookie==null) {
				//如果为空则为第一次登陆,添加cookie
				Cookie c = new Cookie("last",System.currentTimeMillis()+"");	//写入当前时间
				c.setMaxAge(60*60);		//cookie有效期
				response.addCookie(c);	//添加
				response.getWriter().write("登陆成功");
			}else {
				long lastVisitTime =Long.parseLong(cookie.getValue()) ;	//获取cookie里的value
				response.getWriter().write("登陆成功,上次登录时间为"+new Date(lastVisitTime));
				cookie.setValue(System.currentTimeMillis()+"");    //更新登陆时间,将当前时间写入
				response.addCookie(cookie);     //添加
			}
			
			
		}else {
			response.getWriter().write("登陆失败");
		}
	}

public class CookieUtil {
	public static Cookie findCookie(Cookie[] cookies,String name) {
		if(cookies!=null) {
		for (Cookie cookie : cookies) {
			if(name.equals(cookie.getName())){
				return cookie;
			}
		}
		}
		return null;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值