vendredi 18 mars 2016

How can you access the @Size annotation of a field in JSF?

My problem is:

Some of my entity fields need to have an exact length for compatibility reasons. That length is defined via @Size(min=10, max=10) or similar on the field. Although the fields are typed as String, they actually contain numbers. Most of the fields have values with leading zeroes, for example: 0000148233.

Now I don't want to force the user to enter those leading zeroes in the input fields. It should be possible to just enter 148233.

My first approach was writing a composite component that uses a simple FacesConverter to add leading zeroes on the input, based on an attribute length:

<composite:interface>
    <composite:attribute name="value" required="true" />
    <composite:attribute name="length" required="true"
        type="java.lang.Integer" />
</composite:interface>

<composite:implementation>
    <h:inputText value="#{cc.attrs.value}">
        <f:converter converterId="leadingZeroesConverter" />
        <f:attribute name="length" value="#{cc.attrs.length}" />
    </h:inputText>
</composite:implementation>

I read the length attribute in the Converter:

@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
    int length = (Integer) component.getAttributes().get("length");
    return Strings.zeroPrefixFillUp(value, length);
}

That does work quite well, but I actually don't want to define the length in JSF.

What I would like to do is access the annotation somehow, either in JSF or in the converter. This way I could avoid maintaining that attribute in two places.

In the converter I have the FacesContext and the UIComponent (which is an InputText, obviously). Is there any way to get the field's name (and it's class), so I can access that annotation?

PS: Just to let you know, I stripped all the error handling from the Converter for clarity reasons.





Aucun commentaire:

Enregistrer un commentaire