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;
}
}