Cookie案例:获取上次登录时间
设计一个登录页面,输入账号和密码,点击登录,登录成功跳转到LoginServlet,执行相关逻辑。在当前会话进行第二次登录,登录成功后,显示出上次登录的时间。
- login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 关于 action="LoginServlet" 路径问题
LoginServlet的访问路径:http://localhost:8080/01_ServletTest/LoginServlet
login.html的访问路径:http://localhost:8080/01_ServletTest/login.html
故 action的路径可以写相对路径LoginServlet
-->
<form action="LoginServlet" method="post">
用户名:<input type="text" name="username">
密码:<input type="text" name="password">
<input type="submit" value="登录">
</form>
</body>
</html>
- LoginServlet.java
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置request对象使用UTF-8字符集对请求体中的内容进行解码
request.setCharacterEncoding("UTF-8");
//设置响应数据类型是html文本,并告诉浏览器使用UTF-8解码
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter writer = response.getWriter();
if("admin".equals(username)&&"1".equals(password)){
Cookie[] cookies = request.getCookies();
Cookie lastTimeCookie = findCookie( cookies, "lastTime");
if(lastTimeCookie==null){//第一次登录,没有相应的Cookie
Cookie cookie = new Cookie("lastTime", System.currentTimeMillis()+"");
//只有访问“/项目名/路径”下的的资源才会携带Cookie
cookie.setPath("/GetLastLoginTimeDemo/LoginServlet");
//如果关闭浏览器,再打开浏览器进入登录,登录成功后还可获取上次的登录时间,则要设置cookie时效。
//cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
writer.write("欢迎您!"+username);
}else{//第二及以后的登录
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String lastTime = simpleDateFormat.format(new Date(Long.parseLong(lastTimeCookie.getValue())));
writer.write("欢迎您!"+username+"\n上次登录时间:"+lastTime);
lastTimeCookie.setValue(System.currentTimeMillis()+"");
//只有访问“/项目名/路径”下的的资源才会携带Cookie,
lastTimeCookie.setPath("/GetLastLoginTimeDemo/LoginServlet");
//lastTimeCookie.setMaxAge(60*60*24);
response.addCookie(lastTimeCookie);
}
}else{
writer.write("登陆失败");
}
}
//根据name找到相应的cookie
private Cookie findCookie(Cookie[] cookies, String name) {
if(cookies!=null){
for (Cookie cookie : cookies) {
if(name.equals(cookie.getName())){
return cookie;
}
}
}
return null;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
在一次会话中多次访问:http://localhost:8080/GetLastLoginTimeDemo/login.html 登录成功后,跳转到LoginServlet,执行相关逻辑。
第一次访问
当前会话第二次访问
