Returning Custom Status Codes from Spring Controllers – 从Spring控制器返回自定义状态代码

最后修改: 2016年 2月 3日

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

1. Overview

1.概述

This quick article will demonstrate a few ways to return custom HTTP status codes from Spring MVC controllers.

这篇快速文章将演示几种从Spring MVC控制器返回自定义HTTP状态代码的方法。

This is often important in order to more clearly express the result of a request to a client and using the full rich semantics of the HTTP protocol. For example, if something goes wrong with a request, sending a specific error code for each type of possible problem would allow the client to display an appropriate error message to the user.

为了更清楚地表达对客户端的请求结果,并使用HTTP协议的全部丰富语义,这通常是很重要的。例如,如果一个请求出了问题,为每一种可能的问题类型发送一个特定的错误代码,将允许客户端向用户显示一个适当的错误信息。

The setup of a basic Spring MVC project is outside the scope of this article, but you can find more information here.

基本的Spring MVC项目的设置超出了本文的范围,但你可以在这里找到更多信息

2. Returning Custom Status Codes

2.返回自定义状态代码

Spring provides a few primary ways to return custom status codes from its Controller classes:

Spring提供了几种主要的方法来从其Controller类中返回自定义状态代码。

  • using a ResponseEntity
  • using the @ResponseStatus annotation on exception classes, and
  • using the @ControllerAdvice and @ExceptionHandler annotations.

These options are not mutually exclusive; far from it, they can actually complement one another.

这些选项并不相互排斥;远非如此,它们实际上可以相互补充。

This article will cover the first two ways (ResponseEntity and @ResponseStatus). If you would like to learn more about using @ControllerAdvice and @ExceptionHandler, you can read about it here.

本文将介绍前两种方式(ResponseEntity@ResponseStatus)。如果你想了解更多关于使用@ControllerAdvice@ExceptionHandler的信息,你可以在这里阅读。

2.1. Returning Status Codes via a ResponseEntity

2.1.通过ResponseEntity返回状态代码

In a standard Spring MVC controller, we will define a simple mapping:

在一个标准的Spring MVC控制器中,我们将定义一个简单的映射。

@RequestMapping(value = "/controller", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity sendViaResponseEntity() {
    return new ResponseEntity(HttpStatus.NOT_ACCEPTABLE);
}

Upon receiving a GET request to “/controller“, Spring will return a response with the 406 Code (Not Acceptable). We arbitrarily selected the specific response code for this example. You can return any HTTP status code (the full list can be found here).

当收到对”/controller“的GET请求时,Spring将返回406代码(不可接受)的响应。我们在这个例子中任意选择了特定的响应代码。你可以返回任何HTTP状态代码(完整的列表可以在这里)。

2.2. Returning Status Codes via an Exception

2.2.通过异常返回状态代码

We will add a second method to the controller to demonstrate how to use an Exception to return a status code:

我们将为控制器添加第二个方法,演示如何使用Exception来返回状态代码。

@RequestMapping(value = "/exception", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity sendViaException() {
    throw new ForbiddenException();
}

Upon receiving a GET request to “/exception“, Spring will throw a ForbiddenException. This is a custom exception that we will define in a separate class:

在收到对”/exception“的GET请求时,Spring将抛出一个ForbiddenException。这是一个自定义的异常,我们将在一个单独的类中定义。

@ResponseStatus(HttpStatus.FORBIDDEN)
public class ForbiddenException extends RuntimeException {}

No code is required in this exception. All the work is done by the @ResponseStatus annotation.

在这个异常中不需要任何代码。所有的工作都由@ResponseStatus注解完成。

In this case, when the exception is thrown, the controller that threw it returns a response with the response code 403 (Forbidden). If necessary, you can also add a message in the annotation that will be returned along with the response.

在这种情况下,当异常被抛出时,抛出异常的控制器会返回一个响应代码为403(禁止)的响应。如果有必要,你也可以在注解中添加一条信息,该信息将与响应一起返回。

In this case, the class would look like this:

在这种情况下,该类将看起来像这样。

@ResponseStatus(value = HttpStatus.FORBIDDEN, reason="To show an example of a custom message")
public class ForbiddenException extends RuntimeException {}

It is important to note that while it is technically possible to make an exception return any status code, in most cases it only makes logical sense to use exceptions for error codes (4XX and 5XX).

需要注意的是,虽然在技术上可以使异常返回任何状态代码,但在大多数情况下,只有对错误代码(4XX和5XX)使用异常才是合理的。

3. Conclusion

3.结论

The tutorial showed how to return custom status codes from Spring MVC controllers.

该教程展示了如何从Spring MVC控制器返回自定义状态代码。

The implementation can be found in the example GitHub project.

可以在示例GitHub项目中找到该实现。