Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

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

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

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

And the scope of the Bean is ViewScope

I end up with this error:

Unable to create managed bean receipt. The following problems were found: - The scope of the object referenced by expression #{param.id}, request, is shorter than the referring managed beans scope of view

What can I do?

arjan take a look:

My page: Facelet Title

<form method="post" action="faces/index.xhtml">
  <input name="id" value="4" />
  <input type="submit" value="submit" />
</form>

<h:form>
  <h:commandLink value="click" action="index">
    <f:param id="id" name="id" value="20"/>
  </h:commandLink>
</h:form>

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...