我制作了一个自定义验证器来检查语言环境。 我想在url路径参数中使用它。
[ValidLocale]
@Target({ElementType.PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = ValidLocaleValidator.class)
@Documented
public @interface ValidLocale {
String message() default "Locale";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
[ValidLocaleValidator]
public class ValidLocaleValidator implements ConstraintValidator<ValidLocale, String> {
private Set<String> validLocales = new HashSet<String>();
@Override
public void initialize(ValidLocale constraintAnnotation) {
Locale[]locales = Locale.getAvailableLocales();
for (java.util.Locale l : locales) {
validLocales.add(l.toString());
}
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
System.out.println("is valid start");
if(!validLocales.contains(value)){
return false;
}
return true;
}
}
我想在这里使用。
@GetMapping("/player-messages/players/{id}/messages/{messageId}/locale/{locale}")
@Timed
public ResponseEntity<List<PlayerMessageViewDTO>> getPlayerMessage(
@PathVariable String id, @PathVariable Long messageId, @PathVariable @ValidLocale final String locale) {
.....
return something;
}
如果我发送语言环境值'aa',我想返回FAIL。