簡體   English   中英

使用Spring時,如何將默認的REST驗證響應從HTML更改為JSON?

[英]How can I change the default REST validation response from HTML to JSON when using Spring?

我正在使用一個漂亮的標准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?

驗證工作時,將引發異常。 然后服務器將找到代表服務器響應的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是您的自定義響應。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM