Cookies实现的自动登录

自动登录

在这里插入图片描述

  • 自动登录的机制就是如同我右边写的那样,很简单的一个设定
  • 下面看代码讲解

login.jsp

 <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	
	<% Cookie[] cookieList=request.getCookies();
	if(cookieList==null)
		cookieList=null;
				for(Cookie cookie:cookieList){
					if(cookie.getName().equals("sure")&&cookie.getValue().equals("success")){
						Date date = new Date();
				        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd--hh:mm:ss");
				        String currentTime = format.format(date);
						Cookie cookie2=new Cookie("lasttime",currentTime);
						cookie2.setMaxAge(40);
						response.addCookie(cookie2);
						response.sendRedirect("suss.jsp");
					}
						
				}
				%>
	
	<form action="Login" method="get">
		姓名:<input type="text" name="id">
		密码:<input type="text" name="pwd">
		<input type="submit" value="登录">
	</form>
	
</body>
</html>
  • 代码其实看起来不难,首先最开始在jsp页面写JAVA代码,读取cookies
  • 判断cookies是否有自动登录的凭证
  • 如果有就跳转,并且发送一个登录时间
  • 如果没有就运行下面的表单,跳转到Sevlet

Login

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String id=request.getParameter("id");
		String pwd=request.getParameter("pwd");
		if(id.equals("admin")&&pwd.equals("123")) {
			Cookie cookie=new Cookie("sure", "success");
			cookie.setMaxAge(20);
			response.addCookie(cookie);
			response.sendRedirect("suss.jsp");
		}else {
			response.sendRedirect("login.jsp");
		}
	}
  • 这里代码和上述代码差不多,都是先判断登录是否成功,如果成功保留cookies,然后跳转
  • 这里有个注意的,如果登录时间没有设定就是30分钟,一但设定不可更改哦

suss.jsp

<body>
	登录成功:<% 
	
	
	Cookie[] cookieList=request.getCookies();
	if(cookieList==null)
		cookieList=null;
				for(Cookie cookie1:cookieList){
					if(cookie1.getName().equals("lasttime"))
						out.write(cookie1.getValue());
				}
				%>
</body>
  • 这里就只是一个读取最后登录时间的代码,很简单

总结

  • Cookies一个客户端有无数个,但是一个Cookies只能存放一对键值对
  • 同一个页面可以获取该cookie,也可以发送cookies,但是注意,获取的只是获取的上次的请求,不是本次
  • cookies的时间一但设定就不能更改
  • cookies是通过响应发送给客户端的,然后通过请求获取,获取的是一个数组
  • Session的本质也是一个cookies,所以有一个ID,可以找到
  • cookies的具体一些api可以查看官方文档
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值