Using Spring @ResponseStatus to Set HTTP Status Code – 使用Spring @ResponseStatus来设置HTTP状态代码

最后修改: 2018年 7月 3日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In Spring MVC, we have many ways to set the status code of an HTTP response.

在Spring MVC中,我们有很多方法来设置HTTP响应的状态代码

In this short tutorial, we will see the most straightforward way: using the @ResponseStatus annotation.

在这个简短的教程中,我们将看到最直接的方法:使用@ResponseStatus注释。

2. On Controller Methods

2.关于控制器方法

When an endpoint returns successfully, Spring provides an HTTP 200 (OK) response.

当一个端点成功返回时,Spring提供一个HTTP 200(OK)响应。

If we want to specify the response status of a controller method, we can mark that method with @ResponseStatus. It has two interchangeable arguments for the desired response status: code, and value. For example, we can indicate that the server refuses to brew coffee because it is a teapot:

如果我们想指定一个控制器方法的响应状态,我们可以用@ResponseStatus标记该方法。它有两个可互换的参数,用于指定响应状态。code,value.例如,我们可以表示服务器拒绝煮咖啡,因为它是一个茶壶

@ResponseStatus(HttpStatus.I_AM_A_TEAPOT)
void teaPot() {}

When we want to signal an error, we can provide an error message via the reason argument:

当我们想发出一个错误信号时,我们可以通过reason参数提供一个错误信息。

@ResponseStatus(HttpStatus.BAD_REQUEST, reason = "Some parameters are invalid")
void onIllegalArgumentException(IllegalArgumentException exception) {}

Note, that when we set reason, Spring calls HttpServletResponse.sendError(). Therefore, it will send an HTML error page to the client, which makes it a bad fit for REST endpoints.

注意,当我们设置reason时,Spring调用HttpServletResponse.sendError()。因此,它将向客户端发送一个HTML错误页面,这使得它不适合REST端点

Also note, that Spring only uses @ResponseStatus, when the marked method completes successfully (without throwing an Exception).

还要注意的是,Spring只在标记的方法成功完成时使用@ResponseStatus(没有抛出一个Exception)。

3. With Error Handlers

3.有错误处理程序

We have three ways to use @ResponseStatus to convert an Exception to an HTTP response status:

我们有三种方法来使用@ResponseStatusException转换为HTTP响应状态。

  • using @ExceptionHandler
  • using @ControllerAdvice
  • marking the Exception class

In order to use the first two solutions, we have to define an error handler method. You can read more about this topic in this article.

为了使用前两种解决方案,我们必须定义一个错误处理方法。你可以在这篇文章中阅读更多关于这个主题的内容。

We can use @ResponseStatus with these error handler methods the same way we did with regular MVC methods in the previous section.

我们可以在这些错误处理方法中使用@ResponseStatus与上一节中使用常规MVC方法的方式相同

When we don’t need dynamic error responses, the most straightforward solution is the third one: marking the Exception class with @ResponseStatus:

当我们不需要动态错误响应时,最直接的解决方案是第三种:用@ResponseStatus:标记Exception类。

@ResponseStatus(code = HttpStatus.BAD_REQUEST)
class CustomException extends RuntimeException {}

When Spring catches this Exception, it uses the settings we provided in @ResponseStatus.

当Spring捕捉到这个Exception时,它会使用我们在@ResponseStatus中提供的设置。

Note, that when we mark an Exception class with @ResponseStatus, Spring always calls HttpServletResponse.sendError(), whether we set reason or not.

注意,当我们用@ResponseStatus标记Exception类时,Spring总是调用HttpServletResponse.sendError(),无论我们是否设置reason

Also note, that Spring uses the same configuration for subclasses, unless we mark them with @ResponseStatus, too.

还要注意的是,Spring对子类使用相同的配置,除非我们也用@ResponseStatus标记它们。

4. Conclusion

4.总结

In this article, we saw how we can use @ResponseStatus to set HTTP response code in different scenarios, including error handling.

在这篇文章中,我们看到了如何使用@ResponseStatus来设置不同场景下的HTTP响应代码,包括错误处理。

As usual, the examples are available over on GitHub.

像往常一样,这些例子可以在GitHub上找到over