【问题标题】:Error response in json format for Spring interceptorSpring拦截器的json格式的错误响应
【发布时间】:2012-04-14 07:24:05
【问题描述】:

我正在编写一个基于 REST 的 Web 服务。我需要以 JSON 格式返回所有响应。我有一个拦截器来验证我的身份验证参数。在身份验证失败的情况下,我必须以 JSON 格式返回错误响应。

目前我在做

response.setHeader("Content-Type","application/json"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "{\"error\":\"缺少认证参数\"}");

响应正文如下。

JBoss Web/2.1.3.GA - 错误报告

HTTP 状态 401 - {"error":"Missing Authentication Parameters"}

类型状态报告

消息 {"error":"缺少身份验证参数"}

说明此请求需要 HTTP 身份验证({"error":"Missing Authentication Parameters"})。

JBoss Web/2.1.3.GA

我只需要 JSON 字符串作为响应。请帮帮我。

【问题讨论】:

    标签: spring-mvc jboss iinterceptor


    【解决方案1】:

    您可能应该为此使用 spring-security。如果您想手动操作,在响应中使用sendError 的替代方法是使用spring MVC 的@ExceptionHandler 和content negotiation 来返回JSON。

    首先定义一个错误类*:

    public class Error {
        public message;
        public exception;
        public Error(String message, Exception ex) {
            this.message = message;
            this.exception = ex;
        }
    }
    

    还有一个例外:

    public class NotAuthenticatedException extends Exception {
        // ...
    }
    

    然后在您的控制器中,您在适当的时候抛出一个异常,用@ExceptionHandler 捕获它并返回一个包含Error 实例和相应错误代码的ResponseEntity。

    @Controller
    public class SimpleController {
        @RequestMapping(...)
        public String aMethod() {
            // ...
            throw new NotAuthenticatedException("Missing Authentication Parameters");
        }
    
        @ExceptionHandler(NotAuthenticatedException.class)
        public ResponseEntity<Error> handleNotAuthenticatedException(
                NotAuthenticatedException ex, 
                HttpServletRequest request) {
            return new ResponseEntity<Error>(
                new Error(ex.getMessage(), ex), 
                HttpStatus.UNAUTHORIZED
            );
        }
    }
    

    *使用 getter/setter 来取悦 java 约定之神

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      • 2016-03-03
      • 1970-01-01
      • 2016-02-02
      相关资源
      最近更新 更多