cookie.html文件
首先我们需要使用h5代码设置一个简单的登录界面
使用get方法,跳转到CookieLogin.java文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>验证登录</title>
</head>
<body>
<form method="get" action="http://localhost:8080/myfrist/CookieLogin">
<input type="text" name = "username" ><br>
<input type="password" name = "password" >
<input type="submit">
</form>
</body>
</html>
CookieLogin.java文件
首先我们需要设置编码统一,在接收到在h5上的输入,实例化一个Cookie对象,然后判断该对象是否为空,为空肯定是第一次登录,我们使用简单的验证登录并且将登录成功的值保存在cookie中,当cookie中存在值的时候,则使用cookie登录
下面给出 doget() 代码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
// 获取html页面的用户名和密码
String user = request.getParameter("username");
String password = request.getParameter("password");
Cookie[] cookie = request.getCookies();
if (cookie != null) { // 缓存cookie登录,减轻服务器的负担,客户端验证
System.out.println("使用cookie的方式进行比较");
String dbUser = null;
String dbpass = null;
for (int i = 0; i < cookie.length; i++) {
if (cookie[i].getName().equals("username")) {
dbUser = cookie[i].getValue();
}
if (cookie[i].getName().equals("password")) {
dbpass = cookie[i].getValue();
}
}
System.out.println(dbpass + " " + dbUser);
if (user.equals(dbUser) && password.equals(dbpass)) {
System.out.println("使用cookie : 登录成功。");
}
} else { // 第一次肯定使用服务器验证
if (user.equals("admin") && password.equals("123456")) {
Cookie ck1 = new Cookie("username", "admin");
Cookie ck2 = new Cookie("password", "123456");
response.addCookie(ck1);
response.addCookie(ck2);
System.out.println("使用账号密码 : 登录成功");
}
}
}