在整个会话中更改JSF中的本地化 [英] Change Localization In JSF Throughout The Session

查看:51
本文介绍了在整个会话中更改JSF中的本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序,该Web应用程序将JSF与PrimeFaces一起使用,还有一个JSF,它允许用户动态更改语言环境.但是,在用户转到另一个JSF之后,语言环境又变回默认值. 我在此处查看了代码,和此处,但仍无法使其正常工作

I have a web application, which uses JSF with PrimeFaces, and there is a JSF which allows users to change the locale dynamically. But the locale changes back to the default after the user goes to another JSF. I looked at the codes here, and here, but still couldn't get it to work.

在我的资源目录中,我有3个属性文件.

In my resource directory, I have 3 property files.

Project
    - src/main/resources
        - <default package>
            - messages_en_US.properties
            - messages_zh_CN.properties
            - messages_zh_TW.properties

在我的faces-config.xml中,我定义了语言环境

In my faces-config.xml I have the locales defined

<application>
        <locale-config>
            <default-locale>en_US</default-locale>
            <supported-locale>zh_TW</supported-locale>    <!-- generic traditional chinese -->
            <supported-locale>zh_CN</supported-locale>    <!-- generic simplified chinese -->
        </locale-config>
        <message-bundle>
            messages
        </message-bundle>
        <resource-bundle>
            <base-name>messages</base-name>
            <var>msg</var>
        </resource-bundle>
    </application>

在允许用户更改语言环境的JSF中,它实际上是用户个人资料页面.从枚举中读取<p:selectOneMenu />项,并在单击保存"按钮后更改语言环境.

In the JSF which allows users to change the locale, it is actually a user profile page. The <p:selectOneMenu /> items are read from an Ennum and the locale is changed upon clicking on the "Save" button.

<p:selectOneMenu id="defaultLanguage" value="#{userController.userLanguage}">
                            <f:selectItems value="#{userController.langcode}" var="lang" itemValue="#{lang.locale}"
                                           itemLabel="#{lang.locale} - #{lang.desc}" />
                        </p:selectOneMenu>
...
<p:commandButton id="save" value="#{msg.save}" title="#{msg.save}" icon="ui-icon-disk"
                             styleClass="action-buttons" actionListener="#{userController.doSave}" update="@form" />

UserController ManagedBean中,代码如下:

In the UserController ManagedBean, the code are as follows:

@ManagedBean
@ViewScoped
public class UserController extends BaseController implements Serializable {

    public void doSave(ActionEvent e) {
            String lang;
            String country = null;
            String[] selectedLanguage = userLanguage.split("_");

            lang = selectedLanguage[0];
            if (selectedLanguage.length > 1) {
                country = selectedLanguage[1];
                setUserLocale(new Locale(lang, country));
            }
            else {
                setUserLocale(new Locale(lang));
            }

            LOG.debug("userLanguage: {}; lang: {}", userLanguage, lang);

            FacesContext.getCurrentInstance().getViewRoot().setLocale(userLocale);      // sets the locale from the selected user language

            Messages.addGlobalInfo(getMessage(msgInfoUpdated));
        }

    private LangCode userLangCode;              // getter + setter
    private LangCode[] langcode = LangCode.values();    // getter + setter
    @ManagedProperty(value = "#{loginController.userLocale}")
        private Locale userLocale;              // getter + setter

}

在JSF中,我尝试添加<f:view locale="#{loginController.locale}" />.但是还是一样.在调试模式下,转到新的JSF页面时,userLocale的值始终是默认语言环境,而不是用户更改的语言环境.

In the JSF I tried to add the <f:view locale="#{loginController.locale}" />. But still the same. In debug mode, when going to a new JSF page, the value of the userLocale is always the default locale and not the one which the user changed.

LoginController代码如下.在doLogin()方法中,我使用Faces上下文中的语言环境设置了userLocale对象.

The LoginController code is as below. At the doLogin() method, I set the userLocale object with the locale from the Faces Context.

@ManagedBean
@SessionScoped
public class LoginController extends BaseController implements Serializable {

    public String doLogin() {
            String returnValue;

            try {
                currentUser = aduserFacade.validateUserLogin(username, password);
                LOG.debug("Successful login: {}", currentUser.getUsrId());

                // Set currentUser object into request session attribute
                FacesContext context = FacesContext.getCurrentInstance();
                HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

                setUserSession();
                userLocale = Faces.getLocale();
                request.getSession().setAttribute("userSession", userSession);

                returnValue = "main";
            }
            catch (Exception e) {
                Messages.addGlobalError(getMessage(e.getMessage()));
                LOG.error(e.toString(), e);
                returnValue = null;
            }

            return returnValue;
    }

    private Locale userLocale;  // getter + setter

}

推荐答案

您的语言环境无法保留的原因是,您注入的语言环境属性尚未更新为新值注入它.请参见,在注入托管bean属性时,与在

The reason your locale is failing to hold is that the locale property you're injecting has not yet been updated with the new value as at the time you're injecting it. See, when you inject a managed bean property, as against the managed bean itself as in

@ManagedProperty(value = "#{loginController.userLocale}")

代替

 @ManagedProperty(value = "#{loginController}") 

您将获得静态值注入.即使注入的Bean中的值已更新,您仍将仅获得初始化注入的Bean时所设置的陈旧值.因此,您需要做的是注入整个LoginController,然后自己提取值,这样您将获得最新的值.

You're going to get a static value injection. Even after the value in the injected bean has been updated, you'll still only get a stale value that was set as soon as the injected bean was initialized. So what you need to do is inject the entire LoginController and then pull the value yourself, so you'll get the most current values.

另请参见

与您的问题无关,您实际上不应该将成员变量和注入放在类的底部.使您的代码不方便阅读

Unrelated to your question, you really shouldn't put member variables and injection at the bottom of your class. Makes your code inconvenient to read

这篇关于在整个会话中更改JSF中的本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆