带有Spring Boot的Hibernate @Validator

时间:2017-03-14 01:30:45

标签: java spring hibernate spring-boot

我有一个控制器方法来处理重置密码表单的POST请求。表单具有重置令牌的隐藏输入字段,并提示用户输入新密码。

我想在下面的代码中使用@Valid注释,但不确定我是否可以使用现有的User类。

Hibernate Validator是否要求我专门为表单创建一个额外的类?

控制器方法

@RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
public ModelAndView setNewPassword(@RequestParam Map<String,String> requestParams) {
  User user = userService.findUserByResetToken(requestParams.get("token"));

  ModelAndView modelAndView = new ModelAndView();
  modelAndView.addObject("message", "Form data is " + requestParams.get("token") + requestParams.get("password") + user.getEmail());
  modelAndView.setViewName("resetPassword");

  return modelAndView;
}

用户类

@Entity
@Table(name = "user")
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "id")
  private int id;

  @Column(name = "email")
  @Email(message = "Please provide a valid e-mail")
  @NotEmpty(message = "Please provide an e-mail")
  private String email;

  @Column(name = "password")
  @Size(min = 8, max = 72, message = "Your password must be between 8 and 72 characters long")
  @NotEmpty(message = "Please provide a password")
  @Transient
  private String password;

  @Column(name = "first_name")
  @NotEmpty(message = "Please provide your first name")
  private String firstName;

  @Column(name = "last_name")
  @NotEmpty(message = "Please provide your last name")
  private String lastName;

  @Column(name = "enabled")
  private boolean enabled;

  @Column(name = "confirmation_token")
  private String confirmationToken;

  @Column(name = "created_on")
  private Date createdOn;

  @Column(name = "last_login")
  private Date lastLogin;

  @Column(name = "reset_token")
  private String resetToken;

  // Getters and setters omitted 
}

1 个答案:

答案 0 :(得分:2)

您应该创建一个单独的类,最好直接将该类用作您的请求主体,以便能够在其上应用@Valid;

控制器方法

@RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
public ModelAndView setNewPassword(@RequestBody @Valid PasswordUpdateRq passwordUpdateRq) {
  User user = userService.findUserByResetToken(passwordUpdateRq.getToken());

  ModelAndView modelAndView = new ModelAndView();
  modelAndView.addObject("message", "Form data is " + passwordUpdateRq.getToken() + passwordUpdateRq.getPassword() + user.getEmail());
  modelAndView.setViewName("resetPassword");

  return modelAndView;
}

新请求Bean

public class PasswordUpdateRq {
  @Size(min = 8, max = 72, message = "Your password must be between 8 and 72 characters long")
  @NotEmpty(message = "Please provide a password")
  private String password;
  private String token;

  // Getters and setters omitted 
}

这将根据您的要求自动进行验证。 User类在此处不可用的原因是,还有其他具有@NotEmpty等限制的字段,这些字段在您当前的表单中不存在,并且这些字段始终无法通过验证。

额外评论:我认为使用相同的对象进行控制器层验证&amp;使用数据库的操作在两者之间创建了高耦合,我建议在逻辑类下保持与表相关的类,并使用在控制器层中特定于端点的接口bean。