【问题标题】:What is the difference between ResponseEntity<T> and @ResponseBody?ResponseEntity<T> 和@ResponseBody 有什么区别?
【发布时间】:2014-05-08 15:23:57
【问题描述】:

我的控制器中有一个简单的处理程序,它返回一条消息

@RequestMapping(value = "/message")
@ResponseBody
public Message get() {
    return new Message(penguinCounter.incrementAndGet() + " penguin!");
}

同时我可以使用这样的东西

@RequestMapping(value = "/message")
ResponseEntity<Message> get() {
    Message message = new Message(penguinCounter.incrementAndGet() + " penguin!");
    return new ResponseEntity<Message>(message, HttpStatus.OK);
}

这两种方法有什么区别?我们不要考虑 HttpStatus :)

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    ResponseEntity是一个带有类型参数的泛型类,你可以指定将什么类型的对象序列化到响应体中。

    @ResponseBody是一个注解,表示方法的返回值将被序列化到HTTP响应的正文中。

    您可以使用 ResponseEntity

    设置标头

    【讨论】:

      【解决方案2】:

      HttpEntity 代表一个 HTTP requestresponseheadersbody 组成.

      // Only talks about body & headers, but doesn't talk about status code
      public HttpEntity(T body, MultiValueMap<String,String> headers)
      

      ResponseEntity 扩展了 HttpEntity,但也添加了一个 Http 状态码。

      // i.e ResponseEntity = HttpEntity + StatusCode
      public ResponseEntity(T body, MultiValueMap<String,String> headers, HttpStatus statusCode)
      

      因此用于完全 配置 HTTP 响应。

      例如:

      @ControllerAdvice 
      public class JavaWebExeptionHandler {
      
          @Autowired
          ExceptionErrorCodeMap exceptionErrorCodeMap;
      
          @ExceptionHandler(RuntimeException.class)
          public final ResponseEntity<ExceptionResponseBody> handleAllExceptions(Exception ex) {
              Integer expCode = exceptionErrorCodeMap.getExpCode(ex.getClass());
              // We have not added headers to response here, If you want you can add by using respective constructor
              return new ResponseEntity<ExceptionResponseBody>(new ExceptionResponseBody(expCode, ex.getMessage()),
                      HttpStatus.valueOf(expCode));
          }
      
      }
      

      @ResponseBody 表示使用它的 methodreturn 值绑定到响应 body (意味着方法的返回值被视为Http响应体)

      【讨论】:

        【解决方案3】:

        ResponseEntity 将在定义任意 HTTP 响应标头时为您提供一些额外的灵活性。在这里查看第四个构造函数:

        http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/http/ResponseEntity.html

        ResponseEntity(T body, MultiValueMap<String,String> headers, HttpStatus statusCode) 
        

        此处提供了可能的 HTTP 响应标头列表:

        http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Responses

        一些常用的有St​​atus、Content-Type和Cache-Control。

        如果不需要,使用@ResponseBody 会更简洁一些。

        【讨论】:

        • header 中传输了哪些内容?有什么例子吗?
        猜你喜欢
        • 2022-12-23
        • 2012-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-16
        • 2019-10-30
        相关资源
        最近更新 更多