2017-05-04 41 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