2

I'm going to pass a parameter from one page (Facelet) to a Managed Bean whose scope is View Scope.

I try to do it like this:

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

@ManagedBean
@ViewScoped
public class Mybean {
  private int id;


  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }    
}

First page:

  <h:body>            
    <h:form>
      <h:commandLink value="click" action="index">
        <f:setPropertyActionListener target="#{mybean.id}" value="20"/>
      </h:commandLink>
    </h:form>
  </h:body>

second page:

  <h:body>
    param value #{param.id}
    <br />
    bean value #{mybean.id}
    <br />

    <h:messages/>
  </h:body>

But it does not show 20

ehsun7b
  • 4,796
  • 14
  • 59
  • 98

1 Answers1

1

@ViewScoped bean stays only for the view that the user is watching.

Once the user switched to another view - the bean is being destroyed and created from scratch. Therefore, if you want to use the same bean for more than one page - use @SessionScoped bean.

Another way, is to create a Singleton class in Java, and one bean will update the value in this class, while the other bean will extract the value from it.

Dejell
  • 13,947
  • 40
  • 146
  • 229
  • You are right, and I can change it to RequestScope too, right? – ehsun7b Jan 03 '11 at 11:59
  • 2
    The singleton class will keep the values like an ApplicationScoped bean! I mean the value will be the same for all visitors, won't be? – ehsun7b Jan 03 '11 at 12:01
  • You are right! so you can use session scope bean to store the values if it's for many users – Dejell Jan 03 '11 at 13:13