2

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

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

我试图嵌入另一个 el 表达式而不是“nameofbean”:

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

但它没有成功。

4

2 回答 2

7

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

例如

<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. 这个不对。

于 2011-05-17T12:36:02.390 回答
3

其他方式:

<h:inputText id="loginField1" value="#{bean1.login}" rendered="someCondition1"/>
<h:inputText id="loginField2" value="#{bean2.login}" rendered="someCondition2"/>
于 2011-05-17T09:49:58.990 回答