1、前台页面实现:
<input id="remember" name="remember" type="checkbox" value="remember-me">记住我
2、后台获取remember参数,判断它的值是否为remember-me,如果是,则:
if ("remember-me".equals(remember)) { rememberMe(username, password, resp); }
/** * 将用户名和密码存放到cookie中 * @param username * @param password * @param response */ private void rememberMe(String username,String password,HttpServletResponse response){ Cookie user = new Cookie("user",username+"-"+password); user.setMaxAge(1*60*60*24*7);//生命周期为一星期 response.addCookie(user); }
3、前台页面获取cookie中的user值时需要进行判断
<% if(request.getAttribute("user")==null){//如果user不为空,说明是第一次登录用户名或密码输错,后台设置的user值 String username = null; String password = null; Cookie[] cookies = request.getCookies(); for(int i=0;cookies!=null && i<cookies.length;i++){ if(cookies[i].getName().equals("user")){ username = cookies[i].getValue().split("-")[0]; password = cookies[i].getValue().split("-")[1]; } } if(username==null){ username = ""; } if(password==null){ password = ""; } pageContext.setAttribute("user", new User(username,password)); } %>