users@jersey.java.net

Re: [Jersey] Access to HttpServletRequest from custom parameter class

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Mon, 30 Mar 2009 11:04:40 +0200

Hi Daniel,

The HttpServletRequest.getLocale(), which is equivalent to the JAX-RS
HttpHeaders.getAcceptableLanguages(), returns the value of the Accept-
Language header. For HttpServletRequest.getLocale(), if the Accept-
Language header is absent then the default locale for the server
returned.

I think you are mixing layers incorrectly. IMHO Accept-Language header
should not influence how you process a URI query parameter. That
header declares what is the most acceptable locale for a response.

If you require the default locale for the server i recommend you use a
another mechanism to obtain it. Or if you require the client to send a
locale for processing the URI then that locale should be in the URI,
say as another query parameter.


Putting aside the layering issue you are right to consider using the
StringReader and StringReaderProvider:

https://jersey.dev.java.net/nonav/apidocs/1.0.3-SNAPSHOT/jersey/com/sun/jersey/spi/StringReaderProvider.html
https://jersey.dev.java.net/nonav/apidocs/1.0.3-SNAPSHOT/jersey/com/sun/jersey/spi/StringReader.html

You could create a StringReaderProvider<Bar>, for example:

   public class BarStringReaderProvider implements
StringReaderProvider<Bar> {

     @Context UriInfo ui;

     public StringReader<Bar> getStringReader(Class<?> type, Type
genericType, Annotation[] annotations) {
       if (type != Bar.class) return null;

       return new StringReader<Bar>() { ... };
     }
   }

Paul.


On Mar 27, 2009, at 8:49 PM, Daniel Larsson wrote:

> Hi,
>
> I recently ran into a "problem" with a custom parameter class for a
> QueryParam, e.g.
>
> @GET
> public getFoo(@Context HttpServletRequest r, @QueryParam("bar") Bar
> bar) {
> Baz baz = bar.getValue(r.getLocale());
> }
>
> The bar class needs to know the current Locale in order to parse the
> incoming string correctly, and I believe I can't get the request
> object (HttpServletRequest) from inside Bar. Right now I've resorted
> to have a method on Bar to extract the "real" value, taking a Locale
> as input.
>
> Is there a neater way that I've missed? Does the StringReader<T>
> class posted last month help out any? (e.g.. can I add @Context
> annotated objects into my StringReaderProvider?).
>
> Daniel