我当前正在发送一个登录的User
对象来查看它将通过th:object注入(inject)到表单中。我想更新此 User
对象中的某些属性,但仍保留该对象的其余内容。但是,当我提交此表单时,User
对象包含除我在 thymeleaf 页面中设置的值之外的所有值的空值。我知道一种解决方案是为我想要保留的值添加隐藏标签,但如果 User
对象很大,这似乎非常乏味。
@RequestMapping(value="/newprofile", method=RequestMethod.GET)
public String newProfile(Model model, Principal principal) {
String email = principal.getName();
User user = userService.findUserByEmail(email);
model.addAttribute("user", user);
return "newprofile";
}
@RequestMapping(value="/newprofile", method=RequestMethod.POST)
public String registerNewProfile(Model model,User user, Principal principal) {
userService.saveProfile(user); //this user object will contain null values
return "redirect:/profile";
}
这是表单的外观。进来的用户对象是一个现有的User
,其值已经设置。有可以更新的成员变量。
<form autocomplete="off" action="#" th:action="@{/newprofile}" th:object="${user}" method="post" class="form-signin" role="form">
<h3 class="form-signin-heading">Registration Form</h3>
<div class="form-group">
<div class="">
<input type="text" th:field="*{profile.basicInfo.age}" placeholder="Name" class="form-control" />
</div>
</div>
<div class="form-group">
<div class="">
<button type="submit" class="btn btn-primary btn-block">Update profile</button>
</div>
</div>
</form>
提交表单后,我通过 Spring JPA 的 save()
方法执行该 User 对象的保存。但是,如果 User 对象包含 null,它会错误地将这些值“更新”为 null。同样,我可以做一些检查来验证哪些成员应该更新,哪些成员不应该更新,但这似乎不正确......
@Override
public User saveProfile(User user) {
// TODO Auto-generated method stub
userRepository.save(user);
return user;
}
最佳答案
我们可以使用bean validation API模型类属性的注释如下:
@NotNull(message = "Name cannot not be null")
private String name;
这样,如果任何一个验证失败,就不会进入。
关于java - Spring MVC 通过表单更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59923825/