JSF里通过commandButton来传参的一种方法

JSF里通过commandButton来传参的一种方法(转)

假设我的JSF应用中有一个列表,列表的每一行有一个超链接用以处理该行的记录(比如删除该行),如图1所示

图1
上图倒数的第二第三列就是commandlink的实现

如果使用commandLink来传递参数给backingbean的话很方便(这种例子随处可见),就像代码1使用f:param 标签传递每一行的id号一样
代码1
<h:commandLink value="Done" action="#{taskejb.Done}">
    <f:param name="TasktodoParam" value="#{item.todoid}"/>
</h:commandLink>

然后backbean的Done方法可以用代码2取得参数

代码2
String id =
FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(TasktodoParam);

新的需求是把commandLink 换成是commandButton ,就像图1最后的一列。

如果我们简单的把代码1的commandLink 替换成 commandButton,然后用代码2来取参数的话取到的值会是null,随后可能会抛出nullpointexception。

所以采用下面的办法,在commandButton上加一个actionListener,像代码3这样

代码3
<h:commandButton value="Done" action="#{taskejb.Done}"
actionListener="#{taskejb.testListener}">
   <f:attribute name="myAttribute" value="#{item.todoid}" />
</h:commandButton>

backbean的testListener方法用以下方法取得参数

代码4
    public void testListener(ActionEvent e) {
        if (e.getComponent().getAttributes().get("myAttribute") != null) {
            tempParam = e.getComponent().getAttributes().get("myAttribute").toString();
        }
    }

其中String型的全局变量tempParam用以接受传入的参数,实际执行时testListener方法会先于Done方法执行,所以在Done方法中可以使用传入的参数。

另一种方法仍然使用f:param传参,像代码5,6

代码5
<h:commandButton value="Hello" actionListener="#{myBean.myMethod}">
<f:param name="myParam" value="hello" />
</h:commandButton>

 代码6
public void myMethod( ActionEvent e ) {
String myParam = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get( "myParam" ).toString();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值