Convert inputText to byte[] in JSF

非 Y 不嫁゛ 提交于 2019-12-11 05:08:10

问题


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; } } 

回答1:


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" />


来源:https://stackoverflow.com/questions/5224633/convert-inputtext-to-byte-in-jsf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!