Spring 配置使用@Valid注解
依赖jar包
1 2 3
| [group: "org.hibernate", name: "hibernate-validator", version: "${vHibernateValidator}"] [group: "org.springframework", name: "spring-webmvc", version: "${vSpringFramework}"], [group: "org.springframework", name: "spring-context-support", version: "${vSpringFramework}"],
|
Spring配置
1 2 3 4 5 6 7 8 9
| <context:annotation-config/> <mvc:annotation-driven/> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> </bean>
|
Java代码
1 2 3 4
| @RequestMapping(value = "/xxx", method = RequestMethod.POST) public String add(@Valid @ModelAttribute Person person, BindingResult validResult, ModelMap modelMap) { ... }
|
需要注意的是@Valid注解后面必须紧挨着BindingResult,否则Request会匹配不上,然后报404