ResponseEntity< T>之间有什么区别?和@ResponseBody? [英] What is the difference between ResponseEntity<T> and @ResponseBody?
问题描述
我的控制器中有一个简单的处理程序,它返回一条消息
I have a simple handler in my controller which returns a message
@RequestMapping(value = "/message")
@ResponseBody
public Message get() {
return new Message(penguinCounter.incrementAndGet() + " penguin!");
}
同时我可以使用类似的东西
At the same time I can use something like this
@RequestMapping(value = "/message")
ResponseEntity<Message> get() {
Message message = new Message(penguinCounter.incrementAndGet() + " penguin!");
return new ResponseEntity<Message>(message, HttpStatus.OK);
}
这两种方法有什么区别?我们不考虑HttpStatus:)
What is the difference betweet this two approaches? Let's not take into account HttpStatus :)
推荐答案
ResponseEntity将为您提供更多的灵活性来定义任意HTTP响应头。请参阅此处的第4个构造函数:
ResponseEntity will give you some added flexibility in defining arbitrary HTTP response headers. See the 4th constructor here:
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响应标头列表:
A List of possible HTTP response headers is available here:
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Responses
一些常用的是状态,内容类型和缓存控制。
Some commonly-used ones are Status, Content-Type and Cache-Control.
如果你不需要,使用@ResponseBody将更简洁一点。
If you don't need that, using @ResponseBody will be a tiny bit more concise.
这篇关于ResponseEntity< T>之间有什么区别?和@ResponseBody?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!