selectManyMenu中的ClassCastException - 无法将Integer强制转换为String

时间:2014-11-29 22:14:07

标签: jsf primefaces converter

传递给select的值的列表是Integer类型。

<p:selectManyMenu id="estabelecimentos" value="#{questionarioMB.estabelecimentosIds}" var="e" converter="#{estabelecimentoConverter}" style="width:100%" filter="true" filterMatchMode="contains" showCheckbox="true">
    <f:selectItems value="#{questionarioMB.estabelecimentos}" var="estabelecimento" itemValue="#{estabelecimento}" itemLabel="#{estabelecimento.nomefantasia}" />
    <p:column>
        <h:outputText value="#{estabelecimentoMB.getIdentificadorByEstabelecimentoId(e.id)}" />
    </p:column>
    <p:column>
        <h:outputText value="#{e.nomefantasia}" />
    </p:column>
</p:selectManyMenu>

Netbeans在outputTexts(“未知属性”)中找不到属性,抛出异常的行如下:

this.estabelecimentosIds.parallelStream().forEach((Integer id) -> {
    this.questionarioBean.insertQuestionarioHasEstabelecimento(this.questionarioBean.getLastId() + 1, id);
});

转换器:

@Named
public class EstabelecimentoConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
        if (value != null && value.trim().length() > 0) {
            try {
                EstabelecimentoMB estabelecimentoMB = (EstabelecimentoMB) fc.getExternalContext().getApplicationMap().get("estabelecimentoMB");
                return estabelecimentoMB.getEstabelecimentos().get(Integer.parseInt(value));
            } catch (NumberFormatException e) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro de Conversão", "Estabelecimento inválido."));
            }
        } else {
            return null;
        }
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object o) {
        if (o != null) {
            return String.valueOf(((Estabelecimento) o).getId());
        } else {
            return null;
        }
    }
}

P.S。:我不能使用字段tradingName,因为它可以在表establishment中重复,因此我必须使用“id”来区分它们。第一列具有该建立的标识符(在另一个表中,“client_has_establishment”,也可以重复 - 但不能用于相同的client_id)。

1 个答案:

答案 0 :(得分:0)

根据BalusC的答案:https://stackoverflow.com/a/13866179/1639141

将转换器更改为JSF内置IntegerConverter

<p:selectManyMenu ... converter="javax.faces.Integer">