Cookie是实现记住用户名实例
记住用户名的功能,登入成功后,给响应消息头添加用户名的Cookie信息,在登入页面时,加载cookie信息,通过cookie获取用户名信息,写在输入框中。
SimpleLoginServlet(简单的登入页面):
@WebServlet({ "/SimpleLoginServlet", "/simple/login" })
public class SimpleLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SimpleLoginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String value = "";
String check="checked='checked'";
Cookie[] cookies = request.getCookies();
if(cookies!=null ){
for (int i = 0;i < cookies.length; i++) {
if ("username".equals(cookies[i].getName())) {
value = cookies[i].getValue();
System.out.println(value);
}
}
value = "value='"+value+"'";
}
out.print("<form action='"+request.getContextPath()+"/simple/login/success' method='post'>");
out.print("用户名<input type='text' name='username' "+value+"/><br/>");
out.print("密码<input type='password' name='password'/><br/>");
out.print("<input type='checkbox' name='check' "+check+"/>记住用户名<br/>");
out.print("<input type='submit' value='登入'/><br/>");
out.print("</form>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
LoginSuccessServlet(登入成功页面)
@WebServlet({ "/LoginSuccessServlet", "/simple/login/success" })
public class LoginSuccessServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginSuccessServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
String check = request.getParameter("check");
Cookie cookie = new Cookie("username", username);
cookie.setPath(request.getContextPath());
if ("tuhao".equals(username) && "123456".equals(password)) {
//check部位null,表示记住用户名了
if(check!=null){
cookie.setMaxAge(5*60);
response.addCookie(cookie);
out.println("登入成功,已经记住用户名");
}else {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("不记住用户名");
}
}else {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("清除用户名");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}