【问题标题】:How can I change the default REST validation response from HTML to JSON when using Spring?使用 Spring 时,如何将默认 REST 验证响应从 HTML 更改为 JSON?
【发布时间】:2016-08-12 20:34:09
【问题描述】:

我正在使用一个非常标准的 REST 请求,如下所示:

@RestController
@RequestMapping("/rest/xyz")
public class SomeApiService {

    @RequestMapping(value = "/doSomething", method = RequestMethod.POST)
    public SomeSharedObject doSomething(@Validated @RequestBody SomeSharedObject so) {
        ...
        return so;
    }

该共享对象是具有字段级验证的 POJO:

@NotNull(message = "error.fieldA.notNull")
private String fieldA;

验证有效。如果我为 fieldA 提供值,则请求有效。如果我省略 fieldA 的值,我会收到验证错误。问题是这个验证错误是 HTML:

如何将此响应更改为 JSON?

【问题讨论】:

标签: java json spring rest validation


【解决方案1】:

当验证工作时,会抛出异常。然后服务器会找到代表服务器响应的 httpstatus(404,400,500 等) 的页面。因此您需要捕获异常并自定义您自己的响应。作为 springmvc ,这是我的建议。

1.配置您的 applicationContext.xml

    <context:component-scan base-package="cn.org.citycloud">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation"
                                expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>

好吧,只关注 ControllerAdvice

2.然后自定义你自己的ExceptionHandler。这里是示例代码。

@ControllerAdvice
public class ApiExceptionHandler {
    @ExceptionHandler(BusinessErrorException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorResponse handleBusinessErrorException(BusinessErrorException ex) {
        return new ErrorResponse(ex.getCode(), ex.getMessage());
    }
}

这里,HttpStatus.BAD_REQUEST 代表 400.ErrorResponse 是您的自定义响应。

【讨论】:

    【解决方案2】:

    在 Spring 中,您可以使用 ResponseEntity 类:

    @RequestMapping(value = "/doSomething", method = RequestMethod.POST)
    public ResponseEntity<SomeSharedObject> doSomething(@Validated @RequestBody SomeSharedObject so) {
        ...
        return new ResponseEntity<>(so, HttpStatus.OK);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 2017-11-18
      • 2016-09-04
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 2018-02-23
      • 2018-09-10
      相关资源
      最近更新 更多