导航后的Primefaces新bean实例

时间:2016-06-28 07:51:02

标签: jsf-2 primefaces backing-beans

我有一个bean作为managedproperty另一个bean:

public class Bean1
{   
    @ManagedProperty(value = "#{bean2}")
    private Bean2 bean2;

    ....
}

Bean2正确创建,但从bean1.xhtml导航到bean2.xhtml 创建另一个Bean2实例,所以我丢失了从Bean1设置的每个参数。 Bean1和Bean2是@ViewScoped。

我哪里错了?

1 个答案:

答案 0 :(得分:0)

Bean1.java

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.view.ViewScoped;

@ManagedBean
@ViewScoped
public class Bean1 {

    @ManagedProperty(value = "#{bean2}")
    private Bean2 bean2;

    @PostConstruct
    public void init() {
        System.out.println("in bean one....");
    }

    public Bean2 getBean2() {
        return bean2;
    }

    public void setBean2(Bean2 bean2) {
        this.bean2 = bean2;
    }

    public String changetoview() {
        return "bean2";
    }
}

Bean2.java

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

@ManagedBean
@ViewScoped
public class Bean2 {

    private String nameOfBean;

    public String getNameOfBean() {
        return nameOfBean;
    }

    public void setNameOfBean(String nameOfBean) {
        this.nameOfBean = nameOfBean;
    }

}

bean1.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">
<h:head>
    <title>bean1</title>
</h:head>
<h:body>
    <h:form>
        <h:inputText value="#{bean1.bean2.nameOfBean}"></h:inputText>
        <h:commandButton action="#{bean1.changetoview}"
            value="Login"></h:commandButton>
    </h:form>
</h:body>
</html>

Bean2.xhmtl

<?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">
<h:head>
    <title>bean2</title>
</h:head>
<h:body>
    <h:form>dd
        <h:outputLabel value="#{bean2.nameOfBean}"></h:outputLabel>
    </h:form>
</h:body>
</html>

它正在我的工作中,即使我将@ViewScope更改为@SessionScope也正常工作。 如果您想了解更多信息,请使用有关您的代码的更多信息重写您的问题。感谢