服务器与客户端存储
Session和Cookie对象:
尝试完成七天免登录的功能:
login.jsp:登录界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<%--
表单(form)
action:表单提交的地址
method:表单提交的方式
* get(默认) 显示在地址栏上,数据长度有限制
* post 不显示在地址栏上,且数据长度没有限制
必须携带name属性,不然接收不到数据
--%>
<%
String username="";
String password="";
if(request.getCookies()!=null){//判断是否有Cookie,一般第一次登陆是没有Cookie的,没有非空判断会报错
for(Cookie cookie : request.getCookies()){//遍历Cookie数组
if(cookie.getName().equals("username"))//如果有账号,则赋值给账号输入框
username=cookie.getValue();
if(cookie.getName().equals("password"))//如果有密码,则赋值给密码输入框
password=cookie.getValue();
}
}
%>
<form action="doLogin.jsp" method="post">
<p>
<input value="<%=username %>" type="text" name="username" placeholder="请输入用户名" required>
</p>
<p>
<input value="<%=password %>" type="password" name="password" placeholder="请输入密码" required>
</p>
<p>
<button>登录</button>
<button>注册</button>
</p>
</form>
</body>
</html>
dologin.jsp:处理登录请求
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- 处理登录请求 -->
<%
String username=request.getParameter("username");//拿到登陆请求发过来的账号
String password=request.getParameter("password");//拿到登陆请求发过来的密码
Cookie cookie_username=new Cookie("username",username);//新建一个Cookie用来装账号
cookie_username.setMaxAge(60*60*24*7);//设置七天的存活时间,时间单位为S(秒)
Cookie cookie_password=new Cookie("password",password);//新建一个Cookie用来装密码
cookie_password.setMaxAge(60*60*24*7);//设置七天的存活时间
//将Cookie存到前台去,完成七天免登陆
response.addCookie(cookie_username);
response.addCookie(cookie_password);
//前往主页
response.sendRedirect("home.jsp");
%>
如何查看Cookie:
English: 右键检查,点击Application,找到Cookie
中文: 右键检查,点击应用,找到Cookie