2016-05-23 58 views
0

我按照Jersey User Guide - bean-validation的步驟操作,並在下面添加到pom.xml;球衣2的限制註釋不起作用

<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 
) 

但@NotNull和@Max既當http://0.0.0.0:8080/api/v1/shows?limit=10001被稱爲不起作用在使用約束註解。我不知道原因的話,我想自定義(用於參數「sortBy」)一個名爲@ValidSortBy驗證

@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

我通過寄存器驗證手動解決它。下面的代碼添加到registerResourceConfig

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

我找不到禁用此功能的任何地方,但手動註冊確實有效。 – Cuero