因此,我用 @Controller
注释了我的类,而不是我一直使用的 @RestController
。我的乐趣...
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = Paths.SOMEPATH, method = RequestMethod.POST)
public MyObject createMyObject(){
MyObject myObject = newMyObject();
myObjectRepository.save(myObject);//autowired repository
return myObject;
}
Produced 405 Method not allowed(整个方法通过,在返回时)
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = Paths.SOMEPATH, method = RequestMethod.POST)
public @ResponseBody MyObject createMyObject(){
MyObject myObject = newMyObject();
myObjectRepository.save(myObject);//autowired repository
return myObject;
}
效果很好,达到了预期效果
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = Paths.SOMEPATH, method = RequestMethod.POST)
public MyObject createMyObject(){
MyObject myObject = newMyObject();
return myObjectRepository.save(myObject);//autowired repository
}
这也有效,这就是为什么我很困惑。谁能解释一下为什么?
(我删除了诸如 @PathVariable
之类的东西以及对 myObject
和 @RequestBody
对象的操作,这些对象用于在 MyObject 中填充数据
为简洁起见的实例)
编辑: 405响应正文
{
"timestamp": 1446735218918,
"status": 405,
"error": "Method Not Allowed",
"exception": "org.springframework.web.HttpRequestMethodNotSupportedException",
"message": "Request method 'POST' not supported",
"path": "/myPath"
}
最佳答案
在 Http 中,错误 4XX 是用户错误。这意味着您没有正确调用您的服务。
"status": 405,
"error": "Method Not Allowed",
此错误意味着您没有调用正确的 Http 方法,您将方法定义为 POST,可能您正在使用 GET 调用它。
关于java - 关于@Controller @RestController 和@ResponseBody 的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33547357/