Convert string to lowercase for property binding within xhtml?

jakarta-ee, java, jsf

Solution

<h:inputText value="#{userService.user.username.toLowerCase()}" />

You can't perform a "set" operation on the given EL expression, while this is mandatory in order to update the model value with the submitted value. The `toLowerCase()` method expression doesn't have a corresponding setter method.

Technically, you should be creating a `Converter` for the job. Here's a kickoff example:

@FacesConverter("toLowerCaseConverter")
public class ToLowerCaseConverter implements Converter {

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        if (!(modelValue instanceof String)) { 
            return null; // Or throw ConverterException.
        }

        return ((String) modelValue).toLowerCase();
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        if (submittedValue == null) { 
            return null;
        }

        return submittedValue.toLowerCase();
    }

}

Use it as follows:

<h:inputText value="#{userService.user.username}" converter="toLowerCaseConverter" />

You should preferably not clutter the model with conversion strategies.

Problem

How could I always convert the property `username` to lower case? This does not work: ``` <h:inputText value="#{userService.user.username.toLowerCase()}" /> ``` as target gets "unreachable" by this. How could I else do this?

Original source