我认为我的问题很简单,但是我没有找到解决方案。
我有一个HTML文件,其中创建了两个按钮
<button id="saveEmployee" type="submit" class="btn btn-primary">Save</button>
<button id="deleteEmployee" type="submit" class="btn btn-secondary">Delete</button>
并且我的控制器类中有两个PostMapping
@PostMapping
public String saveButton(Employee employee) {
Employee saved = employeeRepository.save(employee);
return "redirect:/employee/" + saved.getEmployeeId() + "/view";
}
@PostMapping
public String deleteButton(Employee employee) {
employeeRepository.deleteByEmployeeId(employee.getEmployeeId());
return "redirect:/employee/create";
}
现在我想通过id“ saveEmployee”和“ deleteEmloyee”来处理正确的PostMapping。
我该怎么做?
答案 0 :(得分:0)
您可以通过添加参数来检查它,以检查用户是否单击删除或保存。
例如
在按钮中添加名称和值属性
<button id="saveEmployee" name="btn" value="Save" type="submit" class="btn btn-primary">Save</button>
<button id="deleteEmployee" name="btn" value="Delete" type="submit" class="btn btn-secondary">Delete</button>
然后在您的控制器中使用@RequestMapping。
@RequestMapping(value="/someurl", method=RequestMethod.POST)
public String handleSaveDelete(@RequestParam("employee") Employee employee, @RequestParam("btn") String button){
if("Save".equals(button)) {
// Save
}else if("Delete".equals(button)){
// Delete
}
return "redirect:/";
}
希望能有所帮助,谢谢。
答案 1 :(得分:0)
也许此页面对您有帮助https://spring.io/guides/gs/handling-form-submission/
一种方法可能类似于:
<form action="/save/" method="post">
<button id="saveEmployee" type="submit" class="btn btn-primary">Save</button>
</form>
<form action="/delete/" method="post">
<button id="deleteEmployee" type="submit" class="btn btn-secondary">Delete</button>
</form>
和:
@PostMapping("/save/")
public String saveButton(Employee employee) {
Employee saved = employeeRepository.save(employee);
return "redirect:/employee/" + saved.getEmployeeId() + "/view";
}
@PostMapping("/delete/")
public String deleteButton(Employee employee) {
employeeRepository.deleteByEmployeeId(employee.getEmployeeId());
return "redirect:/employee/create";
}