gpt4 book ai didi

java - Spring 3.1 验证 - 当您有 2 个单独的表单提交和持久模型时如何使用 @valid

转载 作者:行者123 更新时间:2023-12-01 15:12:51 25 4
gpt4 key购买 nike

我有两个独立的模型 AccountDetailsFormAccountDetails,前者用于表单提交,后者用于持久性。

帐户详细信息表格:

public class AccountDetailsForm {

private AccountDetails accountDetails;

@NotNull
private String confirmPassword;

//setter and getters
}

和帐户详细信息:

@Entity
@Table(name = "ACCOUNT")
public class AccountDetails {

@Id
@Column(name = "USER_NAME")
@NotEmpty
@Max(value = 60)
private String userName;


@Column(name = "PASSWORD")
@NotEmpty
@Min(value = 8)
private String password;

//setters and getters
}

现在我正在使用 @Valid 验证提交的表单:

@RequestMapping(value="userRegistration", method = RequestMethod.POST)
public ModelAndView registerUser(@Valid AccountDetailsForm accountDetailsForm, BindingResult result,Model model){

//I autowire localValidatorFactoryBean to validate the fields in AccountDetails bean.
localValidatorFactoryBean.validate(accountDetailsForm.getAccountDetails(), result);

if (result.hasErrors()){
model.addAttribute("accountDetailsForm", new AccountDetailsForm());
model.addAllAttributes(result.getModel());
return new ModelAndView("userRegistration");
}

我使用 hibernate 来实现持久性。有没有办法使用 @Valid 来验证 accountDetails bean,而不是显式调用 validate() 方法或使用 spring validator 实现?

我不介意听到有关 confirmPassword 解决方法的建议。我遵循当前的方法,因为模型中包含 confirmPassoword 字段没有意义。

最佳答案

@Valid放入AccountDetailsFormAccountDetails对象中:

public class AccountDetailsForm {

@Valid
private AccountDetails accountDetails;

@NotNull
private String confirmPassword;

//setter and getters
}

当在 Controller 中使用 @Valid 验证 AccountDetailsForm 时,AccountDetails 也将被验证。

引用示例here .

关于java - Spring 3.1 验证 - 当您有 2 个单独的表单提交和持久模型时如何使用 @valid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12087160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com