How to update JSTL Locale dynamically
- By Viral Patel on November 22, 2012
When you use JSTL format tag
, JSTL automatically takes care of locale resolution. Depending on the browser’s locale setting JSTL will display the date and numbers.
You may want to override this default behavior. For example in case where you want to display date format only in en_US locale irrespective of user locale setting of browser. Or you may want to store user locale settings in database and render the page accordingly.
There are number of ways of overriding default JSTL locale at runtime.
Use setLocale tag in format taglib to set a default locale. For example:
Set locale to en_US on current JSP page:
Set locale to en_US for all JSP page by saving the setting in session:
scope attribute to set the scope of the locale.
2. Programmatically using Config API
If you want to set the JSTL Locale programmatically within Servlet / Controller, use
javax.servlet.jst.jstl.core.Config class to do so.
import javax.servlet.jst.jstl.core.Config; Config.set( session, Config.FMT_LOCALE, new java.util.Locale("de","DE") )
You can read user preference from database and set locale programmatically as shown in above code. Each JSP rendered after this would show number/date format in given locale.
3. Global setting using Servlet Context param
Set locale at global level by passing a servlet content parameter:
... javax.servlet.jsp.jstl.fmt.locale en_US
This sets the locale at global level. If you are not overriding locale by any of above way (1 and 2), this locale will be used to render JSP.
Here is a simple JSP which display date in default locale, de_DE and en_US:
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
Following is the output:
Get our Articles via Email. Enter your email address.