首页 > 解决方案 > Spring MVC 通过表单更新对象

问题描述

我目前正在发送一个登录的User对象来查看,它将通过 th:object 注入到表单中。我想更新此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 对象包含空值,它会错误地将这些值“更新”为空值。同样,我可以做一些检查来验证哪些成员应该更新,哪些不应该更新,但这似乎不正确......

@Override
public User saveProfile(User user) {
    // TODO Auto-generated method stub
    userRepository.save(user);
    return user;
}

标签: javaspringspring-bootspring-mvc

解决方案


如果在更新之前复制现有的用户 bean 是一个选项,则可以使用以下 api。

BeanUtils。复制属性

请注意,有两个流行的 BeanUtils.copyProperties。一个来自Apache,另一个在这篇文章中提到。这两个 api 的方法参数的顺序是不同的。


推荐阅读