Spring Boot。我有一个验证参数的服务
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/1.0.13/webcomponents-lite.js" type="text/javascript"></script>
</head>
<body>
<h1>Hello, worssld</h1>
<div id="ff"></div>
<script src="sc.js" type="text/javascript"></script>
</body>
</html>
验证的字段是e。 G。
@Override
public void registerUser(
@Valid RegisterDTO registerDTO
) {
然后我设置ExceptionHandler来获取此异常
@NotEmpty
@Pattern(regexp = "[a-zA-Z0-9_-]{6,36}")
private String username;
我有一个validationMessages。属性文件,我保留我的错误消息
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ValidationErrorDTO processValidationError(ConstraintViolationException ex) {
ValidationErrorDTO validationErrorDTO = new ValidationErrorDTO();
Set<ConstraintViolation<?>> set = ex.getConstraintViolations();
for (Iterator<ConstraintViolation<?>> iterator = set.iterator();iterator.hasNext(); ) {
ConstraintViolation<?> next = iterator.next();
validationErrorDTO.getFieldErrors()
.add(new ErrorFieldDTO(((PathImpl)next.getPropertyPath()).getLeafNode().getName(),
next.getMessage()));
}
return validationErrorDTO;
}
但是,此操作的结果似乎是 https://zapodaj.net/d1a4f695e6a7d.png.html
不从中检索本地消息。属性文件。
如何设置要从属性文件下载的本地消息?
答案 0 :(得分:0)
好吧,你必须为Hibernate配置自定义验证消息。第一个bean将验证消息的位置配置为自定义validationMessages
文件(使用任何名称)。在WebMvcConfigurerAdapter
中,您可@Override
getValidator()
方法返回自定义验证程序。
@Bean(name = "messageSource")
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource rrbms = new ReloadableResourceBundleMessageSource();
rrbms.setBasename("classpath:validationMessages");
rrbms.setDefaultEncoding("UTF-8");
return rrbms;
}
@Bean(name = "validator")
public LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean lvfb = new LocalValidatorFactoryBean();
lvfb.setValidationMessageSource(messageSource());
return lvfb;
}
@Override
public Validator getValidator() {
return validator();
}
由于您可以使用默认名称validationMessages.properties
或使用WebConfigurationSupport
,因此最小设置为:
@Override
public Validator getValidator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource());
return validator;
}
无论如何,您使用message
引用到正确的属性。
@Pattern(regexp = "[a-zA-Z0-9_-]{6,36}", message="{Pattern.registerDTO.username}")
一个好的做法是不根据它正在验证的字段命名属性,而是根据验证的类型命名。
validation.notEmpty=This field is required.
validation.pattern.username=Please enter at least 6 characters(max. 36 characters). Only letters, numbers and special characters '_' and '-'.
validation.pattern.email=...
validation.pattern.phone=...
validation.size=...