如何在jsf中从另一个访问一个managedbean

时间:2014-12-15 12:07:43

标签: jsf jsf-2.2

我有两个managedbean类(UserBean.java& HelloBean.java)和一个index.xhthl类。在HelloBean.java课程中,我使用了@ManagedProperty anotation来访问UserBean.java的属性,我在HelloBean.java类中有一个方法。

这里,我的班级:

UserBean.java

package com.bean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;


@ManagedBean(name="ubean", eager=true)
@SessionScoped
public class UserBean {

    private String username;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }   
}

HelloBean.java

package com.bean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;


@ManagedBean(name="hellobean", eager=true)
@RequestScoped
public class HelloBean {

    @ManagedProperty(value="#{ubean}")
    private UserBean mbean;
    private String username;

    public String getUsername() {
        if(mbean!=null){
            username=mbean.getUsername();
        }
        return username;
    }

    public void setMbean(UserBean mbean) {
        this.mbean = mbean;
    }

    public UserBean getMbean() {
        return mbean;
    }

    public void showMsg(){  
        System.out.println("UserName :"+username);
    }
}

并且 index.xhtml

<body>
    <h:form>
        <h:inputText id="username" value="#{ubean.username}"></h:inputText>
        <h:commandButton value="submit" action="#{hellobean.showMsg}"></h:commandButton>
    </h:form>
</body>

我想从showMsg()类调用index.xhtml方法。点击commandButton会触发该方法,但它始终返回null而不是inputText值。我的代码中的问题是什么?有人帮忙...... 提前谢谢..

1 个答案:

答案 0 :(得分:0)

此处usernameUserBean.java类的属性。因此,您必须通过父级(username)类的对象调用UserBean.java变量。因此,请尝试mbean.getUsername()而不是仅username