逻辑是这样的 - 来自数据库的记录显示在 html 页面的表中,该方法获取某条记录getUser并显示在 HTML 页面上,您可以在其中为字段设置新值的表单,按钮应该将整个事情发送回数据库update。但是更改没有到达数据库,我得到一个未更改的表。同时,从hibernate的日志来看,先是拉出了一条单独的记录,但是当按下按钮时,update什么也没发生,整个表就简单的显示出来了
GET 请求的控制器:
@GetMapping(value = "/users/get/{id}")
public ModelAndView getUser(@PathVariable long id) {
ModelAndView modelAndView = new ModelAndView("users/get");
modelAndView.addObject("getUser", userService.getUser(id));
return modelAndView;
}
保存请求的控制器:
@PostMapping(value = "/users/update")
public ModelAndView updateUser(@ModelAttribute User user) {
ModelAndView modelAndView = new ModelAndView("redirect:/users/");
modelAndView.addObject("updateUser", user);
return modelAndView;
}
用于更改用户的表单页面的 HTML 代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:form="http://www.w3.org/1999/html">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update user</title>
</head>
<body>
<form action="#" th:action="@{../update/} " th:object="${getUser}" method="post">
<label for="firstName" >Name</label>
<input type="text" th:field="*{firstName}" id="firstName" placeholder="Name">
<label for="lastName">Last Name</label>
<input type="text" th:field="*{lastName}" id="lastName" placeholder="Last Name">
<label for="email" class="col-form-label">eMail</label>
<input type="text" th:field="*{email}" id="email" placeholder="eMail">
<label for="phoneNo" >Phone No</label>
<input type="text" th:field="*{telephone}" id="phoneNo" placeholder="phoneNo">
<input type="submit" value="Update">
</form>
</body>
</html>
检查此值 th:action="${getUser}" 您正在尝试将 POST 方法映射到 GET 控制器。
感谢大家的回复!问题已通过更换控制器解决,附上代码