简体   繁体   English

从ManagedBean传递参数到jsf页面

[英]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. 我正在使用JSF 2.2和Tomcat 8,现在才开始使用它们。

I have a command button in a jsf page. 我在jsf页面中有一个命令按钮。

<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: ManagedBean与此类似:

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. sqlInsert方法工作正常。 I use it to insert a new row in some sql table and get the auto generated key, which is an int. 我用它在某些sql表中插入新行并获取自动生成的键,它是一个int。 If the insert did not happen it would return 0. 如果未发生插入,则将返回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. 我可以导航到new_page,但是参数object_id为0。我添加了println以显示object_id,它是实际的键。

What am I doing wrong? 我究竟做错了什么?

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] 由于您在受管Bean上仅使用@ManagedBean批注,并且未明确指定Bean的任何作用域,因此您的Bean就像其@RequestScoped Bean一样起作用。[查看链接]

So every time you click your New Object button, the Bean is re initialized and you will loose the state(variable values). 因此,每次单击“ New Object按钮时,都会重新初始化Bean,并且会丢失状态(变量值)。

Think and decide which scope you want to use [See link] . 考虑并决定您要使用的范围[查看链接] For your requirements @ViewScoped might do the job for you. 根据您的要求, @ViewScoped可以为您完成这项工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM