【问题标题】:Spring MVC updating an object via formSpring MVC 通过表单更新对象
【发布时间】:2020-01-26 23:51:16
【问题描述】:

我目前正在发送一个已登录的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;
}

【问题讨论】:

    标签: java spring spring-boot spring-mvc


    【解决方案1】:

    我们可以在模型类属性上使用bean validation API注解,如下所示:

    @NotNull(message = "Name cannot not be null")
    private String name;
    

    @NotEmpty@NotBlank的类似用法

    这样,任何一个验证失败都不会进入。

    【讨论】:

      【解决方案2】:

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

      BeanUtils.copyProperties

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多