How do I set the user's locale on a JSP

Posted by ebynum on Stack Overflow See other posts from Stack Overflow or by ebynum
Published on 2010-06-09T20:14:32Z Indexed on 2010/06/09 20:32 UTC
Read the original article Hit count: 247

Filed under:
|
|

I have a .jsp page that the user loads directly. The request it with a URL like the following: http://www.example.com/myfile.jsp?country=CA&language=fr

In the JSP, I pull the URL GET parameters and attempt to set the locale using them as follows:

<%
    String myLanguage = request.getParameter("language");
    String myCountry  = request.getParameter("country");

    Locale myLocale = new Locale(myLanguage, myCountry);
    pageContext.setAttribute("myLocale", myLocale, PageContext.PAGE_SCOPE);
%>
<fmt:setLocale value="${myLocale}" scope="page" />

There are several places in the JSP that then display a message pulled from a localized resource bundle using <bean:message bundle="ts" key="..." /> from Struts.

On the first request for this page (after changing the language in the URL), it is returned in US English (the default Locale), and then subsequent refreshes will return the properly localized content.

© Stack Overflow or respective owner

Related posts about jsp

Related posts about localization