When should a Spring MVC controller method have @ResponseBody?
java, spring, spring-mvc
Solution
When you use @ResponseBody, controller will convert the content you returned into the response body by HttpMessageConverter.
Usually, you can use it when you want to return specific data format(like json or xml). Here is a sample:
@RequestMapping(value = "/addproduct", method = RequestMethod.POST)
public String index(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file,
@RequestParam("desc") String desc,) {
return "{\"name\": \"" + name + "\"}";
}
Then, you can get a response : {\"name\": \"xxxxxx\"}"
Problem
I use the `@ResponseBody` annotation with my Spring controller but I'm not sure when to use it. Also, I named my method `index`and I wonder if that matters. My method head is ``` @RequestMapping(value = "/addproduct", method = RequestMethod.POST) public ModelAndView index(@RequestParam("name") String name, @RequestParam("file") MultipartFile file, @RequestParam("desc") String desc,) { ``` But in another method in the same controller I use the `@ResponseBody` and I want to know when that usage is correct: ``` @RequestMapping(value = "", method = RequestMethod.GET) @ResponseBody public ModelAndView start() { ``` Can you please tell me? The functionality is working but I want to be sure what I'm doing.