@ManagedProperty(value = “#{param.id}”) in a non-request Scope Bean

后端 未结 2 1323
耶瑟儿~
耶瑟儿~ 2020-12-23 10:47

I need to pass a parameter (POST) to a @managedBean, I used managed properties like this:

@ManagedProperty(value = \"#{param.id}\")
private int id;
         


        
2条回答
  •  情书的邮戳
    2020-12-23 11:06

    Two ways:

    1. Make the bean request scoped and inject the view scoped one as another @ManagedProperty.

      @ManagedBean
      @RequestScoped
      public class RequestBean {
      
          @ManagedProperty(value="#{param.id}")
          private Integer id;
      
          @ManagedProperty(value="#{viewBean}")
          private ViewBean viewBean;
      }
      

      The view scoped bean is available during @PostConstruct and action methods of request scoped bean. You only need to keep in mind that the id can get lost when you do a postback to the same view without the parameter.

    2. Or, grab it manually from the request parameter map during bean's initialization.

      @ManagedBean
      @ViewScoped
      public class ViewBean {
      
          private Integer id;
      
          @PostConstruct
          public void init() {
              id = Integer.valueOf(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id"));       
          }
      }
      

      This way the initial id is available during the entire view scope.

提交回复
热议问题