Localizing Messages

If your application supports more than one locale, you must be concerned also with the messages generated by the validators, the converters, and possibly your application code. The good news is that JSF is already internationalized with regards to how it handles messages—and if you follow the code samples for application-generated messages from Chapter 7, so is your application. This piece of code from the custom validator we developed in Chapter 7 shows what I mean:

package com.mycompany.jsf.validator;

import java.text.MessageFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.StateHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
...
public class LaterThanValidator implements Validator, StateHolder {
    ...
    public void validate(FacesContext context, UIComponent component,
        Object value) throws ValidatorException {

        Application application = context.getApplication( );

        String messageBundleName = application.getMessageBundle( );
        Locale locale = context.getViewRoot( ).getLocale( );
                       ResourceBundle rb = 
                           ResourceBundle.getBundle(messageBundleName, locale);

        UIComponent peerComponent = component.findComponent(peerId);
        if (peerComponent == null) {
 String msg = rb.getString("peer_not_found"); ...

Get JavaServer Faces now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.