使用自定义验证输入验证

时间:2017-10-06 09:59:24

标签: java validation spring-boot

自定义注释,定义为https://dzone.com/articles/bean-validation-and-jsr-303

我们可以在控制器中使用@Capitalized注释吗?

e.g。

 @RestController

public class Abc {

@RequestMapping(value="/abc", method=RequestMethod.POST)

public String abc(@Capitalized @RequestParam(value="abc") String abc) {



}

}

我用这种方式,但它不起作用。知道为什么它不起作用吗?

谢谢,

3 个答案:

答案 0 :(得分:0)

在注释目标中添加Parameter ElementType,然后就可以了。

E.g:

@Target(ElementType.PARAMETER)

答案 1 :(得分:0)

假设@Capitalized是:

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CapitalizedValidator.class)
@Documented
public @interface Capitalized {

    String message() default "should be capital";

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

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

你有一个约束验证impl:

public class CapitalizedValidator implements ConstraintValidator<Capitalized, String> {

    private String message;
    @Override
    public void initialize(Capitalized constraintAnnotation) {
        message = constraintAnnotation.message();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        String inUpperCase = value.toUpperCase();

        if (inUpperCase.equals(value)) {
            return true;
        }

        context.buildConstraintViolationWithTemplate(message);

        return false;
    }

}

然后和你一起试试这个:

@Validated
@RestController
public class SampleController {

    @RequestMapping(method = RequestMethod.POST)
    public String post(@Capitalized @RequestParam("content") String content) {
        return content;
    }

}

答案 2 :(得分:0)

在Application.java中包含以下代码后,其工作正常。

@Bean
    public Validator validator() {
return new LocalValidatorFactoryBean();
 }

  @Bean
   public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setValidator(validator());
return methodValidationPostProcessor;

}