0

I have JSTL Java code that reads request header Accept language paremeter

<c:set var="locale" value="<%= request.getHeader("Accept-Language") %>"/>

The variable locale's value varies based on the order of browser's language setting.

Sometimes it is like this

en-GB,en;q=0.8,en-AU;q=0.6,en-US;q=0.4,en-CA;q=0.2

Some other times it is like this

en,en-GB;q=0.8,en-AU;q=0.6,en-US;q=0.4,en-CA;q=0.2

On either case I want to read the first occurrence of locale such as en-XX. In this case, en-GB.

I was using split function but I couldn't figure out the correct way to use it for this task.

I did this and it'd work only if en-XX was the first one in the string

<c:set var="locale" value="<%= request.getHeader("Accept-Language").split(",")[0] %>"/>

Any help in terms of incorporating regex with split function (or anyother function) is much appreciated.

Thanks,

1
  • Stop using scriptlets. Request headers are just available by ${header['name']} and the request locale is just available by ${pageContext.request.locale}. Commented Feb 9, 2016 at 9:06

2 Answers 2

1

Two answers:

  1. Don't do this (in JSTL), but in your servlet code if you really need to
  2. Don't do this, but use request.getLocale()

The request.getLocale():

Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.

It's probably a better choice to do what you want.

Sign up to request clarification or add additional context in comments.

Comments

0

There is nothing in the specification that says that languages are listed in descending order of preference (quality).

What you should be doing, is to compare the language you support to the given list of languages, to find the best match.

E.g. if you get this (example from specification):

Accept-Language: da, en-gb;q=0.8, en;q=0.7

but you only support "English (United States)" and "Spanish (Mexico)", then the best (only) match is en;q=0.7, meaning "any English language", so your choice would be en-US.

All this is something that should be done in a Servlet or action handler, not in the JSP. Alternatively, you create a helper class to provide the logic, that the JSP can use with <jsp:useBean>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.