使用Cookie完成账号密码登录验证

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("使用账号密码   :   登录成功");
		}
	}
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Modify_QmQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值