【问题标题】:Is it possible to distinguish 2 POST methods with same URL in Spring MVC?是否可以在 Spring MVC 中区分具有相同 URL 的 2 个 POST 方法?
【发布时间】:2018-03-04 10:45:28
【问题描述】:

在我的应用中,我可以创建和更新实体。问题是我无法将这两种方法合并到一个带有 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");
        }
    });
}

提前致谢

【问题讨论】:

  • 1/为什么不使用 2 个不同的 url? 2/我相信你可以使用@pathvariable 3/你发送相同的表格,那么为什么还要使用两种方法呢?
  • 是什么迫使你这样设计它?
  • :D 好的,唯一的解决方案似乎是使用不同的 URL,谢谢

标签: java ajax spring spring-mvc controller


【解决方案1】:

你可以使用@RequestBody注解:

@PutMapping("/users/{id}")
public void update(@PathVariable Long id, @RequestBody User user) 
{
    service.update(user);
}

【讨论】:

  • 但是这里的重点是你不能在 PUT 方法中请求一些东西
【解决方案2】:

这可能会对您有所帮助:

@RequestMapping(value="/users/{id}", method=RequestMethod.POST) 

【讨论】:

  • 欢迎来到 StackOverflow 并感谢您的帮助。您可能希望通过添加一些解释来使您的答案变得更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多