Spring Boot Rest Controller如何返回不同的HTTP状态代码? [英] Spring Boot Rest Controller how to return different HTTP status codes?

查看:716
本文介绍了Spring Boot Rest Controller如何返回不同的HTTP状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Spring Boot用于简单的REST API,如果出现故障,我想返回正确的HTTP状态代码.

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

@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?
}

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

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

推荐答案

您可以使用几个选项.很好的方法是使用异常和类进行处理,称为@ControllerAdvice:

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

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

您还可以将HttpServletResponse传递给控制器​​方法,而只需设置响应代码:

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

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中使用@ResponseBody注释是多余的-它已经包含在

In Spring MVC using @ResponseBody annotation is redundant - it's already included in @RestController annotation.

这篇关于Spring Boot Rest Controller如何返回不同的HTTP状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆