Java Spring MVC控制器方法何时应该有@ResponseBody?
我在Spring控制器中使用了Java Spring MVC控制器方法何时应该有@ResponseBody?,java,spring,spring-mvc,Java,Spring,Spring Mvc,我在Spring控制器中使用了@ResponseBody注释,但我不确定何时使用它。此外,我还将我的方法命名为index,我想知道这是否重要。我的方法是 @RequestMapping(value = "/addproduct", method = RequestMethod.POST) public ModelAndView index(@RequestParam("name") String name, @Request
@ResponseBody
注释,但我不确定何时使用它。此外,我还将我的方法命名为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() {
你能告诉我吗?功能正常,但我想确定我在做什么 当您使用@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 + "\"}";
}
然后,您可以得到一个响应:{“name\”:\“xxxxxx\”}“当返回类型不是字符串而是ModelView时会发生什么情况(将@ResponseBody和返回ModelView组合在一起看起来像是一个错误)?使用哪个消息HttpMessageConverteris?取决于您在文件springMVC-servlet.xml中设置的转换器。如果您使用MappingJacksonHttpMessageConverter。转换器将尝试将对象转换为json并返回。使用默认配置,将使用哪个转换器?HttpMessageConverter是一个转换器接口。有7个implemented转换器。应该使用哪一个,由几个条件决定:转换器寄存器列表、请求头中的接受类型等等。也许这可以帮助您了解更多关于HttpMessageConverter的信息。