---
title: "JSF里通过commandButton来传参的一种方法"
author: "seven0_0"
date: "2010-06-29T17:21:32Z"
tags: []
categories: ["企业架构"]
slug: "jsf-commandbutton"
draft: false
lastmod: "2010-06-29T17:21:32Z"
id: 701868
url: "https://sevenjava.iteye.com/blog/701868"
---

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

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

**图1**[](http://haadyg.blu.livefilestore.com/y1pddIsebtPk0dV19UFcXiJ4pcJlQHKxckzr5kAU5clFI2T4SRSQSNgVjrhXqZk-D4GuF8TKnbaT_I?PARTNER=WRITER)  
上图倒数的第二第三列就是commandlink的实现

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

然后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**  
&lt;h:commandButton value="Done" action="#{taskejb.Done}"  
**actionListener="#{taskejb.testListener}"&gt;**  
   **&lt;f:attribute name="myAttribute" value="#{item.todoid}" /&gt;**  
&lt;/h:commandButton&gt;

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**  
&lt;h:commandButton value="Hello" actionListener="#{myBean.myMethod}"&gt;  
&lt;f:param name="myParam" value="hello" /&gt;  
&lt;/h:commandButton&gt;

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