Setting Managed Bean attribute's value from JSF page and using it in bean's methods

99封情书 提交于 2019-12-11 08:09:08

问题


I have a ViewScoped Managed Bean. In my .xhtml page I want to set bean's attribute's value and use it in methods in the same bean. I managed to set the value from jsf page, but when i want to use it in some method the value of an attribute is not the value i have set before.

Description (xhtml): In this form there is a command link which sets the value of an attribute. And it is working fine. Also, as command link is clicked, second form is being showed.

<h:form>
  <h:commandLink value="Set" >
     <f:setPropertyActionListener target="#{bean.attribute}" value="true" />
     <f:ajax execute="@this" />
  </h:commandLink>
</h:form>

This form executes method that uses attribute's value set before, but the value is not true, its false.

<h:form>
    <h:commandButton id="submit" value="Execute" action="#{bean.execute}" />
</h:form>

Bean:

public void execute(){
    if(isAttribute())
        ---do something---
}

The question is: Why execute() is not reading attribute's value right?

When I use one form, it's working fine. But I need them to be in separated forms.


回答1:


The scope of your bean is incorrect. ViewScoped means that the minute the view is changed, the bean is discarded and re-created for the next view. So, in your case, the original data you had for the first view is lost.

I'm going to refer you to BalusC's blog:

http://balusc.blogspot.co.uk/2010/06/benefits-and-pitfalls-of-viewscoped.html

which states:

A @ViewScoped bean will live as long as you're submitting the form to the same view again and again. In other words, as long as when the action method(s) returns null or even void, the bean will be there in the next request. Once you navigate to a different view, then the bean will be trashed




回答2:


I can't determine of you stay on the same page with both requests. If you do, viewScope should work even in two different forms. If you are navigating from 1 view to another, another viewScope will be created and you will loose the current one.

You could set the value in the sessionScope with java or by annotating the backingNean. But then everything in your backingBean becomes sessionScoped and that might not be needed.

You could also use a spring-like flow scope.

Example to do it with java:

public void callThisAfterFirstClick() {
   Faces.setSessionAttribute(attribute, true)
}

public void callThisAfterSecondClick() {
   Faces.getSessionAttribute(attribute);
}


来源:https://stackoverflow.com/questions/24674198/setting-managed-bean-attributes-value-from-jsf-page-and-using-it-in-beans-meth

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!