更新用户数据spring boot的最佳方法是什么?

时间:2018-04-29 15:39:54

标签: java spring-boot spring-data spring-data-jpa thymeleaf

我无法以正确的方式更新用户数据,例如他的名字或姓氏

控制器:

@Controller
public class UpdateUserData {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user/updateFirstName", method = RequestMethod.POST)
    public String changeUserFirstName(RedirectAttributes rm, final Locale locale, @Valid UserDto userDto) {
        final User user = (User) SecurityContextHolder.getContext()
            .getAuthentication()
            .getPrincipal();
        userService.changeUserFirstName(user, userDto.getFirstName());

        rm.addFlashAttribute(
            "message",
            messages.getMessage("message.updateFirstNameSuc", null, locale)
        );
        return "redirect:/user/myAccount?lang=" + locale.getLanguage();
    }
}

这是myAccount html页面中相关的部分:

<div class="manageinfo">
   <h1>Manage your personal information</h1>
   <br/>
   <div class="container">
      <div th:if="${message != null}" class="alert alert-info" 
         th:text="${message}">message</div>
      <div th:each = "user: ${user}" >
         <p>Firstname</p>
         <input type="text" th:value="${user.firstName}"><a data-toggle="modal" 
            data-target="#myModalFirstName"><i class="fa fa-pencil fa-lg"> </i></a>
      </div>
      <!-- Modal for firstName-->
      <div class="modal fade" id="myModalFirstName" role="dialog">
         <button type="button" class="close" data-dismiss="modal">&times;</button>
         <form th:action="@{/user/updateFirstName}" th:method="POST">
            <p>First Name</p>
            <input type="text" name="firstName" required="required">
            <span id="firstNameError"  style="color:#F41F0E" ></span>     
            <button type="submit" class="btn btn-default" >Save</button>
         </form>
      </div>
   </div>
</div>

UserServiceImpl:

public void changeUserFirstName(final User user, final String firstname) {
    user.setFirstName(firstname);
    userRepository.save(user);   
}

当我尝试更改我将收到的姓名时

Failed to resolve argument 2 of type Myproject.dto.UserDto
javax.validation.ValidationException: HV000028: Unexpected exception during isValid call

1 个答案:

答案 0 :(得分:1)

逻辑更新程序似乎没问题,我建议检查UserDto及其验证注释(@NotNull,@ Size等等),因为isValid是由@Valid注释引起的。 ; e控制器作为数据没有遵循给定的约束条件。

E.g, 您的UserDTO可能包含:

@Size(max = 30)
private String firstName;
@Pattern(regexp = "....")
private String lastName;

但是你的控制器收到的firstName大于maximum / firstName且格式错误。

另请阅读: https://docs.oracle.com/javaee/7/api/javax/validation/ConstraintValidator.html#isValid-T-javax.validation.ConstraintValidatorContext-