在使用注解的方式来验证角色和权限时,如:
//注解验角色和权限
@RequiresRoles("admin")
@RequiresPermissions("add")
@RequestMapping(value="/index",produces = "application/json;charset=UTF-8")
public String index() {
return "you get it!";
}
可以通过几种方法来获取异常抛出的情况,即没有权限被阻挡的情况。
一、添加error.html
当权限认证不通过时,默认会跳转到error.html,所以只要创建一个error.html,就可以实现正常跳转了。
二、在shiro的配置文件中配置simpleMappingExceptionResolver
我的shiro的配置文件命名为shiroConfig.java,在里面添加这样一部分内容。可以实现自定义异常抛出的界面文件命名。
/**
* shiro中如果使用注释来注入角色和权限的话,无法抛出UnauthorizedException的异常
* 需要添加以下内容,当出现异常时,跳转至UnauthenticatedException.html。
* 下面部分也可以不添加,就会跳转至默认的error.html界面。
* 添加了下面的内容,可以指定跳转的页面。
* @return
*/
@Bean
public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
Properties properties = new Properties();
//未授权的网页跳转至error.html
properties.setProperty("org.apache.shiro.authz.UnauthorizedException", "/UnauthenticatedException");
resolver.setExceptionMappings(properties);
return resolver;
}
三、新建一个统一异常处理类HandlerExceptionResolver
这部分是别人的做法,我没试过,为了文章的完整性,也写在这里了。可以实现自定义异常抛出的界面文件命名。
新建一个异常处理类。
public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
if (e instanceof UnauthorizedException) {
ModelAndView mv = new ModelAndView("/error");
return mv;
}
return null;
}
}
在启动界面中注册这个异常处理类。
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
// 注册统一异常处理bean
@Bean
public MyExceptionResolver myExceptionResolver() {
return new MyExceptionResolver();
}
}