简体   繁体   中英

Content-type and @ResponseBody in spring

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?

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM