Java Spring MVC通过表单更新对象
我当前正在发送一个登录的Java Spring MVC通过表单更新对象,java,spring,spring-boot,spring-mvc,Java,Spring,Spring Boot,Spring Mvc,我当前正在发送一个登录的用户对象以查看,该对象将通过th:object注入表单。我想更新此用户对象中的某些属性,但仍保留该对象的其余内容。但是,当我提交此表单时,User对象包含除我在ThymileAF页面中设置的值之外的所有值的空值。我知道一个解决方案是为我想要保留的值添加隐藏标记,但如果用户对象很大,这似乎非常乏味 @RequestMapping(value="/newprofile", method=RequestMethod.GET) public String newProfile(M
用户
对象以查看,该对象将通过th:object注入表单。我想更新此用户
对象中的某些属性,但仍保留该对象的其余内容。但是,当我提交此表单时,User
对象包含除我在ThymileAF页面中设置的值之外的所有值的空值。我知道一个解决方案是为我想要保留的值添加隐藏标记,但如果用户
对象很大,这似乎非常乏味
@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";
}
下面是表单的外观。进入的用户对象是现有的用户
,其值已设置。存在可以更新的成员变量
<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>
我们可以在模型类属性上使用注释,如下所示:
@NotNull(message = "Name cannot not be null")
private String name;
类似使用
这样,如果任何验证失败,它就不会输入。如果在更新之前复制现有用户bean是一个选项,那么可以使用以下api 小海狸 请注意,有两种流行的BeanUtils.copyProperties。一个来自,另一个在这篇文章中提到。这两种api的方法参数顺序不同
@NotNull(message = "Name cannot not be null")
private String name;