步骤:
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请求路径