How do I access Locale from a JSP?

Sergio del Amo picture Sergio del Amo · Dec 2, 2008 · Viewed 43.1k times · Source

I want to include a js file depending on the value of the current Locale. I have tried to access it from JSP as follows:

<%@ page import="java.util.Locale" %>  
<% if( ((Locale) pageContext.getAttribute("org.apache.struts.action.LOCALE",PageContext.REQUEST_SCOPE)).getLanguage().equals("de")) { %>
    <script src="../themes/administration/js/languages/i18nDE.js" type="text/javascript"> </script>
<% } else { %>
    <script src="../themes/administration/js/languages/i18nEN.js" type="text/javascript"> </script>
<% } %>

However, I am getting a java.lang.NullPointerException because pageContext.getAttribute("org.apache.struts.action.LOCALE",PageContext.REQUEST_SCOPE) is NULL.

Does anyone knows how I can solve this?

Answer

dawez picture dawez · Nov 10, 2009

At the moment I am using this :

<c:set var="localeCode" value="${pageContext.response.locale}" />

This can later be access by using ${localeCode}

  1. Scriplet mode, discouraged! See Why not use Scriptlets for reason not to use a scriptlet.

The localeCode variable can be queried inside a scriptlet with:

<%
  Object ob_localeCode = pageContext.getAttribute("localeCode");
  if (ob_localeCode != null) {
    String currentLanguageCode = (String) ob_localeCode;
  }
  //more code
%>
  1. Scripletless mode correct way to go. See How to avoid Java Code in JSP-Files? Here on SO.

I am using spring 2.5 config at the moment.

So following this, coming back to your original question you can implement something like:

<c:set var="localeCode" value="${pageContext.response.locale}" />
<c:choose>
  <c:when test="$localecode == 'de' }"> 
    <script src="../themes/administration/js/languages/i18nDE.js" type="text/javascript"> </script>
  </c:when>
  <c:otherwise>
    <script src="../themes/administration/js/languages/i18nEN.js" type="text/javascript"> </script>
  </c:otherwise>
</c:choose>

or if you really want to use some short code to impress your colleagues, you can do:

<c:set var="localeCode" value="${fn:toUpperCase(pageContext.response.locale)}" />
<c:set var="availLanguages" value="EN,DE" />
<c:if test="${!fn:contains(availLanguages,localeCode)}">
  <c:set var="localeCode" value="EN" />
</c:if>

<script src="../themes/administration/js/languages/i18n{$localeCode}.js" type="text/javascript"> </script>