Search code examples
jsf-2selectmanylistbox

<f:selectItems> are not rendered in <h:selectManyListbox>


I'm starting with JSF, and trying to get the following simple example working, but it just displays an empty rectangle

The java bean code is:

import javax.faces.model.SelectItem;
import java.util.*;

public class SItemsBean
{ 
  private List options;
  public SItemsBean() 
  {
  options = new ArrayList();
  SelectItem option = new SelectItem("ch1", "choice1", "This bean is for selectItems tag", true);
  options.add(option);
  option = new SelectItem("ch2", "choice2");
  options.add(option);
  option = new SelectItem("ch3", "choice3");
  options.add(option);
  option = new SelectItem("ch4", "choice4");
  options.add(option);
  option = new SelectItem("ch5", "choice5");
  options.add(option);
  }

   public void setOptions(List opt)
  {
   options = opt;
  }

   public List getOptions()
  {
   return options;
  }
}

and the xhtml code is:

<h:form>
<h:outputText value="Select choices given below :"/><br/><br/>
<h:selectManyListbox id="subscriptions" value="#{SItemsBean.options}" size="3">
<f:selectItems value="#{SItemsBean.options}" />
</h:selectManyListbox>
</h:form>

and appended the following in faces-config.xml:

<managed-bean>
    <managed-bean-name>sItemsBean</managed-bean-name>
    <managed-bean-class>sItemsBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <display-name>options</display-name>
        <property-class>java.util.List</property-class>
    </managed-property>     
</managed-bean>

Solution

  • Your problem is caused by having the following managed property:

    <managed-property>
        <display-name>options</display-name>
        <property-class>java.util.List</property-class>
    </managed-property>     
    

    Managed properties are set after the bean is constructed. This one basically sets the options property with an empty list and thus overrides the list which you've diligently populated in the bean's constructor.

    I'm not sure why you configured it like that, but I believe that you misunderstood the purpose of <managed-property>. It's not intented to "declare" all available properties of the bean, no, it instead sets the properties of the bean to the specified values after bean's construction.

    To solve your concrete problem, just remove that <managed-property> from your faces-config.xml.


    Unrelated to the concrete problem, are you sure that you're learning from the right JSF resources? The code which you've posted so far is typical for the old JSF 1.x and does not use any of the new JSF 2.x features such as @ManagedBean at all. Assure that you're learning from the right JSF resources, because in JSF 2.x a lot of things are done differently (much better) than in JSF 1.x.

    See also: