1
votes

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.

2
How are you able to execute both #{bean.execute} and #{bean.attribute} in the same request?kolossus
I have no problem to execute this code. The commandLink sets the value to true and this value remains the same when clicking the button. I'm with Mojarra JSF 2.2.7, which version are you using?Xtreme Biker

2 Answers

0
votes

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

0
votes

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);
}