clbcabral
clbcabral

Reputation: 503

Bean Validation for POST requisition in JAX-RS with Jersey implementation

I'm using the Jersey implementation for JAX-RS, and I was looking for an example where I can use the Bean Validation in POST requisitions. I have this operation, for example:

@POST
@Path("document/annotations/save")
@Produces("application/json")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Map<String, Object> saveAnnotation(
        @FormParam("user") String userStr,
        @FormParam("documentId") String documentId,
        @FormParam("documentPage") Integer documentPage,
        @FormParam("annotationContent") String annotationContent,
        @FormParam("annotationId") Long annotationId,
        @FormParam("isMobile") Boolean isMobile) { // the code... }

I wanna use validations constraints (@NotNull, @Pattern, etc) for each method param. I saw this doc where they're using the Seam Framework to do that.

Currently, I'm trying to use the javax.validation implementation to validate my requests, but it doesn't working.

Is there a way to use the JSR-303 specification with JAX-RS?

Tnks.

Upvotes: 4

Views: 6147

Answers (2)

James
James

Reputation: 1571

This is currently not possible using Jersey; one possible alternative is to write a customer resource filter and bind to the @NotNull, etc. annotations.

It would be simpler if it was encapsulated in a resource class because you could then bind to a @Valid annotation on your method and validate the bean in one shot.

Because JSR-303 is designed to deal with beans and not a collection of parameters then it ends up being very verbose when you try to bend it to your will.

IMHO it's better not to keep validation inside your class anyway and to either use the pipes and filters pattern, i.e. ContainerRequestFilter, or to use something like AspectJ as @Willy suggested.

Upvotes: 2

Related Questions