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 = ...;
Locale locale = request.getLocale();
The client should set the Accept-Language
header.
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();
...
}
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 )
{
...
}