1

我有带有用户个人资料设置的表格。这些设置之一是站点的默认语言。当用户更改默认语言设置时,我想更改当前会话的区域设置。表格处理方法:

@ManagedBean(name="userEditBean")
@RequestScoped
public class UserEditBean {


    @ManagedProperty(value = LanguageBean.INJECTION_NAME)
    private LanguageBean languageMB;

    private AdminUsersEditForm editForm = new AdminUsersEditForm();


    public String changeDefaultLanguage() {
        editForm.getUser().setDefaultLanguage(editForm.getLocaleCode());
        adminUserEditService.update(editForm.getUser());
        languageMB.changeLocale(editForm.getLocaleCode());
        FacesContext context = FacesContext.getCurrentInstance();  
        context.addMessage(null, new FacesMessage(languageMB.translate("user.edit.languageChanged")));
        return "/pages/protected/user/edit.xhtml?faces-redirect=true";
    }

和changeLocale:

@ManagedBean(name="languageMB")
@SessionScoped
public class LanguageBean implements Serializable {
    public void changeLocale(String newLocaleValue) {
            //loop country map to compare the locale code
            for (Map.Entry<String, Object> entry : countries.entrySet()) {
                if(entry.getValue().toString().equals(newLocaleValue)){
                    FacesContext.getCurrentInstance()
                            .getViewRoot().setLocale((Locale)entry.getValue());
                }
            }
        }

DB 中的语言已更改,但站点仍使用旧语言环境。当我从 eventListener 调用 changeLocale 以更改站点语言时,它可以工作,那么问题出在哪里。谢谢你。

更新: 我做了一些调试,问题出在 ViewHandlingStrategy#createView() 就行了:

if (ctx.getViewRoot() != null) {
    locale = ctx.getViewRoot().getLocale();

ctx.getViewRoot() 显然返回 null 并且区域设置未设置 grom getViewRoot()。但我不知道,我的 viewRoot “丢失”了

4

1 回答 1

3

I suppose your locale bean is a @SessionScoped bean right?

If that's the case, you should also:

  • Set the locale in your root template or in all your pages in case you don't use templating:

    <f:view contentType="text/html" locale="#{yourLocaleBean.locale}">
        <h:head>
            <!-- headers here -->
        </h:head>
        <h:body>
            <!-- content here -->
        </h:body>
    </f:view>
    

I hope it helps.

于 2012-10-17T14:24:58.760 回答