Getting the client locale in a jersey request

2019-01-26 07:21发布

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

4条回答
我只想做你的唯一
2楼-- · 2019-01-26 07:31

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 )
{
   ...
}
查看更多
何必那么认真
3楼-- · 2019-01-26 07:32

The client should set the Accept-Language header.

查看更多
甜甜的少女心
4楼-- · 2019-01-26 07:45

Locale locale = request.getLocale();

查看更多
做个烂人
5楼-- · 2019-01-26 07:47

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();
...
}
查看更多
登录 后发表回答