客户端记录:cookie
服务器记录:session
小例:登录时记住密码
基本结构如图
Loginaction.java
package com.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class Loginaction extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username=request.getParameter("username");
String password=request.getParameter("userpass");
String flag=request.getParameter("flag");
String path="/error.jsp";
if("admin".equals(username)&&"123".equals(password)){
if(flag!=null&&flag.equals("select")){
Cookie c1=new Cookie("uname",username);
Cookie c2=new Cookie("upass",password);
//设置有效时间,单位毫秒
c1.setMaxAge(60*60*60*24);
c1.setMaxAge(60*60*60*24);
response.addCookie(c1);
response.addCookie(c2);
}else{
Cookie c1=new Cookie("uname",username);
Cookie c2=new Cookie("upass",password);
c1.setMaxAge(0);
c1.setMaxAge(0);
response.addCookie(c1);
response.addCookie(c2);
}
path="/index.jsp";
}
request.getRequestDispatcher(path).forward(request,response); }
}
***********************************************************************************************************************************************************
index.xml
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>cookie</title>
</head>
<body>
<form action="login.do"method="post" >
用户:<input type="text" name="username" value="${cookie.aname.value }"><br/>
密码:<input type="password" name="userpass" value="${cookie.apsss.value}" ><br/>
记住密码:<input type="checkbox" name="flag" value="select" ${cookie.aname.value}!=null ? 'checked':''/>
<%-- ? : 表达式
不为空的话就是被选上,为空就是没被选上,不记住密码
--%>
<br/>
<input type="submit" value="登录">
</form>
</body>
</html>