jsp实现自动登录的代码

html页面

  <input type="checkbox" name="remember"  />自动登录

在controller判断是否勾选了自动登录

  public String login() { 
          HttpServletRequest request = ServletActionContext.getRequest();
          HttpServletResponse response = ServletActionContext.getResponse();
          //勾选了自动登录
          if(remember!=null) {
               Cookie c1 = new Cookie("userName", uUser.getUserName());  
               Cookie c2 = new Cookie("password", uUser.getPassword());  
               c1.setMaxAge(60*60*24*30);  
               c2.setMaxAge(60*60*24*30);//这里设置保存这条Cookie的时间  
               response.addCookie(c1);//添加Cookie  
               response.addCookie(c2);  
          }else {//未勾选自动登录
              Cookie cookies[] = request.getCookies(); 
              for (Cookie cookie : cookies) {
                  if(cookie.getName().equals("userName")) {
                      System.out.println("清除");
                      cookie.setMaxAge(0);
                      response.addCookie(cookie);//清除了
                  }
                  if(cookie.getName().equals("password")) {
                      cookie.setMaxAge(0);
                      response.addCookie(cookie);//清除了
                  }
              }
          }
          
          UIUser uiUser = uiUserService.login(uUser);
          if(uiUser == null) {
              //登录失败
              request.setAttribute("msg", "账号或者密码出错,请重新登录");
              return "login_fail";
          }
          request.getSession().setAttribute("bean", uiUser);
          return "login_success";
      }

如果勾选,就保存到session中。

下次访问首页,先调用cookie中的信息

  public String toIndex() {
          HttpServletRequest request = ServletActionContext.getRequest();
          HttpServletResponse response = ServletActionContext.getResponse();
          Cookie cookies[] = request.getCookies(); 
          for (Cookie cookie : cookies) {
              if(cookie.getName().equals("userName")) {
                  uUser = new UIUser();//是成员变量。
                  System.out.println(cookie.getValue());
                  uUser.setUserName(cookie.getValue());
              }
              if(cookie.getName().equals("password")) {
                  uUser.setPassword(cookie.getValue());
              }
          }
          if(uUser != null) {
              System.out.println("我进行了自动登录");
              request.getSession().setAttribute("bean", uUser);
          }
          return "index";
      }

展开阅读全文

没有更多推荐了,返回首页