When should a Spring MVC controller method have @ResponseBody?

I use the @ResponseBody annotation with my Spring controller but I'm not sure when to use it. Also, I named my method indexand 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.

Answers


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\"}"


Need Your Help

Ajax call for json fails in ie

ajax json internet-explorer jquery

My jquery ajax call for a json file fails in Internet Explorer.

ROR - My logic works, Boolean value doesn't post

ruby-on-rails post boolean

My logic tests an inventory supply; and the < operator functions fine. How do I assign boolean values to "instock"? (using POST) In this test, under both conditions the value remains unchanged and