0

嗨,我正在处理 Primfaces 页面的每个人,我必须制作一个 selectOneMenu 来从数据库中获取项目,所以我试图这样做,但我仍然有转换器的问题

所以我的源代码如下:

选择一个菜单:

<p:selectOneMenu id="devises" required="true" value="#{pret.devise}" effect="fade" converter="devise">  
    <f:selectItem itemLabel="Select One" itemValue="" />  
    <f:selectItems value="#{devise.listDevise()}" var="devise" itemLabel="#{devise.nomDevise}" itemValue="#{devise}"/>  
</p:selectOneMenu>

转换器代码:

@FacesConverter(value = "devise")
public class DeviseConverter implements Converter{  

    public static List<Devise> devises = Devise.listDevise();  

    public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {  
        if (submittedValue.trim().equals("")) {  
            return null;  
        } else {  
            try {  
                int idDevise = Integer.parseInt(submittedValue);
                for (Devise p : devises) {  
                    if (p.getIdDevise()== idDevise) {  
                        return p;  
                    }  
                }
            } catch(NumberFormatException exception) {  
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Devise"));  
            }  
        }
        return null;  
    }  

    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {  
        if (value == null || value.equals("")) {  
            return "";  
        } else {  
            return String.valueOf(((Devise) value).getIdDevise());  
        }  
    }
}

错误代码是:“设计:验证错误:值无效”

4

1 回答 1

0

您的对象Devise需要包含equals()hashCode()方法。

您也可以使用generic converter它适用于所有类型的对象,并且您不需要为所有选择列表编写转换器。

import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.WeakHashMap;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter(value = "entityConverter")
public class EntityConverter implements Converter {

    private static Map<Object, String> entities = new WeakHashMap<Object, String>();

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object entity) {
        synchronized (entities) {
            if (!entities.containsKey(entity)) {
                String uuid = UUID.randomUUID().toString();
                entities.put(entity, uuid);
                return uuid;
            } else {
                return entities.get(entity);
            }
        }
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
        for (Entry<Object, String> entry : entities.entrySet()) {
            if (entry.getValue().equals(uuid)) {
                return entry.getKey();
            }
        }
        return null;
    }

}
于 2013-07-22T08:21:44.490 回答