我正在尝试在我的电子商务网站中设置Hibernate验证。 我有一个分配了多个对象的订单对象。当客户完成结账时,我希望能够单独验证这些对象 - 有时是一个表单的多个对象。
例如,在提交交付表单时,应验证deliveryCharge和deliveryAddress。如果此验证失败,将返回交付表单,其中包含验证错误列表。
我可以通过java实现验证对象,但是当我尝试使用<form:error />
标记在视图层上查看这些对象时,我没有得到任何东西。
订单型号
@Entity
@Table(name = "bees_address")
public class Address {
@OneToOne
@JoinColumn(name = "paymentAddress")
private Address payment;
@OneToOne
@JoinColumn(name = "deliveryAddress")
private Address payment;
@Column(name = "deliveryCharge")
private Integer deliveryCharge;
...
地址模型
@Entity
@Table(name = "bees_address")
public class Address {
@Size(min=2, max=150)
@Column(name = "line1", length = 150)
private String line1;
...
控制器
public String updateDelivery(HttpServletRequest request, @ModelAttribute("basket") Order basketUpdate) {
Address deliveryAddress = basketUpdate.getDeliveryAddress();
if (!Validate.isValid(request, deliveryAddress)) {
logger.info("Delivery address does not validate");
return "redirect:/checkout/delivery";
} else {
/* do stuff here */
}
return "redirect:/checkout/payment";
}
public static Boolean isValid(HttpServletRequest request, Address address) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Address>> constraintViolations = validator.validate(address);
request.getSession().setAttribute("formErrors", constraintViolations);
return constraintViolations.size() < 1;
}
JSP结构
<form:form action="${url}" method="post" modelAttribute="basket"
Charge: <form:input path="deliveryCharge" />
Address: <form:input path="deliveryAddress.line1" />
<form:error path="deliveryAddress.line1" />
...
非常感谢
答案 0 :(得分:1)
我认为你所追求的是验证组。它们允许您分几步验证不同的约束集。
通过定义接口并将约束分配给一个或多个组来声明所需的组:
public interface DeliveryChecks{}
public interface PaymentChecks{}
public class Address {
@NotNull(groups = PaymentChecks.class)
private Address payment;
@Min(value=5, groups = DeliveryChecks.class)
private Integer deliveryCharge;
...
}
然后通过将组标识符传递给validate()
来验证每个表单或页面所需的组:
Set<ConstraintViolation<Address>> constraintViolations =
validator.validate(address, PaymentChecks.class);
Hibernate Validator reference guide提供了有关此主题的更多信息。