custom validator 질문있습니다.

55 views
Skip to first unread message

이장군

unread,
Jun 6, 2019, 4:48:04 PM6/6/19
to Korea Spring User Group Q&A
안녕하세요, 
spring-boot 기반으로 이것저것 진행중입니다.

Locale 구분하는 custom validator를 예제를 참고하여 만들었습니다. 
이걸 url에 pathParameter에서 validation을 하고 싶은데 제대로 작동하지 않아서요.
어떤 부분이 부족한지 같이 고민 부탁드립니다.



@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RUNTIME)
@Constraint(validatedBy = ValidLocaleValidator.class)
@Documented
public @interface ValidLocale {
   
String message() default "Locale";

   
Class<?>[] groups() default {};

   
Class<? extends Payload>[] payload() default {};
}


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;
   
}
}



아래는 실제 사용해 보려고 한 api입니다.

@GetMapping("/player-messages/messages/{messageId}/locale/{locale}")
@Timed
public ResponseEntity<List<PlayerMessageViewDTO>> getPlayerMessage(
   
@PathVariable Long messageId,
   
@PathVariable @ValidLocale final String locale) {
   
log.debug("Request to get MessageId:{}, Locale:{}", messageId, locale);
   
List<PlayerMessageViewDTO> viewDTO = playerMessageService.getPlayerMessagesByLocale(messageId, locale);
   
return new ResponseEntity<List<PlayerMessageViewDTO>>(viewDTO, HttpStatus.OK);
}



아래는 기존 api.

@GetMapping("/player-messages/messages/{messageId}/locale/{locale}")
@Timed
public ResponseEntity<List<PlayerMessageViewDTO>> getPlayerMessage(
   
@PathVariable Long messageId,
   
@PathVariable final String locale) {
   
log.debug("Request to get MessageId:{}, Locale:{}", messageId, locale);
     //validate locale
    if (!validateLocale(locale))
       
return ResponseEntity.badRequest().body(null);
   List<PlayerMessageViewDTO> viewDTO = playerMessageService.getPlayerMessagesByLocale(messageId, locale);
   
return new ResponseEntity<List<PlayerMessageViewDTO>>(viewDTO, HttpStatus.OK);
}

private boolean validateLocale(@PathVariable String locale) {
   
//validate locale
    try {
       
LocaleUtils.toLocale(locale);
   
} catch (Exception e) {
       
return false;
   
}
   
return true;
}




Reply all
Reply to author
Forward
0 new messages