How to set the user locale on JSP

I have a .jsp page that the user loads directly. Request it with the url as below: http://www.example.com/myfile.jsp?country=CA&language=fr

In JSP, I pull out the GET URL parameters and try 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 package using <bean:message bundle="ts" key="..." /> from Struts.

The first time this page is requested (after changing the language in the URL), it is returned in English (by default, Locale), and then subsequent updates will return correctly localized content.

+4
source share
1 answer

I do not do Struts, but Google finds out that you need to set Locale as a session attribute with Globals.LOCALE_KEY as the key.

 session.setAttribute(Globals.LOCALE_KEY, myLocale); 

In fact, you do not need JSTL fmt:setLocale .

However, I would do it in one Filter , and not in every JSP.

+2
source

Source: https://habr.com/ru/post/1312364/


All Articles