login.jsp
<%--
Created by IntelliJ IDEA.
User: xfj
Date: 2021/5/29
Time: 15:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%!
String uname;
%>
<%
Cookie[] cookies=request.getCookies();
for (Cookie cookie:cookies){
if (cookie.getName().equals("uname")){
uname=cookie.getValue();
}
}
%>
<form action="check.jsp" method="post" >
用户名:<input type="text" name="uname" value="<%=(uname==null? "":uname)%>"><br>
密码:<input type="password" name="upwd"><br>
<input type="submit" value="登录" ><br>
</form>
</body>
</html>
check.jsp
<%--
Created by IntelliJ IDEA.
User: xfj
Date: 2021/5/29
Time: 15:45
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String name=request.getParameter("uname");
String pwd=request.getParameter("upwd");
Cookie cookie = new Cookie("uname",name);
response.addCookie(cookie);
response.sendRedirect("A.jsp");
%>
</body>
</html>
A.jsp
<%--
Created by IntelliJ IDEA.
User: xfj
Date: 2021/5/31
Time: 10:22
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Cookie[] cookies=request.getCookies();
for (Cookie cookie:cookies){
out.print(cookie.getName()+"<br>"+"--"+cookie.getValue()+"<br>");
}
%>
</body>
</html>
此例子为了实现下次访问网页时,cookie依然存在(用户名),在这个例子中,在用户zs登录过之后,下次访问时依然还有用户名zs。