Cookie获取上次登录时间

一、Cookie获取上次登录时间#

  主要是由一个index.html的前端浏览器代码写出登录需要的用户密码提交按钮,然后通过servlet提交到另外一个Demo03程序(新建CookieUtil完成所有cookies和所要的cookie对比的功能)之中。

  由Demo03先去写由request得到用户名和密码然后if判断用户名是否正确:
  1.如果不正确弹出密码错误,由于输出中文需要提前写好response.setContenType那行文字编码。
  2.如果是正确进入之后获取所有的cookies值,调用方法判断是不是所要的cookie,
    2.1如果是null那么就是没有cookie需要完成的是设置一个名为last,值为当前时间的cookie,然后将它添加到客户端,输出语句。
    2.2如果cookie存在,那就只需要输出上一次最近的访问时间。

客户端用于写按钮的index.html代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Demo03">
账号: <input type="text" name="username"/><br>
密码: <input type="text" name="password"/><br>
<input type="submit" value="登录"/><br>
</form>
</body>
</html>

用于匹配判断是不是存在有的CookieUtil的类代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class CookieUtil {
public static Cookie findCookie(Cookie[] cookies,String name) {
if(cookies !=null)
{
for (Cookie cookie :cookies)
{
if(name.equals(cookie.getName())) { //从一个cookie数组中找到具体的对象
return cookie;
}
}
}
return null;
}
}

Demo03主要类代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Demo03 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8"); //解决中文乱码问题
String username=request.getParameter("username");
String password=request.getParameter("password");

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

//获取所有的cookie值
Cookie[] cookies = request.getCookies();

Cookie cookie = CookieUtil.findCookie(cookies, "last"); //在匹配的类里面去放数组找last配对的值

if(cookie==null) //第一次登录 --设置一个cookie--然后设置有效期--添加到客户端
{
Cookie c=new Cookie("last",System.currentTimeMillis()+""); //因为一会在数组找last那个 value写当前时间戳
c.setMaxAge(60*60); //设置cookie有效值(1小时)
response.addCookie(c);
response.getWriter().write("欢迎您"+username); //使用字符流 但是要改中文的问题
}
else //第二次登陆 已经有了cookie --输出cookie值
{
//1.取之前的cookie值
Long lastVisitTime = Long.parseLong(cookie.getValue()); //转成long型
//2.输出到界面
response.getWriter().write("欢迎您"+username+",上次来访时间是:"+new Date(lastVisitTime)); //使用字符流 但是要改中文的问题
//3.重置时间
cookie.setValue(System.currentTimeMillis()+""); //使用时间戳
response.addCookie(cookie);
}

}

else
{
response.getWriter().write("登陆失败!请退出重新输入!"); //使用字符流 但是要改中文的问题
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

用户admin和密码123第一次进入是欢迎界面,第二次界面为弹出上次登录时间:


×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. 一、Cookie获取上次登录时间#
,