users@jersey.java.net

Re: [Jersey] Using JSR-303 (bean validation) with Jersey

From: James Strachan <james.strachan_at_gmail.com>
Date: Tue, 14 Apr 2009 12:15:39 +0100

2009/4/10 Tatu Saloranta <tsaloranta_at_gmail.com>:
> Quick question: I am planning to use hibernate-validation (impl of
> JSR-303) with my Jersey service, and it looks like a very good match
> if things work as planned. I can do this easily from my resources, and
> that's good enough for immediate use.
>
> But it also seems like aspect that could be quite easily added to
> generic handling: for example, if bound input argument fails
> validation, a 4xx error could be returned.
>
> So I was wondering if:
>
> (a) There is already a natural place for hooking this in (by adding a filter?)
> (b) If not, is this something for which a simple hook could be added.
> Probably not JSR-303 specific.

BTW I guess it does depend a little on what kind of thing you want to do.

e.g. if its a POST of JSON/XML then you probably just wanna return a
validation 4xx error - but you might want to also encode the
validation errors in the result? If its posting a web form (typically
from a browser), you might want to just re-render the same page with
errors highlighted for the user so they can see whats wrong.

For the latter case, injecting the validator is probably the easiest...

  @Inject
  Validator validator;

    @POST
    @Consumes("application/x-www-form-urlencoded")
    public Response postForm(Form formData) {
       MyDTO dto = ...;
       // lets store the errors in a field so they can be viewed
       this.errors = validator.validate(dto);
       if (errors.isEmpty()) {
         return Response.seeOther(someNewUri).build();
       else {
            // lets re-render the form
            return Response.ok(new Viewable("index", this)).build();
       }
  }

I guess returning the 4xx and maybe rendering the errors as XML/JSON
could be a useful interceptor though (maybe annotating the method with
@Validate or something to indicate you want to use it?)

-- 
James
-------
http://macstrac.blogspot.com/
Open Source Integration
http://fusesource.com/