java - Spring MVC 通过表单更新对象

标签 java spring spring-boot spring-mvc

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

@NotEmpty的类似用法, @NotBlank

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

关于java - Spring MVC 通过表单更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59923825/

相关文章:

java - SimpUserRegistry 不包含任何 session 对象

java - spring boot中多个配置属性@Autowired其中一个属性为null

java - 如何在 Spring Boot 应用程序的 application.properties 文件中设置 MyBatis 配置属性?

java - 读取 url 到字符串时什么也得不到

java.lang.RuntimeException : Parcelable encountered IOException writing serializable object (name = [[Landroid. widget.Button;)

spring - 在 wildfly 中获取 spring 框架登录

java - 声明具有相同属性的 bean

java - Sonar 测试用例失败

java - 将 Play 项目部署为服务

java - 如何在启动时设置一个简单的 Spring 表单