java - Spring MVC 中是否可以区分具有相同 URL 的 2 个 POST 方法?

标签 java ajax spring spring-mvc controller

在我的应用程序中,我可以创建和更新实体。问题是我无法将这 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/

相关文章:

java - 字符串池的意外行为

java - ElementCollections 在父级的 id 上唯一,指定值

php - AJAX即时搜索修改

javascript - AJAX 调用工作正常但加载 gif 消失得太快

java - Spring Auditing - Spring如何自动将@CreatedDate和@LastModifiedDate插入数据库?

java - 仅将 https 与 spring cloud 微服务实例一起使用

ajax - 如何在 Grails 和 AngularJS 上使用 Spring Security 进行 Ajax 登录

java - 成员变量和局部方法变量可以重名吗?

javascript - 如何从php到html获取php数组中项目的位置整数?

java - Android MuPDF 错误