我以前对托管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()中标记???的空白处输入什么。如何获得该豆中其他豆的价值?

最佳答案

正如您在JSF2 tutorial中所了解的那样,可以使用依赖项注入功能。在您的情况下,这是关于将MasterBean实例注入到pageBean中。我相信您的pageBean中可能会有类似的内容:

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

    private String content;

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

    ...


然后在您的方法中使用它:

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


我自己还没有尝试过。我希望它能起作用。

顺便说一句,强烈建议不要以小写字母开头课程名称。因此,应将pageBean类称为PageBean

10-08 00:54