约束球衣2的注释不起作用

时间:2016-05-23 14:04:05

标签: java jersey jersey-2.0

我按照Jersey User Guide - bean-validation中的步骤操作,并在下面添加到pom.xml;

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-bean-validation</artifactId>
    <version>2.22.2</version>
</dependency>

然后我尝试在API中使用约束注释

@Path("shows")
public Response getShows(
        @NotNull @QueryParam("cid") Long cid,
        @Valid @QueryParam("sort_by") @ValidSortBy(modalClass=Show.class) List<String> sortBy,
        @QueryParam("limit") @DefaultValue("100") @Max(1000) int limit,
        @Context UriInfo uriInfo
)

但调用http://0.0.0.0:8080/api/v1/shows?limit=10001时@NotNull和@Max都不起作用。我不知道原因,然后我尝试自定义一个名为@ValidSortBy的验证器(用于参数'sortBy')

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ValidSortByValidator.class)
public @interface ValidSortBy {
    String message() default "";

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

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

    Class<? extends BaseModal>[] modalClass() default {};
}

public class ValidSortByValidator implements ConstraintValidator<ValidSortBy, List<String>> {
    Class<? extends BaseModal> modalClass;

    @Override
    public void initialize(ValidSortBy annotation) {
        System.out.println("aaaaaaaaa initialize");
        if (annotation.modalClass().length > 0) {
            modalClass = annotation.modalClass()[0];
            System.out.println(modalClass.getTypeName());
        }
    }

    @Override
    public boolean isValid(List<String> sortBy, ConstraintValidatorContext context) {
        return false;
    }
}

但即使没有任何输出。

谁能告诉我原因?非常感谢你!

resourceConfig是这样初始化的,没有web.xml

final ResourceConfig resourceConfig = new ResourceConfig();

resourceConfig.packages([package names]);
resourceConfig.property("jersey.config.server.wadl.disableWadl", true);
resourceConfig.property(ServerProperties.BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECK, true);

registerResourceConfig(resourceConfig); // register some error mappers

ServletContainer servletContainer = new ServletContainer(resourceConfig);
ServletHolder servletHolder = new ServletHolder(servletContainer);

servletHolder.setInitOrder(1);
servletHolder.setInitParameter("jersey.config.server.tracing", "ALL");

ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
servletContextHandler.setSessionHandler(new SessionHandler());
servletContextHandler.setContextPath("/");

servletContextHandler.addServlet(servletHolder, "/*");

addServletFilters(servletContextHandler);

return servletContextHandler;

1 个答案:

答案 0 :(得分:2)

我通过手动注册验证解决了这个问题。下面的代码添加在registerResourceConfig

resourceConfig.register(org.glassfish.jersey.server.validation.ValidationFeature.class);