简体   繁体   中英

Pass Parameter to ViewScoped Bean

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

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM