ResponseEntity <t>和@ResponseBody之间有什么区别?</t>

时间:2014-03-28 23:51:25

标签: java spring spring-mvc

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

@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:)

2 个答案:

答案 0 :(得分:50)

ResponseEntity将为您定义任意HTTP响应标头提供一些额外的灵活性。请参见此处的第4个构造函数:

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

一些常用的是Status,Content-Type和Cache-Control。

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

答案 1 :(得分:3)

HttpEntity 表示由标头正文组成的HTTP 请求响应

// 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 表示使用它的方法 return 值已绑定到响应 body (意味着方法的返回值被视为Http响应正文)