Reputation: 1129
It could be very simple but it will be very helpful for me to understand...
I used @ResponseBody in my restcontroller to return String value to browser. The response string is successfully received in browser.
ie:
@RequestMapping(value="/foo", method=RequestMethod.GET)
@ResponseBody
public String foo() {
return "bar";
}
What is the content-type of above response? If this is going to be like writing setAttribute in servlet response what could the attribute name?
If the browser accept only "application/json" how spring will treat the response?
Upvotes: 2
Views: 7748
Reputation: 409
Submitted code produces text/html, as do all mapped Controller methods by default. If you want to produce application/json, you have to change your RequestMapping to
@RequestMapping(value="/foo", method=RequestMethod.GET, produces = "application/json")
However this is not a valid Json String, you would have to change it because the method you submitted would return empty body. The submitted example would be valid text/plain.
When the request contains header "Accept: application/json"
and other content type is returned, Spring returns Json-type response explaining that HttpMediaTypeNotAcceptableException
was thrown.
Regarding the servlet analogy - please explain, I don't fully understand what you mean. The String is returned as response body, it's very different from request attributes. What would you like to achieve?
Upvotes: 4
Reputation: 210
I assume the content type will be plain/text. If the request sets accept to "application/json" it depends on your browser/tool. Most rest clients won't display it as it is not application/json. If you invoke the API directly I would assume it is displayed due to browser content sniffing (can be disabled via a header).
Upvotes: 3