Use jsp to simply implement cookie page login, and finally display the parameters on the form
First we should write our login interface
-
Username (text box)
-
Password (text box)
-
Remember me (button)
-
Login (button)
demo1_login.jsp:
<form action="demo1_cookie.jsp" method="post">
用户名:<input type="text" name="username" value="<%=username%>"/><br>
密码: <input type="text" name="pwd" value="<%=pwd%>"/><br>
<input type="radio" name="checkbox"> 记住我 <br>
<input type="submit" name="提交">
</form>
Then on another jsp page demo1_cookie.jsp accept the parameters and save them to Cookie
- First of all, we have to determine whether our remember me button is selected
- New Cookie is given to username, we can set the duration of cookie here (because it needs to be installed* so write it)
- new Cookie for pwd, we can also set the duration of the cookie here
- Save our cookies
<%
request.setCharacterEncoding("utf-8");
//判断是否勾选了 "记住我"
if (request.getParameter("checkbox")!=null){
Cookie username = new Cookie("username",request.getParameter("username"));
//保存一个小时
username.setMaxAge(60*60);
Cookie pwd = new Cookie("pwd",request.getParameter("pwd"));
//保存一个小时
pwd.setMaxAge(60*60);
//保存cookie
response.addCookie(username);
response.addCookie(pwd);
}
%>
<h1>登陆成功</h1>
Cookie cookie = new Cookie("","");
One party name, one value
String username = request.getParameter("username");
Cookie username = new Cookie("username",username);
So it’s abbreviated here because you want to install*
Cookie username = new Cookie("username",request.getParameter("username"));
This time we finished click remember me can save our cookie, no click cokkie will not save our cookie
How to be realistic in our form ? (Really confusing)
-
Traverse our cookies and get all our cookies
-
Get the name according to our getName method
-
Judging by name
-
When judging whether the value is empty
-
If you don't assign a value to null, it's done
demo1_login.jsp:
<%
String username=""; //用户名
String pwd=""; //密码
String c; //接受值
Cookie[] cookies = request.getCookies(); //拿到数据,才能遍历
for (Cookie cookie : cookies) {
c=cookie.getName(); //遍历 得到了所有cookie的参数
if (c.equals("username")){
//判断cookie的参数是否为空
if (cookie.getValue()!=null){
//赋值
username=cookie.getValue();
//控制台打印
System.out.println(username);
}
}else if(c.equals("pwd")){
//判断cookie的参数是否为空
if (cookie.getValue()!=null){
//赋值
pwd=cookie.getValue();
//控制台打印
System.out.println(pwd);
}
}
}
%>
Run screenshot:
First run:
After entering, click Remember me and submit
Log out and refresh to take a look at the form on our login page