f:selectItems不在视图中呈现复选框

时间:2014-08-14 02:52:12

标签: jsf jsf-2 managed-bean selectmanycheckbox

我正在尝试使用f:selectItems渲染几个复选框,但网页不会按预期显示复选框。请查看下面的代码,让我知道我错过了什么。

HTML:

    <h:form  prependId="false">
        <table align="left" cellspacing="5">
            <tr>
                <td align="right" valign="top"><h:outputText value="#{msgs.interests}" /></td>
                <td align="left" valign="top">
                    <h:selectManyCheckbox value="#{testBean.interests}">
                        <f:selectItems value="#{testBean.checkBoxItems}" />
                    </h:selectManyCheckbox>
                </td>
            </tr>
            <tr>
                <td align="right" valign="top"><h:commandButton value="#{msgs.save}" /></td>
                <td align="left" valign="top"><h:commandButton value="#{msgs.cancel}" /></td>
            </tr>
        </table>
    </h:form>

Managed Bean:

  

package com.jsf.ManagedBeans;

     

import javax.inject.Named; import javax.faces.bean.RequestScoped;

     

import javax.faces.model.SelectItem;

     

@Named( “testBean这个”)   @RequestScoped   公共类TestBean {

private int[] interests;
private SelectItem[] checkBoxItems = {
    new SelectItem("Dancing", "Dancing"),
    new SelectItem("Singing", "Singing"),
    new SelectItem("Reading", "Reading"),
    new SelectItem("Writing", "Writing")
};

public SelectItem[] getCheckBoxItems() {

    return checkBoxItems; 
}

public int[] getInterests() {     return interests;
}
public void setInterests(int[] newValue) { 
    interests = newValue; 
} }

1 个答案:

答案 0 :(得分:1)

您希望将CDI范围注释与CDI @Named注释一起使用,并确保为项目启用CDI(存在WEB-INF / beans.xml文件)。

除此之外,将一个调试语句添加到PostConstruct方法以确认正在创建该bean。在构造bean之后,该方法由CDI自动运行。它也可用于初始化bean字段,因为它保证每次实例化运行一次,而不像类构造函数。

package com.jsf.ManagedBeans;

import javax.inject.Named; 
import javax.enterprise.context.RequestScoped;

import javax.faces.model.SelectItem;

@Named @RequestScoped public class TestBean {

  private int[] interests;
  private SelectItem[] checkBoxItems = {
    new SelectItem("Dancing", "Dancing"),
    new SelectItem("Singing", "Singing"),
    new SelectItem("Reading", "Reading"),
    new SelectItem("Writing", "Writing")
  };

  @PostConstruct public void init() {
      System.out.println("testBean initialized");
  }

  public SelectItem[] getCheckBoxItems() {

    return checkBoxItems; 
  }

  public int[] getInterests() {     return interests;
  }
  public void setInterests(int[] newValue) { 
    interests = newValue; 
  }   
}