2
我無法使用Spring MVC進行自定義驗證。我爲它的參數和自定義驗證器實現了自己的註釋(全部在下面給出),但驗證從不發生。任何想法將非常感激。RequestParam的自定義驗證不適用於Spring MVC
控制器
@Validated
@RestController
public class FooController {
@RequestMapping(value = "/somepath",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public String get(@CustomParam @RequestParam(String fooParam) {
return "Hello";
}
}
自定義請求參數
@Documented
@Constraint(validatedBy = CustomValidator.class)
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomParam {
String message() default "Wrong!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
自定義驗證
@Component
public class CustomValidator implements ConstraintValidator<CustomParam, String> {
@Override
public void initialize(CustomParam param) {}
@Override
public boolean isValid(String givenParam, ConstraintValidatorContext context) {
// some custom validation is here, never enter this method though
}
}