1.pom.xml
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.web/el-impl -->
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>el-impl</artifactId>
<version>2.2</version>
</dependency>
注意:如果异常提示:
java.lang.ClassNotFoundException: com.sun.el.ExpressionFactoryImpl
很可能是少el-impl依赖
2.消息文件是什么?
默认是:ValidationMessages.properties,我发现也有用:ValidatorMessages.properties,当然文件可以随意命名,不是默认的文件名的话要自已设置messageInterpolator,hibernate validation文档很全.可以多看看
3.消息文件放在哪?
3.1 用spring可以放在classpath,也可以放到WEB-INF下,需要在相应的配置文件中配一个ReloadableResourceBundleMessageSource bean.
3.2 maven项目和SE下放到资源文件中
项目名/src/main/resources
布署时如需要布到其它路径可以用maven插件
3.3 验证消息文件是否路径正确?
import java.util.Locale;
import java.util.ResourceBundle;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.validator.resourceloading.PlatformResourceBundleLocator;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author xiaofanku
*/
public class hibernateResourceTest {
private Validator validator;
@Before
public void setUp() {
ValidatorFactory factory=Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
//项目名/src/main/resources/ValidationMessages_zh_CN.properties
@Test
public void hello() {
PlatformResourceBundleLocator prbl=new PlatformResourceBundleLocator( "ValidationMessages" );
ResourceBundle rb=prbl.getResourceBundle(Locale.CHINESE);
//资源文件测试
assertTrue(rb.containsKey("NotNull.artilceForm.title"));
}
}
4.错误消息的内容
4.1类中
public class Car {
@NotNull(message = "The manufacturer name must not be null")
private String manufacturer;
}
4.2在消息文件(ValidationMessages.properties)中
4.2.1 注解是hibernate.validator.constraints
validator.notEmpty=属性需要一个输入值
4.2.2 注解是javax.validation.constraints
javax.validation.constraints.NotNull.message=这是一个必填的输入
4.2.3 自定义的constraints
[Example 63. Defining a custom error message for the CheckCase constraint](http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#validator-customconstraints)
4.3针对属性自定义消息
类:
public class ArticleForm {
@NotNull(message="{NotNull.artilceForm.title}")
private String title;
}
消息文件:
NotNull.artilceForm.title=标题不可以为空
5.学习资源:
Hibernate Validator 5.4.1.Final - JSR 349 Reference Implementation: Reference Guide