Java Shiro:处理注释引发的异常
我使用Shiro注释检查授权,如下所示:Java Shiro:处理注释引发的异常,java,spring,spring-mvc,shiro,Java,Spring,Spring Mvc,Shiro,我使用Shiro注释检查授权,如下所示: @RequiresPermissions("addresses:list") public ModelAndView getCarrierListPage() { return new ModelAndView("addressList", "viewData", viewData); } 我的问题是:如果用户没有注释所需的权限,将引发异常。我更愿意在出现异常时将用户重定向到不同的URL。我该怎么做 以下是我的shir
@RequiresPermissions("addresses:list")
public ModelAndView getCarrierListPage() {
return new ModelAndView("addressList", "viewData", viewData);
}
我的问题是:如果用户没有注释所需的权限,将引发异常。我更愿意在出现异常时将用户重定向到不同的URL。我该怎么做
以下是我的shiro过滤器配置:
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/showLoginPage"/>
<property name="filterChainDefinitions">
</property>
</bean>
看起来您正在使用Spring。我在SpringMVC中通过在控制器中提供ExceptionHandler来处理这个问题
@ExceptionHandler(TheSpecificException.class)
protected ModelAndView handleSpecificException(ApplicationException e, HttpServletRequest request)
{
// code to handle view/redirect here
}
如果没有Spring MVC,您也可以使用ExceptionMapper:
@Provider
@Component
public class GenericExceptionMapper implements ExceptionMapper<ShiroException> {
@Override
public Response toResponse(final ShiroException ex) {
return Response.status(ex instanceof UnauthenticatedException ? Response.Status.UNAUTHORIZED : Response.Status.FORBIDDEN)
.entity(ex.getMessage())
.type(MediaType.TEXT_PLAIN_TYPE)
.build();
}
}
@Provider
@组成部分
公共类GenericeExceptionMapper实现ExceptionMapper{
@凌驾
公众响应(最终ShiroException ex){
返回Response.status(未经验证的异常的实例?Response.status.UNAUTHORIZED:Response.status.FORBIDDEN)
.entity(例如getMessage())
.type(MediaType.TEXT\u PLAIN\u type)
.build();
}
}
在spring-servlet.xml中添加配置:
<beans:bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<beans:property name="exceptionMappings">
<beans:props>
<beans:prop key="org.apache.shiro.authz.UnauthorizedException">/403</beans:prop>
<beans:prop key="org.apache.shiro.authz.AuthorizationException">/login</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
/403
/登录