Shiro實現登陸登出操作(十)

步驟:

1:重寫LoginController類,實現登錄操作

@Controller
public class LoginController {
    @RequestMapping("/login")
    public String login(Model model, HttpServletRequest req) throws  Exception{
        //如果登陸失敗從request中獲取認證異常信息,shiroLoginFailure就是shiro異常類的全限定名
        String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
        //根據shiro返回的異常類路徑判斷,拋出指定異常信息
        if(exceptionClassName!=null){
            if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
                //最終會拋給異常處理器
                model.addAttribute("errorMsg", "賬號不存在");
            } else if (IncorrectCredentialsException.class.getName().equals(
                    exceptionClassName)) {
                model.addAttribute("errorMsg", "用戶名/密碼錯誤");
            } else {
                //最終在異常處理器生成未知錯誤.
                model.addAttribute("errorMsg", "其他異常信息");
            }
        }
        //此方法不處理登陸成功(認證成功),shiro認證成功會自動跳轉到上一個請求路徑
        //登陸失敗還到login頁面
        return "forward:/login.jsp";
    }
}

2:重寫UserRealm中的doGetAuthenticationInfo, 注意需要注入IUserDAO對象操作數據庫

public class UserRealm extends AuthorizingRealm {

    @Setter
    private IUserDAO userDAO;
    //認證操作
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //從token中獲取登錄的用戶名, 查詢數據庫返回用戶信息
        String username = (String) token.getPrincipal();
        User user = userDAO.getUserByUsername(username);

        if(user == null){
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, 
                user.getPassword(),
                ByteSource.Util.bytes(user.getUsername()),
                getName());
        return info;
    }

    @Override
    public String getName() {
        return "UserRealm";
    }

    //授權操作
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
}

3:先請求/main, 再登錄,登錄成功直接跳轉到main請求路徑

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章