使用自定义@ValidCode注释验证RequestParam并不起作用

时间:2016-12-01 20:54:17

标签: spring-mvc spring-boot hibernate-validator spring-validator

使用自定义验证注释验证RequestParam @ValidCode不起作用。但如果使用@Pattern而开始工作。我做错了什么,拜托?

控制器:

@Validated
@RestController
public class MyEndpoint {
    @RequestMapping(path = "/test", method = GET)
    public MyResponse findItems(@ValidCode @RequestParam("code") String code) {
        return new MyResponse("A001");
    }
}

我的验证注释:

@Retention(RUNTIME)
@Target({FIELD, PARAMETER})
@Pattern(regexp = "^[A-Z0-9]{4}?$")
public @interface ValidCode {
    String message() default "{ValidCode.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Web MVC配置:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Bean
    public Validator validator() {
        return new LocalValidatorFactoryBean();
    }

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

的pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
        <relativePath></relativePath>
    </parent>

    ...

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        ...
    </dependencies>
</project>

如果我按照方式更改控制器方法验证开始工作:

@RequestMapping(path = "/test", method = GET)
public MyResponse findItems(@Pattern(regexp="^[A-Z0-9]{2}?$") @RequestParam("code") String code) {
    return new MyResponse("A001");
}

非常感谢提前。

0 个答案:

没有答案