建议您仔细阅读参考资料的相关部分。您创建实现 Validator 接口的验证器:
public class FooValidator implements Validator {
/**
* This Validator validates *just* Foo instances
*/
public boolean supports(Class clazz) {
return Foo.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Foo foo = (Foo) obj;
if (!isNumeric(foo.getFieldThatShouldBeNumeric())
{
e.rejectValue("fieldThatShouldBeNumeric", "notnumeric");
}
}
}
然后将其“本地”注入控制器本身:
@Controller
public class MyController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new FooValidator());
}
@RequestMapping("/foo", method=RequestMethod.POST)
public void processFoo(@Valid Foo foo) { ... }
或“全球”:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven validator="globalValidator"/>
</beans>