SpringMVC使用校验validator校验对象属性

时间:2022-02-11 04:46:56

1.pom.xm添加依赖

<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>

2.配置文件.xml

<!-- 校验参数 -->
<bean id="commonProvider.messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:message/message</value>
<value>classpath:org/hibernate/validator/ValidationMessages</value>
</list>
</property>
<!--默认为false,这样当Spring在ResourceBundle中找不到messageKey的话,就抛出NoSuchMessageException, 把它设置为True,则找不到不会抛出异常,而是使用messageKey作为返回值。-->
<property name="useCodeAsDefaultMessage" value="false"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="cacheSeconds" value="600"/>
</bean> <bean id="commonProvider.validatorFactory" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
<property name="validationMessageSource" ref="commonProvider.messageSource"/>
</bean> <bean id="commonProvider.validator" factory-bean="commonProvider.validatorFactory" factory-method="getValidator"/>
<!-- 参数校验 -->
<bean id="commonProvider.paramCheckLogic" class="com.jd.m.cms.bjshare.common.handler.logic.ParamCheckLogic">
<property name="messageSource" ref="commonProvider.messageSource" />
<property name="validator" ref="commonProvider.validator" />
</bean>

3.对象.java

public class test {
@NotNull(message = "测试id不能为空", groups = { First.class })
private String id;
@NotNull(message = "测试name不能为空", groups = { Second.class })
private String name; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
}
public test(){} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public test(String id, String name) {
this.id = id;
this.name = name;
}
public interface First { }
public interface Second { }

4.调用

1).
public <T> T checkObjParamValidate(@NotNull T t, Class<?>... groups) {
2).
.checkObjParamValidate(test,com.jd.bjshare.domain.test.First.class,com.jd.bjshare.domain.test.Second.class);
3).
validator.validate(t, groups);

5.页面返回结果

{"code":1,"msg":"测试id不能为空,测试name不能为空","data":{}}