When should a Spring MVC controller method have @ResponseBody?

一笑奈何 提交于 2020-01-04 09:05:30

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/20089421/when-should-a-spring-mvc-controller-method-have-responsebody

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!