简体   繁体   English

JSF2:带有自定义selectItems的selectOneMenu:选择所有项目

[英]JSF2: selectOneMenu with custom selectItems: all items are selected

Thanks to some great articles here, I've been able to build a <h:selectOneMenu /> with selectItems containing objects. 由于这里有一些很棒的文章,我已经能够使用包含对象的selectItems构建<h:selectOneMenu /> After providing a custom FacesConverter and fixing the missing equals()/hashcode() methods, I am able to use it to change the property of the backing bean and write it out to the DB. 提供自定义FacesConverter并修复缺少的equals()/ hashcode()方法之后,我可以使用它来更改后备bean的属性并将其写到数据库中。

The only weird thing is that all HTML <option /> elements of the <select /> -element are checked="checked" ! 唯一奇怪的是, <select /> -element的所有 HTML <option /> <select />元素都被checked="checked" In other words: the <h:selectOneMenu /> does not reflect the current value of the bound property! 换句话说: <h:selectOneMenu />不能反映绑定属性的当前值!

Details: 细节:

Store.java Store.java

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

  @ManyToOne
  private Category category;

  // getters, setters, equals, hashcode
}

Category.java Category.java

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

  // getters, setters, equals, hashcode
}

editStore.xhtml editStore.xhtml

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

BackingBean.java 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
}

I leave out listing the Category-Converter (it converts between the object and its ID). 我没有列出Category-Converter(它在对象及其ID之间转换)。

The HTML this creates is: 创建的HTML是:

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

Obviously, store.category can only contain one item... why are both option-elements "selected"? 显然, store.category只能包含一个项目...为什么两个选项元素都被“选中”? No matter, what category is assigned to the store, the HTML always "selects" all option-elements. 不管将什么类别分配给商店,HTML总是“选择”所有选项元素。

How does JSF now, which SelectItem should be selected? 现在如何选择应该选择哪个SelectItem JSF?

It's almost certain that the problem is in the equals(..) method, which returns true for all compared objects. 几乎可以确定问题出在equals(..)方法中,该方法对所有比较对象返回true Test this, and let your IDE generate the method (together with hashCode() ) 测试一下,然后让您的IDE生成方法(与hashCode()一起)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM