效果展示
首页 login.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<%
Cookie[] cookies = request.getCookies();
Cookie remember = null;
if (cookies != null && cookies.length > 0) {
for (Cookie c : cookies) {
if (c.getName().equals("remember")) {
remember = c;
}
}
}
%>
<body>
<form action="/Web1.1/CookieEServlet" method="post">
用户名:<input type="text" name="name" value="<%=remember==null?"":remember.getValue() %>"/><br/>
密码:<input type="password" name="password" /><br/>
记住用户名(一周):<input type="checkbox" name="remember" value="yes" <%=remember==null?"":"checked" %>/><br/>
<input type="submit" value="登录"/><br/>
</form>
</body>
</html>
记住用户名Servlet CookieEServlet
package Cookie;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CookieEServlet
*/
@WebServlet("/CookieEServlet")
public class CookieEServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CookieEServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1 获得用户名
String name = request.getParameter("name");
String remember = request.getParameter("remember");
//新建cookie
Cookie cookie = new Cookie("remember", name);
//2 判断remeber
if (remember != null && remember.equals("yes")) {
// "yes" 勾选了 ==> 设置有效时间为 一周
cookie.setMaxAge(60*60*24*7);
} else {
// null 没勾选 ==> 设置cookie的有效时间为0
cookie.setMaxAge(0);
}
//3 将cookie添加到response
response.addCookie(cookie);
//4 跳转到成功页面
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}