自动登录
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190127140731129.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM3ODcxMDMz,size_16,color_FFFFFF,t_70)
- 自动登录的机制就是如同我右边写的那样,很简单的一个设定
- 下面看代码讲解
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可以查看官方文档