How do I set the user's locale on a JSP
I have a .jsp page that the user loads directly. The request it with a URL like the following:开发者_Go百科
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.
I don't do Struts, but Google learns me that you need to set the Locale
as a session attribute with Globals.LOCALE_KEY
as key.
session.setAttribute(Globals.LOCALE_KEY, myLocale);
You actually don't need the JSTL fmt:setLocale
.
That said, I'd do this in a single Filter
rather than in every JSP.
精彩评论