Reputation: 1209
I followed steps from Jersey User Guide - bean-validation, and add below to pom.xml;
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-bean-validation</artifactId>
<version>2.22.2</version>
</dependency>
Then I tried to use constraint annotation in the 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
)
But both @NotNull and @Max don't work when http://0.0.0.0:8080/api/v1/shows?limit=10001 is called. I don't know the reason, then I tried to custom a validator called @ValidSortBy(used for parameter '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;
}
}
But there even isn't any output.
Can anyone tell me the reason? Thank you a lot!
The resourceConfig is initialized like this and there isn't 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;
Upvotes: 0
Views: 556
Reputation: 1209
I solved it by register validation manually. Below code is added in registerResourceConfig
resourceConfig.register(org.glassfish.jersey.server.validation.ValidationFeature.class);
Upvotes: 2