UISelectOne和UISelectMany组件如何在f:selectItems中预先选择默认值

Ana*_*oly 4 jsf selectonemenu primefaces jsf-2 selectmanymenu

我知道如何preselect <p:selectOneMenu>,在selected中value应该是from中的对象之一<f:selectItems>,但是该组件如何在后台工作,我可以更改此行为吗?

以我为例,我有一个重复的对象,实际上这是两个具有相同值的对象,但是创建了两次,并且所选对象与该对象<p:selectOneMenu>不同,<f:selectItems>并且无法识别它。我很可能会更改设计,因此它会指向同一个对象,但是如果由于遗留代码或其他原因而无法执行该操作,我该如何更改<p:selectOneMenu>它会比较对象的行为id呢?

我以为它是converter负责任的,但是当它呈现时,它不仅会进入getAsObjectmethod getAsString,所以我想这里有些不同,但是又是什么呢?

谢谢

Bal*_*usC 5

Object#equals()用于此。您可以通过在您的实体上相应地实现(更改)此行为。

private Long id;

@Override
public boolean equals(Object other) {
    return (other != null && getClass() == other.getClass() && id != null)
        ? id.equals(getClass().cast(other).id)
        : (other == this);
}
Run Code Online (Sandbox Code Playgroud)

不要忘记hashCode()满足equals-hashCode合同

@Override
public int hashCode() {
    return (id != null) 
        ? (getClass().hashCode() + id.hashCode())
        : super.hashCode();
}
Run Code Online (Sandbox Code Playgroud)

如果由于某些不清楚的原因而无法更改现有实体,请将其包装在您自己的DTO中。

转换器仅在实体及其唯一String表示之间进行转换,以用于HTML输出和HTTP请求参数,因此不会影响预选择。它仅对潜在的验证错误有影响:值无效

也可以看看: