小编典典

Spring MVC控制器方法何时应具有@ResponseBody?

spring-mvc

我在@ResponseBodySpring控制器中使用了注释,但不确定何时使用它。另外,我命名了我的方法index,我想知道这是否重要。我的方法头是

  @RequestMapping(value = "/addproduct", method = RequestMethod.POST)
    public ModelAndView index(@RequestParam("name") String name,
                              @RequestParam("file") MultipartFile file,
                              @RequestParam("desc") String desc,) {

但是在同一控制器中的另一种方法中,我使用@ResponseBody,我想知道该用法何时正确:

@RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView start() {

你能告诉我吗?该功能正在运行,但我想确定自己在做什么。


阅读 279

收藏
2020-06-01

共1个答案

小编典典

当您使用@ResponseBody时,控制器将通过HttpMessageConverter将您返回的内容转换为响应主体。

通常,当您要返回特定的数据格式(例如json或xml)时,可以使用它。这是一个示例:

    @RequestMapping(value = "/addproduct", method = RequestMethod.POST)
    public String index(@RequestParam("name") String name,
                            @RequestParam("file") MultipartFile file,
                            @RequestParam("desc") String desc,) {
           return "{\"name\": \"" + name + "\"}";
    }

然后,您将获得响应:{\“名称\”:\“ xxxxxx \”}“

2020-06-01