问题
I am trying to set up Hibernate Validation in my ecommerce site. I have an order object with multiple objects assigned. As the customer goes through the checkout, I want to be able to individually validate these objects - sometimes multiple objects with one form.
For example, upon submitting the delivery form, the deliveryCharge and deliveryAddress should be validated. If this validation fails, the delivery form will be returned with a list of validation errors.
I can validate the objects via a java implementation, however when I try to view these on the view tier using <form:error />
tag, I am not getting anything.
Order Model
@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;
...
Address Model
@Entity
@Table(name = "bees_address")
public class Address {
@Size(min=2, max=150)
@Column(name = "line1", length = 150)
private String line1;
...
Controller
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";
}
Validation Hibernate Validation Docs
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 Structure
<form:form action="${url}" method="post" modelAttribute="basket"
Charge: <form:input path="deliveryCharge" />
Address: <form:input path="deliveryAddress.line1" />
<form:error path="deliveryAddress.line1" />
...
Many thanks
回答1:
I think what you are after is validation groups. They allow you to validate different sets of constraints in several steps.
Declare the required groups by defining interfaces and assign your constraints to one or more groups:
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;
...
}
Then validate the required group(s) for each form or page by passing the group identifiers to validate()
:
Set<ConstraintViolation<Address>> constraintViolations =
validator.validate(address, PaymentChecks.class);
The Hibernate Validator reference guide has more information on this topic.
来源:https://stackoverflow.com/questions/18442969/custom-error-messaging-on-hibernate-validation