Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the client locale in a jersey request

What is the best and more portable way to get the client locale in the context of a Jersey (JAX-RS) request? I have the following code:

@GET
@Produces("text/html")
@Path("/myrequest")
public Response myRequest(@Context HttpServletRequest request) {
    Locale locale = ...
}

Please assume that the "request" is made by some javascript code within a browser, by calling window.location = ...;

like image 610
Laurent Grégoire Avatar asked Sep 03 '12 10:09

Laurent Grégoire


2 Answers

Getting language/locale data can be done in different ways depending on the final objective. According to the question, I believe the most suitable solution is:

@GET
public Response myRequest( @Context HttpServletRequest request )
{
   Locale locale = request.getLocale();
   ...
}

Another potential alternative is using a language query parameter:

@GET
public Response myRequest( @QueryParam( "language" ) String language )
{
   ...
}

Or alternatively, the "Accept-Language" header parameter:

@GET
public Response myRequest( @HeaderParam( "Accept-Language" ) String acceptLanguage )
{
   ...
}
like image 159
acoelhosantos Avatar answered Sep 18 '22 12:09

acoelhosantos


Use the HTTP Header for that. To request the numeric value in the US Locale decimal you can request like that:

GET /metrics/007/size Accept-Language: en-US

Then from the code:

public Response myRequest(@Context HttpServletRequest request) {
Locale locale = request.getLocale();
...
}
like image 39
user3774109 Avatar answered Sep 18 '22 12:09

user3774109