jsp页面写登录
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="http://localhost:8080/13_Cookie_Session/loginServlet" method="get">
用户名:<input type="text" name="username" value="${cookie.username.value}"><br>
密码:<input type="password" name="password" value="${cookie.password.value}"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
其中http://localhost:8080/13_Cookie_Session/loginServlet地址会触发Servlet层的LoginServlet里的程序:value存放输入的用户名与密码
LoginServlet的程序
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
if("1024ytt".equals(username) && "123456".equals(password)){
//登陆成功
Cookie cookie1=new Cookie("username",username);//创建cookie对象
Cookie cookie2=new Cookie("password",password);//创建cookie对象
cookie1.setMaxAge(60*60*7*24);//设置cookie过期时间
cookie2.setMaxAge(60*60*7*24);//设置cookie过期时间
resp.addCookie(cookie1);//通过客户端保存cookie
resp.addCookie(cookie2);//通过客户端保存cookie
System.out.println("登陆成功");
}else {
//登录失败
System.out.println("登录失败");
}
}
}
如果输入的密码,用户名正确,点击提交,客户端就保存了用户名和密码的cookie;控制台显示登陆成功,然后下次再打开页面的时候就不用输入用户名和密码了;