<f:view locale="#{languageBean.currentLocale}" />
package com.sido.mg.mbean;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Edward P. Legaspi
* @since Jan 17, 2013
*/
@Named
@SessionScoped
public class LanguageBean implements Serializable {
private static final long serialVersionUID = 1L;
private static MapsupportedLocales;
private Logger log = LoggerFactory.getLogger(LanguageBean.class);
@Inject
private transient Locale currentLocale;
static {
supportedLocales = new LinkedHashMap<>();
supportedLocales.put("English", Locale.US);
supportedLocales.put("日本語 言語", Locale.JAPAN);
}
public MapgetSupportedLocales() {
return supportedLocales;
}
public Locale getCurrentLocale() {
if (currentLocale == null || currentLocale.equals("")) {
currentLocale = Locale.US;
}
return currentLocale;
}
public void setCurrentLocale(Locale currentLocale) {
this.currentLocale = currentLocale;
}
public String switchLanguage(String language) {
log.debug("changing locale to={}", language);
if (language.equals("EN")) {
currentLocale = Locale.US;
} else {
currentLocale = Locale.JAPAN;
}
return FacesContext.getCurrentInstance().getViewRoot().getViewId() + "?faces-redirect=true";
}
public String getEntrustLocale() {
if (currentLocale == Locale.US) {
return "9";
} else {
return "28";
}
}
}
<ul class="right">
<li><p:commandLink immediate="true"
action="#{languageBean.switchLanguage('EN')}">
<h:graphicImage library="img" name="flags/us.png"></h:graphicImage>
</p:commandLink></li>
<li><p:commandLink immediate="true"
action="#{languageBean.switchLanguage('JP')}">
<h:graphicImage library="img" name="flags/jp.png"></h:graphicImage>
</p:commandLink></li>
</ul>
@PostConstruct
public void init() throws RuntimeException, IOException {
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
MaprequestParameters = context.getRequestParameterMap();
// set locale
try {
languageBean.setCurrentLocale(LocaleUtils.toLocale(requestParameters.get("locale")));
} catch (IllegalArgumentException | NullPointerException e) {
languageBean.setCurrentLocale(Locale.JAPAN);
}
}
<script type="text/javascript">
window.onload = function() {
if (!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
}
</script>