Search code examples
javajsfjsf-2managed-bean

jsf dynamic change of managedbean


How can I dynamically change managed bean of "value" attribute? For example, I have h:inputText and, depending on typed-in text, managed bean must be #{studentBean.login} or #{lecturerBean.login}. In a simplified form:

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

I tried to embed another el-expression instead of 'nameofbean':

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

but it doesn't worked out.


Solution

  • Polymorphism should rather be done in the model, not in the view.

    E.g.

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

    with

    public interface Person {
        public void login();
    }
    

    and

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

    and

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

    and finally in the managed 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";
    }
    

    Otherwise you have to change the view everytime when you add/remove a different type of Person. This is not right.