I can't seem to get basic validation working with Spring MVC.
I have the following POJO:
public class Example {
@NotNull(message="You must enter a value")
@Size(min=2, max="2", message="You must enter 2 characters")
private String value;
public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
}
My very basic controller looks like this:
@Controller
@RequestMapping("/value.vm")
public class ValueController {
@Autowired
private Validator validator;
@RequestMapping()
public ModelAndView display(@Valid @ModelAttribute("example") Example e, BindingResult result) {
//Details omitted
}
My velocity template is equally as simple:
<form target="_self" enctype="application/x-www-form-urlencoded" action="/value.vm" method="post">
#springBind("example")
#springFormInput("example.value", "")
#springShowErrors("<br />", "")
</form>
My servlet.xml file includes:
<mvc:annotation-driven />
If I manually validate a blank form submission (ie validator.validate(e)), I see that my error messages are being generated, however they never exist on my BindingResult.
Any ideas why my binding result is not getting these errors?
I was mistakenly using:
javax.validation.Validator
When I needed to be using
org.springframework.validation.Validator
Changing to this version, and modifying the validation code to:
validator.validate(e, result);
solved my problem.
You can still use JSR 303 @Valid annotation to automatically invoke validation using javax.validation.Validator without invoking it manually.
This is enabled by default by spring if you include <mvc:annotation-driven/>
element to your application context or @EnableWebMvc when you are using Java config
For this to work you need to have an implementation for Bean Validation API eg Hibernate Validator
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.