RequestParam的自定义验证不适用于Spring MVC [英] Custom validation for RequestParam doesn't work with Spring MVC

查看:860
本文介绍了RequestParam的自定义验证不适用于Spring MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用Spring MVC进行自定义验证。我为它实现了自己的参数和自定义验证器注释(所有都在下面给出),但验证永远不会发生。任何想法都会非常感激。

I can't make custom validation working with Spring MVC. I implemented own annotation for parameter and custom validator for it (all is given below), but validation never happens. Any ideas would be really appreciated.

控制器

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

}


推荐答案

似乎我在这里弄错了。因为我使用Spring Boot,所以它默认使用hibernate验证器。为了解决这个问题,我遵循了这个的答案,并通过添加bean来改变我的Spring配置。

Seems I got what is wrong here. Because I use Spring Boot, it uses hibernate validator by default. To fix this, I followed this answer and just changed my Spring configuration with adding the beans.

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

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

这篇关于RequestParam的自定义验证不适用于Spring MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆