【发布时间】:2011-05-25 16:31:04
【问题描述】:
我有一个为采购订单建模的模型对象。采购订单有几个字段(例如 ID 和日期)和一个行项目列表作为 ArrayList。我可以验证父采购订单,但验证订单项时会卡住。
谁能帮我验证复杂的对象?如果我不能自动验证复杂对象,我该如何编写一个自定义验证器,它依赖于父级中的约束注释,然后迭代子行项?这个验证器实例需要能够调用something.validate(purchaseOrder) 和(对于每个行项目)something.validate(lineItem)。我从哪里得到“东西”?
我在dispatcher-servlet 中指定了<mvc:annotation-driven />。我没有使用@InitBinder。我正在使用@Valid 注释在控制器的方法中进行验证,例如
@RequestMapping(params="confirmPurchaseOrder")
public String confirm(
@ModelAttribute("purchaseOrder") @Valid PurchaseOrder purchaseOrder,
BindingResult result,
@RequestParam("account") String accountString,
@RequestParam("division") String divisionString,
Model model)
{
if (result.hasErrors()) {
return PURCHASE_ORDER_CREATE_VIEW;
}
域类如下所示:-
public class PurchaseOrder implements Comparable<PurchaseOrder> {
/** Based on GUID */
private String id;
/** SOP */
@NotNull
private Integer SOP;
/** Reference from client */
@NotBlank
private String purchaseOrderReference;
/** PO date */
@DateTimeFormat(style="S-")
@NotNull
private Date date;
@Valid
private final Collection<LineItem> lineItems = new ArrayList<LineItem>();
和
public class LineItem {
...Elided
/** Generated from GUID */
private String id;
@NotNull
@DateTimeFormat(style="S-")
@Future
private Date expiry;
private String softwareVersion;
@NotNull
@NumberFormat(style = Style.NUMBER)
@Min(1)
private Integer licenceCount;
提交有效期为空的采购订单时,出现以下异常:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'lineItems[]' of bean class [com.nit.ols.domain.PurchaseOrder]: Invalid index in property path 'lineItems[]'; nested exception is java.lang.NumberFormatException: For input string: ""
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:730)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
【问题讨论】:
标签: validation spring-mvc bean-validation