Spring javax.validation annotation not caught in BindingResult
I am trying to add validation to my model objects (which double as my form backing beans) using javax.validation annotations.
My model looks like this:
public Class TestObject {
private String myProp;
private InnerObject innerObject;
//getters and setters omitted
}
public Class InnerObject {
private BigDecimal myValue;
@NotNull
public BigDecimal getMyValue();
}
In my controller I have the method call like this:
public View calculate(@ModelAttri开发者_如何学编程bute("testObject") @Valid TestObject testObject, BindingResult result)
I also have the <mvc:annotation-driven/>
in my spring-servlet.xml file.
Everytime I run the form with a null value it tells me there are 0 binding result errors.
I am using Java 1.6 with Hibernate-Validator-4.2.0 and Validation-API-1.0.0 on my classpath.
Can anyone help me and let me know what I am doing wrong? Been playing around with this for a while and can't get it to work.
Thanks
You are not referencing your InnerObject class. Your controller is taking a TestObject, but the field "innerObject" of the class TestObject is of type String.
Ok, getting a little further with this. I noticed that I was still using a custom validator in my controller like this:
binder.setValidator(new CustomValidator());
So I removed it and then I added @Valid above the getter on my inner object like:
@Valid
public InnerObject getInnerObject();
Now I can see that there are binding errors in my code. I have a new problem though. I have @NotNull on a BigDecimal property and I get the following error
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.UnexpectedTypeException: No validator could be found for type: java.math.BigDecimal
From the documentation it looks like BigDecimal is supported. So not sure what is going on. Think I am getting closer though.
Ok to resolve the BigDecimal error I changed:
private BigDecimal myField;
to
private BigDecimal myFeild = BigDecimal.Zero;
It works properly now.
The only downside is that since these are my form backing objects a zero is displayed in the field initially instead of a blank.
I am not sure if there is any way around this?
精彩评论