如何在shiro发生UnauthorizedException与UnauthenticatedException等异常时返回json而不是跳转到错误页面

        当客户端的用户要请求一个需要该用户所不具有的role的接口时,往往会抛出未授权异常UnauthorizedException。

默认处理改异常的方式是在springmvc.xml中配置

org.springframework.web.servlet.handler.SimpleMappingExceptionResolver

如下:

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <!-- 错误异常转发jsp页面 -->
                <prop key="org.apache.shiro.authz.UnauthorizedException">/unauthorized.jsp</prop>
                <prop key="org.apache.shiro.authz.UnauthenticatedException">/unauthenticated.jsp</prop>
            </props>
        </property>
    </bean>

如果遇到这种情况不需要跳转别的页面而只需要返回一个结果给客户端,则需要自定义此处的

SimpleMappingExceptionResolver
主要是覆盖
doResolveException
 
@Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
                                              Object handler, Exception ex) {
        try {
            // Expose ModelAndView for chosen error view.
            BaseResult result = new BaseResult();
            if (ex instanceof UnauthorizedException) {
                result.setMsg(RespMSG.MSG_UNAUTHORIZED );
                result.setStatus(RespMSG.STATUS_UNAUTHORIZED);
            } else if (ex instanceof UnauthenticatedException) {
                result.setMsg(RespMSG.MSG_UNAUTHENTICATED );
                result.setStatus(RespMSG.STATUS_UNAUTHENTICATED);
            } else {
                result.setMsg(RespMSG.MSG_FAILLED );
                result.setStatus(RespMSG.STATUS_FAILLED);
            }
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(new Gson().toJson(result));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值