Automatic to-Object conversion in JSF selectOneMenu & Co.

When creating a web UI, there is often the need to let a user make a selection from e.g. a drop-down. The items in such a drop-down are not rarely backed by domain objects. Since these items in the HTML rendering are just simple character identifiers, we need some way to encode the object version of an item to this simple character identifier (its string representation) and back again.

A well established pattern in JSF is the following:

<selectOneMenu value="#{bean.selectedUser}" converter="#{userConverter}">
    <selectItems value="#{bean.selectableUsers}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

With userConverter defined as something like:

@Named
public class UserConverter implements Converter {

    @Inject
    private UserDAO userDAO;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        return userDAO.getById(Long.valueOf(value));
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        return ((User) value).getId().toString();
    }
}
(note that the converter implementation is overly simplified, in practice null checks and checks for "String value" representing a number would be needed)

This is functional, but in its full form not really convenient to program nor efficient. Upon every post back, there will be a call to the DAO to convert the string representation of an item back to its Object form. When no caching is used or the object isn't in the cache, this will likely result in a call to a back-end database, which is never a positive contribution to the overall performance of a page. It gets worse when there are more of such conversions being done and it can go through the roof when we have e.g. editable tables where each row contains multiple drop-downs. A table with only 10 rows and 4 drop-downs might result in 40 separate calls to the back-end being done.

But is using a DAO here really needed?

After all, after the converter does its work, JSF checks whether the Object is equal to any of the Objects in the collection that was used to render the drop-down. In other words, the target Object is already there! And it must be there by definition, since without it being present validation will simply never pass.

So, by taking advantage of this already present collection we can prevent the DAO calls. The only question is, how do we get to this from a converter? A simple way is to use a parameter of some kind and provide it with a binding to this collection. This is however not really DRY, as it means we have to bind to the same collection twice right after each other (once for the selectItems, once for the converter parameter). Additionally, we still have to iterate over this and need custom code that knows to which property of the Object we need to compare the String value. For instance, for our User object we need to convert the String value to a Long first and then compare it with the Id property of each instance.

Another approach that I would like to present here is basically emulating how a UIDataTable detects on which row a user did some action. After the post back it iterates over the data that was used to render the table in the same way again. This will cause the same IDs to be generated as in the original rendering. The ID of the component that is posted back is compared to the newly generated one and when they match iteration stops and we know the row.

In this case, after the post back we'll iterate over all select item values, convert these to their string representation and compare that to the 'to-be-converted' string value. If they match, the unconverted object is the one we're after and we return that. For iterating over the select item values, I took advantage of a private utility class that's in Mojarra: com.sun.faces.renderkit.SelectItemsIterator (for a proof of concept, I just copied it since it's package private).

The implementation is done via a Converter base class from which user code can inherit. That way, only a getAsString method needs to be implemented:

@Named
public class UserConverter extends SelectItemsBaseConverter {
    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        return ((User) value).getId().toString();
    }
}

The base class is implemented as follows:

public abstract class SelectItemsBaseConverter implements Converter {
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {        
        return SelectItemsUtils.findValueByStringConversion(context, component, value, this);    
    }    
}

And the SelectItemsUtils class:

public final class SelectItemsUtils {
    
    private SelectItemsUtils() {}

    public static Object findValueByStringConversion(FacesContext context, UIComponent component, String value, Converter converter) {
        return findValueByStringConversion(context, component, new SelectItemsIterator(context, component), value, converter);        
    }
    
    private static Object findValueByStringConversion(FacesContext context, UIComponent component, Iterator<SelectItem> items, String value, Converter converter) {
        while (items.hasNext()) {
            SelectItem item = items.next();
            if (item instanceof SelectItemGroup) {
                SelectItem subitems[] = ((SelectItemGroup) item).getSelectItems();
                if (!isEmpty(subitems)) {
                    Object object = findValueByStringConversion(context, component, new ArrayIterator(subitems), value, converter);
                    if (object != null) {
                        return object;
                    }
                }
            } else if (!item.isNoSelectionOption() && value.equals(converter.getAsString(context, component, item.getValue()))) {
                return item.getValue();
            }
        }        
        return null;
    }

    public static boolean isEmpty(Object[] array) {
        return array == null || array.length == 0;    
    }

    /**
     * This class is based on Mojarra version
     */
    static class ArrayIterator implements Iterator<SelectItem> {

        public ArrayIterator(SelectItem items[]) {
            this.items = items;
        }

        private SelectItem items[];
        private int index = 0;

        public boolean hasNext() {
            return (index < items.length);
        }

        public SelectItem next() {
            try {
                return (items[index++]);
            }
            catch (IndexOutOfBoundsException e) {
                throw new NoSuchElementException();
            }
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
}

The source of the Mojarra SelectItemsIterator can be found here, MyFaces seems to have a similar implementation here, but I did not test that one yet. PrimeFaces also has something like this (see org.primefaces.util.ComponentUtils#createSelectItems).

A custom selectOneMenu, selectManyListbox etc could even go a step further and should be able to do this without the need for a converter at all. Combined with an extended selectItems tag, it could look like this:

<selectOneMenu value="#{bean.selectedUser}">
    <selectItems value="#{bean.selectableUsers}" var="user" itemValue="#{user}" itemValueAsString="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>

In this hypothetical example, we could even simplify stuff further by setting itemValue by default to var, so it would then look like this:

<h:selectOneMenu value="#{bean.selectedUser}">
    <f:selectItems value="#{bean.selectableUsers}" var="user" itemValueAsString="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>

Implementing this might be the topic for a next article. For now I'll hope the converter based approach is useful.

An implementation of this is readily available in the new OmniFaces library, from where you can find the documentation and the full source code. There's also a live demo available.

Arjan Tijms

Comments

Popular posts from this blog

Jakarta EE Survey 2022

Implementing container authentication in Java EE with JASPIC

Counting the rows returned from a JPA query