Bean Validator扩展
Bean Validator扩展
1、需求
在使用validator时,有个需求就是公用错误提示信息,什么意思?
举个例子:
@NotEmpty非空判断,在资源文件中我不想每个非空判断都写”不能为空“,只需要写”###“,然后提示信息自动会变成”###不能为空“
代码:
public class {
//资源文件中user.name.empty=用户名
2、实现方式
有两种实现方式
方式一:手动调用验证方法
注解
验证器
//验证器
public class MyValidator {
private static final Logger log = LoggerFactory.getLogger(HybValidator.class);
private static Validator validator = null;
private static MessageInterpolator msgInterpolator = null;
static {
if (validator == null) {
LocalValidatorFactoryBean factory =
(LocalValidatorFactoryBean) ApplicationContextUtil.getBean("validator");
validator = factory.getValidator();
msgInterpolator = factory.getMessageInterpolator();
}
}
public static HybValidatorResult validate(Object object, Class<?>... groups) {
HybValidatorResult result = new HybValidatorResult();
Set<ConstraintViolation<Object>> violations = validator.validate(object, groups);
Map<String, String> map = new HashMap<>();
if (CollectionUtils.isEmpty(violations)) {
result.setErrors(false);
} else {
result.setErrors(true);
for (ConstraintViolation<Object> violation : violations) {
String path = violation.getPropertyPath().toString();
String message = violation.getMessage();
if (StringUtils.isBlank(path) || StringUtils.isBlank(message) || map.containsKey(path))
continue;
message = resolveMessage(message);
map.put(path, message);
}
result.setItems(map);
}
return result;
}
private static final Pattern elpattern = Pattern.compile("\\{[^{}]+\\}");
private static String resolveMessage(String message) {
Matcher matcher = elpattern.matcher(message);
try {
while (matcher.find()) {
String el = matcher.group();
//用资源文件信息替换message = {key}{my.empty.message}
//注解这里的key会替换成注解NotEmpty定义的key,即
//message = {user.name.empty}{my.empty.message}