在我的应用程序中,我可以创建和更新实体。问题是我无法将这 2 个方法合并到一个带有 POST 映射的 createOrUpdate 方法中,并检查对象是否是新的(这是因为 ID 不是自动生成的,由用户提供)。 我最终采用了创建(POST 映射)和更新(PUT 映射)方法之一。但过了一段时间,我知道在 Spring 中,如果方法是 PUT,则无法请求参数。 因此,我想我应该使用 2 个 POST 方法,但它们具有相同的 URL 模式,因为我的应用程序无法正常工作。
有可能做出这样的东西吗?
@RequestMapping(value = "/ajax/users")
/.../
@PostMapping (//specific param here to distinguish???)
public void create(User user)
{
service.save(user);
}
@PostMapping(//specific param here to distinguish???)
public void update(User user)
{
service.update(user);
}
function save() {
$.ajax({
type: "POST", //specific param here to distinguish?
url: ajaxUrl,
data: form.serialize(),
success: function () {
$("#editRow").modal("hide");
updateTable();
successNoty("Saved");
}
});
}
function update() {
$.ajax({
type: "POST",//specific param here to distinguish?
url: ajaxUrl,
data: form.serialize(),
success: function () {
$("#editRow").modal("hide");
updateTable();
successNoty("Updated");
}
});
}
提前致谢
最佳答案
您可以使用@RequestBody注释:
@PutMapping("/users/{id}")
public void update(@PathVariable Long id, @RequestBody User user)
{
service.update(user);
}
关于java - Spring MVC 中是否可以区分具有相同 URL 的 2 个 POST 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46371749/