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

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

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

org.springframework.web.servlet.handler.SimpleMappingExceptionResolver

如下:


        
            
                
                /unauthorized.jsp
                /unauthenticated.jsp
            
        
    

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

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;
    }


你可能感兴趣的:(孤陋寡闻)