BaiFan
文章目录
  1. 1. 依赖jar包
  2. 2. Spring配置
  3. 3. Java代码

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/>
<!-- 以下 validator ConversionService 在使用 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

文章目录
  1. 1. 依赖jar包
  2. 2. Spring配置
  3. 3. Java代码