1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
/*
* LanguageBean.java
*/
package org.simplicity2k.application.helper;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
/**
* @author simplicity2k
* @version 1.0-SNAPSHOT
*/
@ManagedBean
@SessionScoped
public class LanguageBean implements Serializable {
private static final long serialVersionUID = 113050854352270339L;
/** The current locale name (eg. en, fr, ...). */
private String currentLanguage;
/**
* The hashmap of locales.
* The key equals the locale name (eg. en, fr, ...).
* The related value is the corresponding Locale object.
*/
private Map<String, Locale> localeHashMap;
/**
* Creates a new instance of LanguageBean and initializes bean's properties.
*/
public LanguageBean() {
currentLanguage = null;
localeHashMap = new HashMap<String, Locale>();
}
/**
* Method called after constructor method.
*/
@PostConstruct
public void load() {
loadLanguageBean();
}
/**
* Method called at the end of the bean lifecycle.
*/
@PreDestroy
public void unload() {
}
/**
* Loads the hashmap with all the locales set in the faces-config.xml.
*/
private void loadLanguageBean() {
FacesContext facesContext = FacesContext.getCurrentInstance();
Iterator<Locale> localeIterator = facesContext.getApplication().getSupportedLocales();
if (currentLanguage == null) {
currentLanguage = facesContext.getApplication().getDefaultLocale().getLanguage();
}
while (localeIterator.hasNext()) {
Locale locale = localeIterator.next();
localeHashMap.put(locale.getLanguage(), locale);
}
}
/**
* Getter for the current language (eg. en, fr, ...).
* @return The current language.
*/
public String getCurrentLanguage() {
return currentLanguage;
}
/**
* Setter for the current language (eg. en, fr, ...).
* @param The current language.
*/
public void setCurrentLanguage(String currentLanguage) {
this.currentLanguage = currentLanguage;
FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(currentLanguage));
}
} |
Partager