是否可以在Spring MVC中区分2个POST方法和相同的URL?

问题描述:

在我的应用程序中,我可以创建和更新实体。问题是我不能将一个createOrUpdate方法中的这两个方法与POST映射合并,并检查对象是否是新的(这是因为ID不是自动生成的,由用户提供)。 我最终创建了一个方法创建(POST映射)和更新(PUT映射)。但过了一段时间,我知道在Spring中,如果方法是PUT,那么它不能请求参数。 所以,我想我应该使用2个POST方法,但它们具有相同的URL模式,因为我的应用程序无法正常工作。是否可以在Spring MVC中区分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"); 
     } 
    }); 
} 

在此先感谢

+0

1 /为什么不使用2个不同的网址? 2 /我相信你可以使用@pathvariable 3 /你发送相同的表格,那么为什么还有两种方法呢? –

+0

是什么强迫你设计它呢? –

+0

:D 好的,有不同的URL似乎是唯一的解决方案,thx –

您可以使用@RequestBody注释:

@PutMapping("https://stackoverflow.com/users/{id}") 
public void update(@PathVariable Long id, @RequestBody User user) 
{ 
    service.update(user); 
} 
+0

但这里的关键是你不能请求PUT方法 –

这可能会帮助您:

@RequestMapping(value="https://stackoverflow.com/users/{id}", method=RequestMethod.POST) 
+0

欢迎来到StackOverflow并感谢您的帮助。你可能想通过添加一些解释来让你的答案更好。 –