users@jersey.java.net

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

From: Tatu Saloranta <tsaloranta_at_gmail.com>
Date: Tue, 14 Apr 2009 09:20:02 -0700

On Tue, Apr 14, 2009 at 4:15 AM, James Strachan
<james.strachan_at_gmail.com> wrote:
> 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.

Certainly.

> 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

Exactly. This is my use case: get in the request, validate, collect
all (or up to N at least) problems, return along as part of response.

This is also where jsr-303 seems bit too geared towards
submit-the-form use case, which leads to localization & formatting
challenges which I am not interested in. This because all that can be
done at another layer, validation IMO should just give you codes. But
I digress. :)

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

Yup.

> For the latter case, injecting the validator is probably the easiest...
>
> @Inject
> Validator validator;

Sounds like it yes. So just need to register validator type.
Fortunately it need not be typed (i.e. validators are not
genericized), so that's quite easy.

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

I think it might be.

It also looks like hibernate validator is still bit work in progress
(with some unnecessary logging warnings etc), but I like the potential
here.
It does seem like a natural fit with JAX-RS.

-+ Tatu +-