Changing the Locale Programmatically in JSF using ActionListener

By using actionListener in Facelets we ensure buttons affect only the UI.

<h:commandButton actionListener="..." .../>

We usually want this process to occur before beans are populated and especially before validation occurs.

While using actionListener, immediate attributr is used to designate that listener fires before validation is performed or beans are populated.

<h:commandButton actionListener="..." immediate="true" .../>

Implementing ActionListener in the Java Code
The method that we call by using actionListener takes ActionEvent as argument with the return type void.
Sample code

public void someMethod(ActionEvent event) {
doSomething();
}

Example of Changing the Locale Programmatically
There are two methods to set the Locale
– Call setLocale on the view

<f:view locale="#{formSettings.currentLocale}">

– You can also get Locale from browser settings

<f:view locale="#{facesContext.externalContext.requestLocale}">

– Set the Locale of the UIViewRoot

FacesContext.getCurrentInstance().getViewRoot().setLocale(currentLocale);

Input Form (index.xhtml)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
    <f:view locale="#{localeBean.locale}">
        <h:head><title>#{prompts.registrationTitle}</title>
            <link href="./css/styles.css" 
                  rel="stylesheet" type="text/css"/> 
        </h:head>
        <h:body>

            <h:form>
                <h:panelGrid columns="1">
                    <h1 class="title">#{prompts.registrationTitle}</h1>
                    <h3>#{prompts.registrationText}</h3>
                </h:panelGrid>
                <h:panelGrid columns="2">
                    #{prompts.firstName}: <h:inputText/>
                    #{prompts.lastName}: <h:inputText/>
                    #{prompts.emailAddress}: <h:inputText/>
                </h:panelGrid>
                <h:panelGrid columns="4">
                    <h:commandButton value="#{prompts.englishLabel}" 
                                     actionListener="#{localeBean.setEnglish}"
                                     immediate="true"/>
                    <h:commandButton value="#{prompts.spanishLabel}" 
                                     actionListener="#{localeBean.setSpanish}"
                                     immediate="true"/>
                    <h:commandButton value="#{prompts.frenchLabel}" 
                                     actionListener="#{localeBean.setFrench}"
                                     immediate="true"/>
                    <h:commandButton value="#{prompts.bangLabel}" 
                                     actionListener="#{localeBean.setBangla}"
                                     immediate="true"/>
                </h:panelGrid>
            </h:form>
        </h:body>
    </f:view>
</html>

LocaleBean.java

package com.bari.example;

import java.io.*;
import java.util.*;
import javax.faces.bean.*;
import javax.faces.context.*;
import javax.faces.event.*;

@ManagedBean
@SessionScoped
public class LocaleBean implements Serializable {
  private final Locale ENGLISH = Locale.ENGLISH;
  private final Locale SPANISH = new Locale("es");
  private final Locale FRENCH = Locale.FRENCH;
  private final Locale BANGLA = new Locale("bn");
  private Locale locale = ENGLISH;

  public Locale getLocale() {
    return(locale);
  }
  public void setBangla(ActionEvent event) {
    locale = BANGLA;
    updateViewLocale();
  }
  
  public void setEnglish(ActionEvent event) {
    locale = ENGLISH;
    updateViewLocale();
  }
  
  public void setSpanish(ActionEvent event) {
    locale = SPANISH;
    updateViewLocale();
  }
  
  public void setFrench(ActionEvent event) {
    locale = FRENCH;
    updateViewLocale();
  }
  
  private void updateViewLocale() {
    FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
  }
}

Declare with resource-bundle in faces-config.xml
base-name gives base file name relative to src (classes)
var gives scoped variable (Map) that will hold results.

<?xml version="1.0"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
   version="2.0">
  <!-- Declare properties files. Note that "form-prompts" for base-name really
       means WEB-INF/classes/form-prompts.properties  -->
  <application>
    <resource-bundle>
      <base-name>form-prompts</base-name>
      <var>prompts</var>
    </resource-bundle>
  </application>
</faces-config>

css/styles.css

body {
  background-color: #e9e9e9; 
}
h1,h2,h3 {
  text-align: center;
  font-family: Verdana, Arial, Helvetica, sans-serif;
  color: black;
}
h1.title {
  display: block;
  margin: auto;
  color: #afc4d6;
  border-width: 4px;
  border-style: outset;
  border-color: #9fd1ff;
  padding: 5px 8px;
  letter-spacing: -.025em;
}

Create a .properties file
-It contains simple keyName=value pairs.
-Must be deployed to WEB-INF/classes
-In Eclipse/NetBeans, this means you put it in “src” folder

src/form-prompts.properties

registrationTitle=Registration
firstName=First Name
lastName=Last Name
emailAddress=Email Address
registrationText=Please enter your first name, last name, and email address.
buttonLabel=Register Me
englishLabel=English
spanishLabel=Español
frenchLabel=Français
bangLabel=বাংলা

src/form-prompts_bn.properties

registrationTitle=রেজিস্ট্রেশন
firstName=নামের প্রথম অংশ
lastName=নামের শেষ অংশ
emailAddress=ই-মেইল
registrationText=অনুগ্রহ করে নামের প্রথম অংশ, শেষ অংশ এবং ই-মেইল লিখুন
buttonLabel=রেজিস্ট্রেশন

Screenshots:

jsf_locale1

Default locale English

jsf_locale2

Showing locale bangla when user clicks the bangla button

 

admin

Hello! I am Md. Abdul Bari; founder and admin of javaknowledge; currently providing training as a J2EE faculty in The Computers Ltd. Dhaka, Bangladesh under an IT Scholarship project provided by IDB-BISEW. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

More Posts - Website

Follow Me:
TwitterFacebookGoogle Plus

10,687` Total Views

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *


− one = 4