使用Spring时,如何将默认的REST验证响应从HTML更改为JSON?

时间:2016-08-12 20:34:10

标签: java json spring rest validation

我使用的标准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:

enter image description here

如何将此响应更改为JSON?

2 个答案:

答案 0 :(得分:0)

验证有效时,会抛出异常。然后服务器会找到代表服务器响应的 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是你的自定义回复。

答案 1 :(得分:0)

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

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