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