我和你有同样的问题,所以我建立了自己的解决方案
1- 您需要在控制器上执行两个操作:视图 (GET) 和操作 (POST)
@GetMapping("/user/edit/{userId}")
public ModelAndView editUserView(@PathVariable Long userId) throws NotFoundException {
User user = this.userService.load(userId);
if (user == null) {
throw new NotFoundException("Not found user with ID " + userId);
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("user.edit");
modelAndView.addObject("user", user);
return modelAndView;
}
@PostMapping("/user/edit/{userId}")
public ModelAndView editUserAction(HttpServletRequest request, @PathVariable Long userId, @Validated(User.ValidationUpdate.class) User userView,
BindingResult bindingResult) throws Exception {
User user = this.userService.load(userId);
if (user == null) {
throw new NotFoundException("Not found user with ID " + userId);
}
ModelAndView modelAndView = new ModelAndView();
if (bindingResult.hasErrors()) {
modelAndView.setViewName("user.edit");
modelAndView.addObject("user", userView);
return modelAndView;
}
Form.bind(request, userView, user);
this.userService.update(user);
modelAndView.setViewName("redirect:/admin/user");
return modelAndView;
}
2- 一个显示错误的视图(非常重要:添加隐藏输入以发送 id 进行验证)
<fieldset th:if="${#fields.hasErrors('${user.*}')}" class="text-warning">
<legend>Some errors appeared !</legend>
<ul>
<li th:each="err : ${#fields.errors('user.*')}" th:text="${err}"></li>
</ul>
</fieldset>
<form action="#" th:action="@{/admin/user/edit/{id}(id=${user.id})}" th:object="${user}" method="post">
<div th:class="${#fields.hasErrors('firstName')} ? 'form-group has-error' : 'form-group'">
<label class="control-label" for="firstName">First Name <span class="required">*</span></label>
<input type="text" th:field="*{firstName}" required="required">
</div>
...
<input type="hidden" th:field="*{id}">
</form>
3- 对于我的示例,我编写了一个 FormUtility 类来合并两个对象:
public static List<String> bind(HttpServletRequest request, Object viewObject, Object daoObject) throws Exception {
if (viewObject.getClass() != daoObject.getClass()) {
throw new Exception("View object and dao object must have same type (class) !");
}
List<String> errorsField = new ArrayList<String>();
// set field value
for (Entry<String, String[]> parameter : request.getParameterMap().entrySet()) {
// build setter/getter method
String setMethodName = "set" + parameter.getKey().substring(0, 1).toUpperCase()
+ parameter.getKey().substring(1);
String getMethodName = "get" + parameter.getKey().substring(0, 1).toUpperCase()
+ parameter.getKey().substring(1);
try {
Method getMethod = daoObject.getClass().getMethod(getMethodName);
Method setMethod = daoObject.getClass().getMethod(setMethodName, getMethod.getReturnType());
setMethod.invoke(daoObject, getMethod.invoke(viewObject));
}
catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException exception) {
errorsField.add(parameter.getKey());
}
}
return errorsField;
}
希望对您有所帮助。