Localization in JSF, how to remember selected locale per session instead of per request/view

后端 未结 5 1143
夕颜
夕颜 2020-11-22 04:36

faces-config.xml:


    
        ru
        

        
5条回答
  •  孤独总比滥情好
    2020-11-22 05:01

    You need to store the selected locale in the session scope and set it in the viewroot in two places: once by UIViewRoot#setLocale() immediately after changing the locale (which changes the locale of the current viewroot and thus get reflected in the postback; this part is not necessary when you perform a redirect afterwards) and once in the locale attribute of the (which sets/retains the locale in the subsequent requests/views).

    Here's an example how such a LocaleBean should look like:

    package com.example.faces;
    
    import java.util.Locale;
    
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.SessionScoped;
    import javax.faces.context.FacesContext;
    
    @ManagedBean
    @SessionScoped
    public class LocaleBean {
    
        private Locale locale;
    
        @PostConstruct
        public void init() {
            locale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale();
        }
    
        public Locale getLocale() {
            return locale;
        }
    
        public String getLanguage() {
            return locale.getLanguage();
        }
    
        public void setLanguage(String language) {
            locale = new Locale(language);
            FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
        }
    
    }
    

    And here's an example of the view should look like:

    
    
    
        
            JSF/Facelets i18n example
        
        
            
                
                    
                    
                    
                
            
            

    Note that is not required for functioning of JSF, but it's mandatory how search bots interpret your page. Otherwise it would possibly be marked as duplicate content which is bad for SEO.

    Related:

    • Internationalization in JSF 2.0 with UTF-8 encoded properties files

提交回复
热议问题