【问题标题】:JSF2: selectOneMenu with custom selectItems: all items are selectedJSF2:带有自定义 selectItems 的 selectOneMenu:所有项目都被选中
【发布时间】:2010-10-21 15:48:00
【问题描述】:

感谢这里的一些很棒的文章,我已经能够使用包含对象的 selectItems 构建一个<h:selectOneMenu />。在提供自定义 FacesConverter 并修复缺少的 equals()/hashcode() 方法后,我可以使用它来更改支持 bean 的属性并将其写入数据库。

唯一奇怪的是 所有 HTML <option /> 元素的<select /> 元素是checked="checked"!换句话说:<h:selectOneMenu /> 不反映绑定属性的当前值!

详情:

Store.java

@Entity
public class Store {
  private Long id;
  private String name;

  @ManyToOne
  private Category category;

  // getters, setters, equals, hashcode
}

Category.java

@Entity
public class Category {
  private Long id;
  private String name;

  // getters, setters, equals, hashcode
}

editStore.xhtml

<h:form>
....
  <h:selectOneMenu value="#{backingBean.store.category}" id="category">
    <f:selectItems value="#{backingBean.categorySelectItems}" />
  </h:selectOneMenu>
....
</h:form>

BackingBean.java

public class BackingBean {
  private Store store;

  // inject data-access-facades via @EJB
  // Constructor
  // getters, setters

  public List<SelectItem> getCategorySelectItems
    List<SelectItem> items = new ArrayList<SelectItem>();
    for (Category cat : categoryFacade.findAll() ) {
      items.add(new SelectItem(cat, cat.getName()));
    }
    return items;
  }

  // action methods
}

我没有列出 Category-Converter(它在对象及其 ID 之间进行转换)。

这样创建的 HTML 是:

<select id="category" name="category" size="1">
  <option value="251" selected="selected">Kosmetik</option>
  <option value="222" selected="selected">Sportwaren</option>
</select>

显然,store.category 只能包含 一个 项...为什么两个选项元素都被“选中”?无论为商店分配什么类别,HTML 总是“选择”所有选项元素。

JSF现在怎么样了,应该选哪个SelectItem

【问题讨论】:

    标签: java jsf jsf-2


    【解决方案1】:

    几乎可以肯定问题出在equals(..) 方法中,该方法为所有比较对象返回true。测试一下,让你的 IDE 生成方法(连同hashCode()

    【讨论】:

    • 谢谢!将对其进行测试并报告。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多