Spring Boot Rest Controller如何返回不同的HTTP状态码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24292373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:47:42  来源:igfitidea点击:

Spring Boot Rest Controller how to return different HTTP status codes?

springrestspring-boot

提问by Marco

I am using Spring Boot for a simple REST API and would like to return a correct HTTP statuscode if something fails.

我正在将 Spring Boot 用于一个简单的 REST API,并希望在出现故障时返回正确的 HTTP 状态码。

@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
@ResponseBody
@ResponseStatus( HttpStatus.OK )
public RestModel create(@RequestBody String data) {
    // code ommitted..
    // how do i return a correct status code if something fails?
}

Being new to Spring and Spring Boot, the basic question is how do i return different status codes when something is ok or fails?

作为 Spring 和 Spring Boot 的新手,基本问题是当某些事情正常或失败时我如何返回不同的状态代码?

回答by Jakub Kubrynski

There are several options you can use. Quite good way is to use exceptions and class for handling called @ControllerAdvice:

您可以使用多个选项。很好的方法是使用异常和类来处理调用@ControllerAdvice

@ControllerAdvice
class GlobalControllerExceptionHandler {
    @ResponseStatus(HttpStatus.CONFLICT)  // 409
    @ExceptionHandler(DataIntegrityViolationException.class)
    public void handleConflict() {
        // Nothing to do
    }
}

Also you can pass HttpServletResponseto controller method and just set response code:

您也可以传递HttpServletResponse给控制器方法并设置响应代码:

public RestModel create(@RequestBody String data, HttpServletResponse response) {
    // response committed...
    response.setStatus(HttpServletResponse.SC_ACCEPTED);
}

Please refer to the this great blog post for details: Exception Handling in Spring MVC

有关详细信息,请参阅这篇很棒的博文:Spring MVC 中的异常处理



NOTE

笔记

In Spring MVC using @ResponseBodyannotation is redundant - it's already included in @RestControllerannotation.

在 Spring MVC 中使用@ResponseBody注解是多余的——它已经包含在@RestController注解中。

回答by Ankit Basarkar

One of the way to do this is you can use ResponseEntity as a return object.

一种方法是您可以使用 ResponseEntity 作为返回对象。

@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)

public ResponseEntity<?> create(@RequestBody String data) {

if(everything_fine)
    return new ResponseEntity<>(RestModel, HttpStatus.OK);
else
    return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);

}

回答by Rodrigo Hernandez

Try this code:

试试这个代码:

@RequestMapping(value = "/validate", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<ErrorBean> validateUser(@QueryParam("jsonInput") final String jsonInput) {
    int numberHTTPDesired = 400;
    ErrorBean responseBean = new ErrorBean();
    responseBean.setError("ERROR");
    responseBean.setMensaje("Error in validation!");

    return new ResponseEntity<ErrorBean>(responseBean, HttpStatus.valueOf(numberHTTPDesired));
}

回答by Vedant Goenka

In case you want to return a custom defined status code, you can use the ResponseEntity as here:

如果您想返回自定义定义的状态代码,您可以使用 ResponseEntity 如下:

@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
public ResponseEntity<?> create(@RequestBody String data) {
    int customHttpStatusValue = 499;
    Foo foo = bar();
    return ResponseEntity.status(customHttpStatusValue).body(foo);
}

The CustomHttpStatusValue could be any integer within or outside of standard HTTP Status Codes.

CustomHttpStatusValue 可以是标准 HTTP 状态代码之内或之外的任何整数。