Getting the client locale in a jersey request

2019-01-26 07:00发布

问题:

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

回答1:

Locale locale = request.getLocale();



回答2:

The client should set the Accept-Language header.



回答3:

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();
...
}


回答4:

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 )
{
   ...
}