关于JSF中托管bean之间的通信

时间:2010-05-06 08:08:29

标签: jsf facelets

我之前关于托管bean的问题似乎并不清楚。所以,我会以更系统的方式再次发布它。

我有一页:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <ui:insert name="head">

        </ui:insert>

        <br/><br/>
        <h:inputText value="#{MasterBean.laala}"/>
        <br/><br/>

        <ui:insert name="content">

        </ui:insert>
    </h:body>
</html>

这是它的bean:

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


@ManagedBean(name="MasterBean")
@ViewScoped
public class MasterBean {

    private String laala;

    public String getLaala() {
        return laala;
    }

    public void setLaala(String laala) {
        this.laala = laala;
    }


    public MasterBean() {
    }

}

这是使用master.xhtml的data.xhtml:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <ui:composition template="master.xhtml">
            <ui:define name="head">
                laala
            </ui:define>

            <h:outputText value="#{pageBean.content}"/>

            <ui:define name="content">
                <h:commandButton actionListener="#{pageBean.speakHello}"/>
            </ui:define>>


        </ui:composition>
    </h:body>
</html>

这是它的bean:

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


@ManagedBean(name="pageBean")
@ViewScoped
public class pageBean {

    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }


    public void speakHello(){
        //how do i get value of laaala here which is in MasterBean???
        content = ??? + " Hello friend";
    }

    public pageBean() {
    }

}

我应该在speakHello()中标记???的空白处放置什么。如何在这个bean中获取其他bean的值?

1 个答案:

答案 0 :(得分:4)

您可以在JSF2 tutorial中学习,可以使用依赖注入功能。在您的情况下,它将向MasterBean注入pageBean实例。我相信你可以在pageBean

中找到类似的内容
@ManagedBean(name="pageBean")
@ViewScoped
public class pageBean {

    private String content;

    @ManagedProperty(value="#{MasterBean}")
    private MasterBean masterBean;

    ...

a然后在你的方法中使用它:

 public void speakHello(){
    //how do i get value of laaala here which is in MasterBean???
    content = masterBean.getLaala() + " Hello friend";
 }

我自己没试过。我希望它能奏效。

顺便说一下,强烈建议不要用小写字母开始上课。因此pageBean类应该被称为PageBean