How to set the locale programmatically in JSF

假装没事ソ 提交于 2019-12-19 10:06:24

问题


I'm currently trying to set the locale programatically, but can't find a good solution. The use case is I have another website that post data to my site that has a locale parameter, and base on this locale, I have to render my page.

I've already tried setting the locale on preRenderView, constructor and PostConstruct but it seems it's already to late.

Any suggestion? Thanks.


回答1:


Key point is that you need to set the locale by UIViewRoot#setLocale() before the view is ever rendered. The <f:view locale="#{languageBean.currentLocale}"> is only set during building of the view. So any request based actions which are invoked thereafter with the intent to change only the bean property won't have any effect. You really need to manually invoke UIViewRoot#setLocale() as well.

Easiest would be to perform that UIViewRoot#setLocale() job in the setter of the currentLocale property as well. The bean example as mentioned in the answer of the link provided by Daniel in your question comment does exactly that: JSF 2.0 set locale throughout session from browser and programmatically. This way no ugly JS hack is necessary to reload the page once.

Based on your own answer, there's another possible problem: your "receiver bean" seems to be request scoped and not be the #{languageBean} itself. If this bean is constructed for the first time after any locale/language related aspects of the view (e.g. language dropdown, localized text, etc), then it's too late to change them as well. You would like to move the construction of the bean to the pre render view event (e.g., via <f:event listener>). An alternative is to just perform the request parameter collecting job in the getter of the currentLocale property instead.




回答2:


I've resolved the issue by using plain javascript to load the page.

In my PostConstruct, I read the parameter from context's request parameter map. // set locale

try {
    languageBean.setCurrentLocale(LocaleUtils.toLocale(temp.getLocale()));
} catch (IllegalArgumentException | NullPointerException e) {
    languageBean.setCurrentLocale(Locale.JAPAN);
}

And then reload the page using plain javascript:

<script type="text/javascript">
    window.onload = function() {
        if (!window.location.hash) {
            window.location = window.location + '#loaded';
            window.location.reload();
        }
    }
</script>

I've wrote a more detailed codes here: http://czetsuya-tech.blogspot.com/2013/01/loading-locale-from-postget-parameter.html



来源:https://stackoverflow.com/questions/14373153/how-to-set-the-locale-programmatically-in-jsf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!