Tuesday, December 29, 2015

Difference between ResponseEntity and @ResponseBody?

Ref:- http://stackoverflow.com/questions/22725143/what-is-the-difference-between-responseentityt-and-responsebody


@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);
}
What is the difference betweet this two approaches?

ResponseEntity will give you some added flexibility in defining arbitrary HTTP response headers. See the 4th constructor here:
ResponseEntity(T body, MultiValueMap<String,String> headers, HttpStatus statusCode) 
A List of possible HTTP response headers is available here:
Some commonly-used ones are Status, Content-Type and Cache-Control.
If you don't need that, using @ResponseBody will be a tiny bit more concise.

No comments:

Post a Comment