shiro单用登录(同一时刻只能登录一个账号)

(一)applicationContext-shiro.xml



    
    


        
        
        
        
        
        
    



    
    
    
        
        
        
    

(二)controller

@RequestMapping(value = "/login",method = RequestMethod.POST)
   @ResponseBody
   public JsonResult login(String username, String password,String code,HttpServletRequest request) {
       String random = (String)request.getSession().getAttribute("RANDOMCODE_IN_SESSION");
       boolean same = RandomCodeUtils.isSame(random, code);
       if (!same) {
           //验证码不同
           return new JsonResult(false,"验证码不正确");
       }

       Collection sessions = sessionDAO.getActiveSessions();
       for (Session session : sessions) {

           System.out.println("登录用户" + session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY));
           if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) != null) {
               return new JsonResult(false,"该用户已经登录");
           }
       }

       //拿到当前用户
       Subject subject = SecurityUtils.getSubject();
       //判断是否登录
       if (!subject.isAuthenticated()) {
           try {
               UsernamePasswordToken token = new UsernamePasswordToken(username,password);
               subject.login(token);
           } catch (UnknownAccountException e) {
               e.printStackTrace();
               System.err.println("用户名不正确");
               return new JsonResult(false,"用户名或密码错误");
           } catch (IncorrectCredentialsException e) {
               e.printStackTrace();
               System.err.println("密码不正确");
               return new JsonResult(false,"用户名或密码错误");
           } catch (AuthenticationException e) {
               e.printStackTrace();
               return new JsonResult(false,"未知错误");
           }
       }
       //将当前登录用户放入session
       UserContext.setUser();
       return new JsonResult();
   }

你可能感兴趣的:(框架)