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)
    public ModelAndView start() {

Can you please tell me? The functionality is working but I want to be sure what I'm doing.


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

Java Equivalent of IEnumerable<char>

c# java translation

This is the C# code that I have to convert:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.