您好我正在使用spring MVC和thymeleaf,我无法更新控制器中的数据,因为我有以下代码。我面临的主要问题是我的put
方法没有被调用。< / p>
@GetMapping("/{id}/edit")
public String editUser(@PathVariable("id") int id, Model model) {
logger.info("++++++++++++[edit User]\n\n" + userService.findById(id));
model.addAttribute("user", userService.findById(id));
return "user/edit";
}
@PutMapping("/{id}/edit")
public String updateUser(@PathVariable("id") int id, @ModelAttribute("user") User user, Model model) {
logger.info("\n\n+++++++++++++++++inside Update");
User toUpdate = userService.findById(user.getId());
user.setUserName(user.getUserName() != null ? user.getUserName() : toUpdate.getUserName());
user.setName(user.getName() != null ? user.getName() : toUpdate.getName());
logger.info(user.toString());
userService.updateUser(user);
model.addAttribute("user", userService.findById(user.getId()));
return "redirect:/user/" + id;
}
和我的html页面
<form action="#" th:action="@{/user/__${user.id}__}" method="put"
th:object="${user}">
<div class="form-group">
<label for="txtUserName">User-name</label> <input
class="form-control" id="txtUserName" placeholder="User Name"
th:feild="${user.userName}" />
</div>
<div class="form-group">
<label for="txtName">First Name</label> <input
class="form-control" id="txtName" placeholder="Full Name"
th:feild="${user.name}" />
</div>
<div class="form-group">
<label for="calDob">Date of Birth</label> <input
class="form-control" id="calDob" placeholder="dd/MM/yyyy" />
</div>
<button type="submit" th:method="put" class="btn btn-success">Update</button>
<a href="#" th:href="@{/user/__${user.id}__}"
class="btn btn-primary">Cancel</a> <a th:method="delete"
href="javascript:deleteUser('${user.id}');" class="btn btn-danger">Delete</a>
</form>
任何帮助都会有用,谢谢
答案 0 :(得分:1)
PUT
不是method
标记form
的有效参数。请参阅HTML specification。
有效方法为GET
和POST
。由于它不是REST API,您可以使用POST
方法进行更新。
所以只需从以下位置更新您的映射:
@PutMapping("/{id}/edit")
到
@PostMapping("/{id}/edit")
将表格标记为:
<form action="#" th:action="@{/user/__${user.id}__}/edit" method="post" th:object="${user}">