简体   繁体   English

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

[英]how to access one managedbean from another in jsf

I have two managedbean class( UserBean.java & HelloBean.java ) and one index.xhthl class. 我有两个ManagedBean类( UserBean.javaHelloBean.java )和一个index.xhthl类。 In HelloBean.java class, I have used @ManagedProperty anotation for accessing the property of UserBean.java and I have a method within HelloBean.java class. HelloBean.java类中,我使用@ManagedProperty批注来访问UserBean.java的属性,并且在HelloBean.java类中有一个方法。

here, my classes: 在这里,我的课:

UserBean.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 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);
    }
}

And, index.xhtml 而且, 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>

I want to invoke the showMsg() method from index.xhtml class. 我想从index.xhtml类调用showMsg()方法。 The method is fired by clicking commandButton , but it always returns null instead of inputText value. 通过单击commandButton会触发该方法,但它始终返回null而不是inputText值。 What's the problem in my codes. 我的代码有什么问题。 Someone, helps... Thanks in advance.. 有人帮忙...提前谢谢..

Here username is the property of UserBean.java class. 这里的usernameUserBean.java类的属性。 As a result, you must have to call the username variable through a object of the parent( UserBean.java ) class.So, try it, mbean.getUsername() instead of only username . 结果,您必须通过父类( UserBean.java )类的对象调用username变量,因此请尝试使用mbean.getUsername()而不是仅username

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM