2017-05-04 60 views
0

我在Spring Boot中使用Hibernate验证器。我在下面注解的类中有一个变量。访问Hibernate验证器消息

Public class User { 

@Pattern(regexp="[email protected]+\\..+", message="Wrong email!") 
private String userEmail; 

} 

我在控制器中使用验证。

@PostMapping("/users") 
public ResponseEntity addUser(@Valid @RequestBody User user, BindingResult result) { 

    if(result.hasErrors()) { 
     log.info("There are errors in the input"); 
    } 

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); 
     Validator validator = factory.getValidator(); 
     Set<ConstraintViolation<User>> inputErrors = validator.validate(user); 

     log.info("Errors: " + inputErrors.toString()); 
} 

是否有更容易的方式访问验证消息,然后通过工厂?喜欢的东西

result.getMessage(); 

回答

0

可以自动装配消息源到控制器

@Autowired 
private MessageSource messageSource; 

,看到消息

messageSource.getMessage(<your key from the error>, null, locale); 

您斯内德区域得到妥善本地化的文本。您需要迭代错误以获取所有发现的验证错误的所有消息。

+0

在我的情况下,密钥是'userEmail'吗?有没有一种检索区域​​设置的好方法? – g3blv