user3861559 February 2016

Java JSTL Split function regex

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


Some other times it is like this


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.



Erik Pragt February 2016

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.

Andreas February 2016

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

Post Status

Asked in February 2016
Viewed 1,145 times
Voted 7
Answered 2 times


Leave an answer