我在我的 Spring Controller 中使用了 @ResponseBody
注释,但我不确定何时使用它。另外,我将我的方法命名为 index
,我想知道这是否重要。我的方法头是
@RequestMapping(value = "/addproduct", method = RequestMethod.POST)
public ModelAndView index(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file,
@RequestParam("desc") String desc,) {
但在同一 Controller 的另一种方法中,我使用了 @ResponseBody
,我想知道这种用法何时正确:
@RequestMapping(value = "", method = RequestMethod.GET)
@ResponseBody
public ModelAndView start() {
你能告诉我吗?该功能正在运行,但我想确定我在做什么。
最佳答案
当你使用@ResponseBody时,controller会通过HttpMessageConverter将你返回的内容转换成response body。
通常,当你想返回特定的数据格式(如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\"}"
关于java - Spring MVC Controller 方法什么时候应该有@ResponseBody?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20089421/