前台页面部分代码展示
<tr> <td colspan="2" style="text-align:center"> <input type="checkbox" name="remanberUserName" value="1" />记住用户名 <input type="checkbox" name="autoLogin" value="1" /> 自动登录 </td> </tr>
后台完整代码展示
@RequestMapping("/login.do") public String loginUser(User user,HttpSession session,HttpServletResponse response,HttpServletRequest request,String remanberUserName,String autoLogin) throws UnsupportedEncodingException { user=userService.findUser(user); session.setAttribute("user",user); if(user!=null){ if(user.getState()==1){ if("1".equals(autoLogin)){ Cookie cookieUserName = new Cookie("userName", URLEncoder.encode(user.getUsername(),"utf-8")); cookieUserName.setMaxAge(60*60*24*7); cookieUserName.setPath(request.getContextPath()+"/"); response.addCookie(cookieUserName); // session.setAttribute("username",user.getUsername());//判断记住用户名之后,把用户名放在session中,在login.jsp中显示 Cookie cookiePassword = new Cookie("password", URLEncoder.encode(user.getPassword(),"utf-8")); cookiePassword.setMaxAge(60*60*20*7); cookiePassword.setPath(request.getContextPath()+"/"); response.addCookie(cookiePassword); }else if("1".equals(remanberUserName)){ Cookie cookieUserName = new Cookie("userName", URLEncoder.encode(user.getUsername(),"utf-8")); cookieUserName.setMaxAge(60*60*24*7); cookieUserName.setPath(request.getContextPath()+"/"); response.addCookie(cookieUserName); // session.setAttribute("cookieUserName",cookieUserName); } return"/index.jsp"; }else{ request.setAttribute("fail","激活码未激活,请先激活"); return "/client/login.jsp"; } }else{ request.setAttribute("fail","尚未注册,请先注册"); return "/client/register.jsp"; } }
实现自动登陆的过程
@RequestMapping("/myAccount.do") public String myAccount(HttpSession session,Model model,HttpServletRequest request,User user) throws UnsupportedEncodingException { User session_user= (User) session.getAttribute("user"); //如果session中有数据,说明已经登陆过,可以进入 if(session_user!=null){ return "/client/myAccount.jsp"; }else{ //session中没有数据,则看有没有自动登陆,cookies中有无数据 Cookie[] cookies=request.getCookies(); for(Cookie cookie:cookies){ if("userName".equals(cookie.getName())){ String username= URLDecoder.decode(cookie.getValue(),"utf-8"); user.setUsername(username); } if ("password".equals(cookie.getName())){ String password= URLDecoder.decode(cookie.getValue(),"utf-8"); user.setPassword(password); } } //解码之后再去查找一遍,看和数据库中的信息是否一致,以防止中途数据修改。 user=userService.findUser(user); //如果能通过cookies中的数据,在数据库中存在,则说明已经自动登陆,可以进入 if(user!=null){ session.setAttribute("user",user); return "/client/myAccount.jsp"; }else{ model.addAttribute("fail","还未登录,请先登录账户"); return "/client/login.jsp"; } } }