1.添加依赖jar
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.1.Final</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency>
2.添加spring 支持
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
3.java bean中添加注解
public class Company { @Length(max = 32) @NotNull private String id; @Length(max = 40,message = "微信openId长度不能大于40") private String openid; @NotNull @Length(max = 30) private String name; }
4.spring controller中添加Valid注解
public JSONView submit(@Valid Company company,BindingResult bindingResult){ //codes }
BindingResult注解必须在@Valid 参数后面
5.最后
然后在访问submit这个方法的时候就会自动根据bean定义的规则验证。验证结果放在bindingResult中