JBoss.orgCommunity Documentation

Chapter 5. Resources

5.1. <a4j:loadBundle>
5.2. <a4j:loadScript>
5.3. <a4j:loadStyle>
5.4. <a4j:keepAlive>
5.5. <a4j:mediaOutput>

This chapter covers those components used to handle and manage resources and beans.

The <a4j:loadBundle> component is used to load resource bundles to aid in localization of an application. The bundles are localized to the locale of the current view, and properties are stored as a map in the current request attributes.

The <a4j:loadBundle> component allows bundles to be accessed by Ajax requests working in their own address scopes. This solves the problem of using the JSF <h:loadBundle> component with Ajax, where bundle information loaded with the page was unavailable for later Ajax requests.

Resource bundles are registered in the Faces configuration file, faces-config.xml.

Example 5.1. <a4j:loadBundle> example

This example shows a simple application capable of switching between different localized languages.

  1. Create resource bundles

    String resource bundles are contained in files with a .properties extension. The files consist of a list of entries, each with a unique name and a corresponding value. A seperate file is required for each language. Append the filename with the locale identifier (en for English, for example).

  2. Register bundles in Faces configuration file

    The resource bundles need to be registered in the Faces configuration file, faces-config.xml. The filename is defined with the <message-bundle> tag, without the locale code and without the extension. The supported locale codes are listed with <supported-locale> tags.

    
    
    <application>
        <locale-config>
            <default-locale>en</default-locale>
            <supported-locale>en</supported-locale>
            <supported-locale>de</supported-locale>
            <supported-locale>it</supported-locale>
        </locale-config>
        <message-bundle>demo.message</message-bundle>
    </application>

  3. Create method to set locale

    The JSF javax.faces.component.UIViewRoot.setLocale() method can be used to update the locale through a Java class:

    
    
    package demo;
    import java.util.Locale;
    import javax.faces.context.FacesContext;
    public class ChangeLocale {
        public String germanAction() {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getViewRoot().setLocale(Locale.GERMAN);
            return null;
        }
        public String englishAction() {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getViewRoot().setLocale(Locale.ENGLISH);
            return null;
        } 
        public String italianAction() {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getViewRoot().setLocale(Locale.ITALIAN);
            return null;
        }
    }
  4. Add <a4j:loadBundle> to the JSP page

    The <a4j:loadBundle> component is added to the application, and links to change the locale will update the displayed text.

    
    
    <h:form>
        <a4j:loadBundle var="msg" basename="demo.message"/>
        <h:outputText id="messageBundle" value="#{msg.greeting}"/>
        <a4j:commandLink value="De" action="#{changeLocale.germanAction}" reRender="messageBundle" />
        <a4j:commandLink value="Eng" action="#{changeLocale.englishAction}" reRender="messageBundle" />
        <a4j:commandLink value="It" action="#{changeLocale.italianAction}" reRender="messageBundle" />
    </h:form> 


Clicking on the different links will render the localized string as appropriate.


The <a4j:loadScript> component allows scripts to be loaded from external sources such as jar files.

The required src attribute defines the path to the script. A leading slash (/) represents the root of the web context. The resource:// prefix can be used to access a file in the RichFaces resource framework. The path is passed to the getResourceURL() method of the application's ViewHandler, with the result then being passed through the encodeResourceURL() method of ExternalContext.


The <a4j:loadStyle> component allows a style sheet to be loaded from an external source, such as a jar file. The style sheet links are inserted into the head element.

The required src attribute defines the path to the script. A leading slash (/) represents the root of the web context. The resource:// prefix can be used to access a file in the RichFaces resource framework. The path is passed to the getResourceURL() method of the application's ViewHandler, with the result then being passed through the encodeResourceURL() method of ExternalContext.


The <a4j:keepAlive> component allows the state of a managed bean to be retained between Ajax requests.

Managed beans can be declared with the request scope in the faces-config.xml configuration file, using the <managed-bean-scope> tag. Any references to the bean instance after the request has ended will cause the server to throw an illegal argument exception. The <a4j:keepAlive> component avoids this be maintaining the state of the whole bean object for subsequent requests.

The beanName attribute uses JSF Expression Language (EL) to define the request scope bean name to keep alive. The expression must resolve to a managed bean instance. The ajaxOnly attribute determines whether or not the value of the bean should be available during non-Ajaxx requests; if ajaxOnly="true", the request-scope bean keeps its value during Ajax requests, but any non-Ajax requests will re-create the bean as a regular request-scope bean.


The <a4j:mediaOutput> component is used for generating images, video, sounds, and other resources defined on the fly.

The createContent attribute points to the method used for generating the displayed content. If necessary, the value attribute can be used to pass input data to the content generation method specified with createContent. The cacheable attribute specifies whether the resulting content will be cached or not.

The mimeType attribute describes the type of output content, and corresponds to the type in the header of the HTTP request. The element attribute defines XHTML element used to display the content:

Example 5.5. <a4j:mediaOutput> example

This example uses the <a4j:mediaOutput> component to generate a JPEG image of verification digits. The code on the application page is a single element:



<a4j:mediaOutput element="img" cacheable="false" session="false" createContent="#{mediaBean.paint}" value="#{mediaData}" mimeType="image/jpeg" />

The <a4j:mediaOutput> component uses the MediaBean.paint method to create the image. The method generates a random number, which is then converted into an output stream and rendered to a JPEG image. The MediaBean class is as follows:



package demo;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public class MediaBean {
    public void paint(OutputStream out, Object data) throws IOException {
        Integer high = 9999;
        Integer low = 1000;
        Random generator = new Random();
        Integer digits = generator.nextInt(high - low + 1) + low;
        if (data instanceof MediaData) {            
            MediaData paintData = (MediaData) data;
            BufferedImage img = new BufferedImage(paintData.getWidth(),paintData.getHeight(),BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = img.createGraphics();
            graphics2D.setBackground(paintData.getBackground());
            graphics2D.setColor(paintData.getDrawColor());
            graphics2D.clearRect(0,0,paintData.getWidth(),paintData.getHeight());
            graphics2D.setFont(paintData.getFont());
            graphics2D.drawString(digits.toString(), 20, 35);
            ImageIO.write(img,"png",out);
        }
    }
}

Another class, MediaData is required by the value attribute for keeping data to be used as input for the content creation method. The MediaData class is as follows:



package demo;
import java.awt.Color;
import java.awt.Font;
import java.io.Serializable;
public class MediaData implements Serializable {
    private static final long serialVersionUID = 1L;
    Integer Width=110;
    Integer Height=50;
    Color Background=new Color(190, 214, 248);
    Color DrawColor=new Color(0,0,0);
    Font font = new Font("Serif", Font.TRUETYPE_FONT, 30);
    /* Corresponding getters and setters */
    ...
}

The <a4j:mediaOutput> component uses the MediaBean and MediaData classes to generate a new image on each page refresh, which appears as shown in Figure 5.1, “<a4j:mediaOutput> example result”

Figure 5.1. <a4j:mediaOutput> example result



Serializable interface

A bean class passed using the value attribute of <a4j:mediaOutput> should implement the Serializable interface so that it will be encoded to the URL of the resource.