0

I have a bean with as managedproperty another bean:

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

    ....
}

Bean2 is correctly create, but navigation from bean1.xhtml to bean2.xhtml create another instance of Bean2, so I lost every parameter setted from Bean1. Bean1 and Bean2 are @ViewScoped.

Where am I wrong?

xc93hil
  • 105
  • 1
  • 9

1 Answers1

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>

It is working at my end, it is working even when i change the @ViewScope to @SessionScope too. if you want some more info, please rewrite your question with more info about your code. thanks

ankush yadav
  • 422
  • 3
  • 13