JSF - 为什么SessionScoped类的实例未初始化?

时间:2013-01-04 19:04:43

标签: java jsf jboss managed-bean

我不想在selectOneMenue中显示我的枚举类[license]的值。

<h:selectOneMenu id="licenseclassmenue" >
            <f:selectItem itemLabel="select license"/>
                <f:selectItems value="#{licenseCodes.licenseCodes}"/>
            </h:selectOneMenu><br />

我的licenseCode类:

/**
 * convert enum to array of strings
 * 
 * */
@ManagedBean(name = "licenseCodes" )
@SessionScoped
public class LicenseCodes {

public SelectItem[] getLicenseCodes() {
    SelectItem[] licenses = new SelectItem[License.values().length];
    int i = 0;
    for (License l : License.values()) {
        licenses[i++] = new SelectItem(l, l.name());
    }
    return licenses;
}

}

枚举

public enum License {
A("A"),B("B"),C("C");

    private String value;

    private License(String v) {
        this.value = v;
    };

}

部署项目时,selectOneMenue中不会有任何许可证。 在调试期间,我注意到永远不会调用getLicenseCodes()。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

这是你的班级:

package so.question14163260;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.model.SelectItem;

@ManagedBean(name = "licenseCodes")
@SessionScoped
public class LicenseCodes {

    private SelectItem[] licenses;

    public LicenseCodes() {
        System.out.println("================Inside===============");
    }

    @PostConstruct
    public void init() {
        SelectItem[] licenses = new SelectItem[License.values().length];
        int i = 0;
        for (License l : License.values()) {
            licenses[i++] = new SelectItem(l, l.name());
        }

        setLicenses(licenses);
    }

    public SelectItem[] getLicenses() {
        return licenses;
    }

    public void setLicenses(SelectItem[] licenses) {
        this.licenses = licenses;
    }
}

这是xhtml:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets">

    <h:head></h:head>
    <h:body>
        <h:selectOneMenu id="licenseclassmenue" >
            <f:selectItem itemLabel="select license"/>
                <f:selectItems value="#{licenseCodes.licenses}"/>
            </h:selectOneMenu>
    </h:body>
</html>

这是截图

enter image description here

你可以看到它正在发挥作用。

更新

我在测试时忘了添加@SessionScoped注释。现在添加它之后也有效。