jsf管理bean的动态变化

时间:2011-05-17 05:44:17

标签: java jsf jsf-2 managed-bean

如何动态更改“value”属性的托管bean?例如,我有h:inputText,并且根据输入的文本,托管bean必须是#{studentBean.login}或#{lecturerBean.login}。以简化形式:

<h:inputText id="loginField" value="#{'nameofbean'.login}" />

我试图嵌入另一个el-expression而不是'nameofbean':

value="#{{userBean.specifyLogin()}.login}"

但它没有成功。

2 个答案:

答案 0 :(得分:6)

多态性应该在模型中完成,而不是在视图中完成。

E.g。

<h:inputText value="#{person.login}" />

public interface Person {
    public void login();
}

public class Student implements Person {
    public void login() {
        // ...
    }
}

public class Lecturer implements Person {
    public void login() {
        // ...
    }
}

最后在托管bean中

private Person person;

public String login() {
    if (isStudent) person = new Student(); // Rather use factory.
    // ...
    if (isLecturer) person = new Lecturer(); // Rather use factory.
    // ...
    person.login();
    // ...
    return "home";
}

否则,每次添加/删除不同类型的Person时都必须更改视图。这不对。

答案 1 :(得分:3)

另一种方式:

<h:inputText id="loginField1" value="#{bean1.login}" rendered="someCondition1"/>
<h:inputText id="loginField2" value="#{bean2.login}" rendered="someCondition2"/>