jaec86
jaec86

Reputation: 45

Pass a param from ManagedBean to jsf page

I am working with JSF 2.2 and Tomcat 8 and I am just starting to play with them.

I have a command button in a jsf page.

<h:commandButton id="newObject" value="New Object" action="#{someObject.someAction}">
<f:param name="object_id" value="#{someObject.object_id}" />
</h:commandButton>

The ManagedBean is similar to this:

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
@ManagedBean
public class SomeObject implements Serializable{
    private static final long serialVersionUID = 1L;
    private int object_id;
    public int getObject_id() {
        return object_id;
    }
    public void setObject_id(int object_id) {
        this.object_id = object_id;
    }
    public String someAction() {
        setObject_id(sqlInsert());
        if(getObject_id() != 0) {
            System.out.println(getObject_id());
            return "new_page";
        }
    }
}

The sqlInsert method is working fine. I use it to insert a new row in some sql table and get the auto generated key, which is an int. If the insert did not happen it would return 0.

I can navigate to the new_page, but the param object_id is 0. I added println to show the object_id and it is the actual key.

What am I doing wrong?

Upvotes: 0

Views: 82

Answers (1)

Kishor Prakash
Kishor Prakash

Reputation: 8151

Since you are using the only @ManagedBean annotation on your Managed Bean and not specifying any Scope of you bean explicitly, your Bean will act as if its a @RequestScoped bean.[See link]

So every time you click your New Object button, the Bean is re initialized and you will loose the state(variable values).

Think and decide which scope you want to use [See link]. For your requirements @ViewScoped might do the job for you.

Upvotes: 1

Related Questions