JSF f:使用List错误的selectItems

时间:2011-12-30 19:19:24

标签: java jsf

Facelet代码:

<h:selectOneMenu id = "country" label = "country" value = "#{beanController.countryResidence}">
    <f:selectItems value = "#{countries.countries}" />
</h:selectOneMenu>

Bean代码:

@ManagedBean(eager=true, name = "countries")
@ApplicationScoped
public class CountriesConstants {
        private List<SelectItem> countries;
        public CountriesConstants(){
            countries.add(new SelectItem("DE", "Germany"));
            countries.add(new SelectItem("JA", "Japan"));
            countries.add(new SelectItem("RU", "Russia"));
            countries.add(new SelectItem("US", "United States"));
        }
        public List<SelectItem> getCountries() {
            return countries;
        }
        public void setCountries(List<SelectItem> countries) {
            this.countries = countries;
        }
}

错误

严重:加载应用时出现异常

SEVERE: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.RuntimeException: com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: com.mysite.util.CountriesConstants.

我一步一步地遵循了一些教程,但我一直收到这个错误。我尝试使用List static 并初始化静态块中的值,但是我得到了同样的错误。

修改

新的 Bean代码

@ManagedBean(eager=true, name="constants")
@ApplicationScoped
public class Constants {

    public static final String VALIDATE_DETAILED = "detailed";
    public static final List<SelectItem> countries;

    static{
        countries = new ArrayList<SelectItem>();
        countries.add(new SelectItem("DE", "Germany"));
        countries.add(new SelectItem("JA", "Japan"));
        countries.add(new SelectItem("RU", "Russia"));
        countries.add(new SelectItem("US", "United States"));
    }

    public List<SelectItem> getCountries() {
        return countries;
    }
}

这似乎有效但我觉得很奇怪我可以用非静态方法访问静态属性。如果我删除 getCOuntries()方法,则会抛出错误,指出没有国家/地区属性存在

3 个答案:

答案 0 :(得分:2)

在你的bean构造函数中,你必须先创建你的List,试试这个:

public CountriesConstants(){
   countries = new LinkedList<SelectItem>();
   countries.add(new SelectItem("DE", "Germany"));
   countries.add(new SelectItem("JA", "Japan"));
   countries.add(new SelectItem("RU", "Russia"));
   countries.add(new SelectItem("US", "United States"));
}

此外,您的<f:selectItems>标记应具有更多属性。像这样:

<f:selectItems value="#{countries.countries}" var="c" itemLabel="#{c.name}" itemValue="#{c.id}" />

更新:假设您有以下控制器

@ManagedBean
@RequestScoped
public class BeanController {
   private String countryResidence;
}

答案 1 :(得分:2)

首先初始化arrayList

private List<SelectItem> countries = new ArrayList<SelectItem>();

您的facelets代码似乎很好

答案 2 :(得分:2)

private final List<SelectItem> countries = new ArrayList<SelectItem>();

如果要使classes对象不再被实例化,请将List初始化并声明为“final”。使用final是一种很好的做法,它也提高了代码的可读性。