我们在一个网站注册账号以后会有提示下次是否自动登录,如果我们选择下次自动登录,那么服务器端就会把你的账号和密码保存在Cookie中,并返回给客户端。下次在登录的时候Http协议会带上你的Cookie中的内容去验证信息,因为服务器中已经存储你的信息,下次登录就会通过验证,并直接进入你的主页。
下面是登录的代码:

public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException
{
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException
{
String username=request.getParameter("username");
String password=request.getParameter("password");
String savetime=request.getParameter("saveTime");

if(CheckLogin.login(username, password))
{

if(null!=savetime)
{
int saveTime=Integer.parseInt(savetime);//这里接受的表单值为天来计算的
int seconds=saveTime*24*60*60;
Cookie cookie = new Cookie("user", username+"=="+password);
cookie.setMaxAge(seconds);
response.addCookie(cookie);
}
request.setAttribute("username",username);
request.getRequestDispatcher("/main126.jsp").forward(request,response);
}

else
{
request.getRequestDispatcher("/failure.jsp").forward(request,response);
}
}
}
验证代码:

public class IndexFilter implements Filter
{

public void destroy()
{
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,

FilterChain arg2) throws IOException, ServletException
{
System.out.println("every request pass here haha");
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
Cookie[] cookies = request.getCookies();
String[] cooks = null;
String username = null;
String password = null;

if (cookies != null)
{

for (Cookie coo : cookies)
{
String aa = coo.getValue();
cooks = aa.split("==");

if (cooks.length == 2)
{
username = cooks[0];
password = cooks[1];
}
}
}
System.out.println("cookie username | " + username);
System.out.println("cookie password | " + password);

if (CheckLogin.login(username, password))
{
System.err.println("check successfully cookie data ");
request.getSession().setAttribute("username",username);
request.getRequestDispatcher("/main126.jsp").forward(request, response);
}

else
{
arg2.doFilter(request,response );
}
}

public void init(FilterConfig arg0) throws ServletException
{
// TODO Auto-generated method stub
}
}

public class CheckLogin
{


public static boolean login(String username, String password)
{

if ("admin".equals(username) && "123456".equals(password))
{
return true;
}

else
{
return false;
}
}
}
我们看看没有登录的结果:
我们再看看已经登录的结果: