实现功能:
登录系统
用户第一次登录,要显示,欢迎这是您第一次访问
下次登陆时示上次登录的时间
前端登录页面
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/HomewprkDemo01" method="post">
<label for="username">用户名:<input id="username" name="username" type="text"></label><br>
<label for="pwd">密码:<input id="pwd" name="password" type="password"></label><br>
<button type="submit">提交</button>
</form>
</body>
</html>
后端获取浏览器cookie(这里主要展示对cookie的操作,就不对前端输入数据的判断)
Cookie[] cookies = request.getCookies();
对cookie进行遍历,然后对获取的cookie做判断是否存在已经登录的cookie,如果有就对cookie进行遍历,将cookie的值作为会话的作用域在前端展示,并添加新的时间作为新的cookie值,然后通过重定向跳转到时间页面
for (Cookie cookie : cookies) {
String name = cookie.getName();
if (name.equals("time")){
for (Cookie cook : cookies) {
String value = cookie.getValue();
String decode = URLDecoder.decode(value);
ServletContext servletContext = request.getServletContext();
servletContext.setAttribute("time",decode);
}
Date date = new Date();
String s = date.toString();
String encode = URLEncoder.encode(s,"utf-8");
Cookie cook = new Cookie("time",encode);
response.addCookie(cook);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/time.jsp");
requestDispatcher.forward(request,response);
}
}
如果没有cookie值,表名是第一次登录,于是跳转到登录成功页面,并赋给cookie值,证明已经登录过,这段代码不能写在cookie的循环里,因为浏览器有很多自带的cookie值,如果写在循环里,else会一直执行这段代码
Date date = new Date();
String s = date.toString();
String encode = URLEncoder.encode(s,"utf-8");
Cookie cook = new Cookie("time",encode);
response.addCookie(cook);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/welcome.jsp");
requestDispatcher.forward(request,response);