一、登录时勾选自动登录,后台将用户账号和密码存放进Cookie中
Cookie user_username = new Cookie("username", user.getUsername());//创建Cookie对象
user_username.setPath(request.getContextPath() + "/");//设置Cookie使用范围,这里表示在当前Web项目中使用
user_username.setMaxAge(60 * 60 * 24 * 7);//设置Cookie有效期,这里表示Cookie一个星期后过期,注意:这里单位是秒!不是毫秒
Cookie user_password = new Cookie("password", user.getPassword());
user_password.setPath(request.getContextPath() + "/");
user_password.setMaxAge(60 * 60 * 24 * 7);
response.addCookie(user_username);//添加Cookie
response.addCookie(user_password);
二、JSP页面body标签前使用JSP代码标签写Java代码
<%
Cookie[] cookies=request.getCookies();
String username=null;
String password=null;
for(Cookie c:cookies){
if(c.getName().equals("username")){
username=c.getValue();
}else if(c.getName().equals("password")){
password=c.getValue();
}
}
if(username!=null && password!=null && !"".equals(username) && !"".equals(password)){
response.sendRedirect(request.getContextPath()+"/UserServlet?operator=cookieLogin&username="+username+"&password="+password);
}
%>
当Cookie中存放用户账号和密码时,重定向至服务器实现登录请求,实现自动登录功能