开发者

Convert inputText to byte[] in JSF

I'm开发者_开发百科 writing a web application which has a JSF page with a bean behind it. I am having trouble with it and I think it's because the bean is expecting a byte array for one particular field and it's being provided with a String.

From what I understand, JSF provides some functionality to automatically convert whatever you enter in your inputText fields to the required data type, but I don't think it does this when you want a byte[] ...

Is it simply a matter of writing a customer converter for JSF? Such as something like this:

public class StringToByteArray implements Converter {

...

public byte[] getAsObject(FacesContext context, UIComponent component, String value) {
    if (StringUtils.isEmpty(value)){ return null;}

    byte[] valueAsBytes = new byte[];

    valueAsBytes = value.getBytes();

    return valueAsBytes; } } 


The answer is yes. It is simply the matter of writing a custom converter. Don´t be discouraged by thinking "too much code for a simple conversion". Here is an example for a converter that converts a custom object to string and back. This kind of converter is often used for select menus:

@FacesConverter( value="merkmalConverter" )
public class MerkmalMenuConverter implements Converter {

    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value != null) {
            Merkmal m = (Merkmal) value;
            return m.getBezeichnung();
        }
        return null; // Value is null.
    }

    @SuppressWarnings("unchecked")
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value != null) {
            MerkmalJpaController mJpaC = new MerkmalJpaController();
            List<Merkmal> mList = mJpaC.findMerkmalEntities();
            for (Merkmal m : mList) {
                if (m.getBezeichnung().equals(value)) {
                    return m;
                }
            }
        }
        return null; // Value is null or doesn't have any match.
    }
}

Use your converter in the jsf file as shown here as child element of your input field to be converted:

<f:converter converterId="merkmalConverter" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜