The Java EE 5 Tutorial

Localizing Dynamic Data

The Duke’s Bookstore application has some data that is set dynamically in backing beans. Because of this, the beans must load the localized data themselves; the data can’t be loaded from the page.

The message method in tut-install/javaeetutorial5/examples/web/bookstore6/src/java/com/sun/bookstore6/backing/AbstractBean.java is a general-purpose method that looks up localized data used in the backing beans:

protected void message(String clientId, String key) {
    // Look up the requested message text
    String text = null;
    try {
        ResourceBundle bundle =
            ResourceBundle.getBundle("messages.BookstoreMessages",
                context().getViewRoot().getLocale());
        text = bundle.getString(key);
    } catch (Exception e) {
        text = "???" + key + "???";
    }
    // Construct and add a FacesMessage containing it
    context().addMessage(clientId, new FacesMessage(text));
}

This method gets the current locale from the UIViewRoot instance of the current request and loads the localized data for the messages using the getBundle method, passing in the path to the ResourceBundle and the current locale.

The other backing beans call this method by using the key to the message that they are trying to retrieve from the resource bundle. Here is a call to the message method from tut-install/javaeetutorial5/examples/web/bookstore6/src/java/com/sun/bookstore6/backing/ShowCartBean.java:

message(null, "Quantities Updated");