`
seven0_0
  • 浏览: 27351 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

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

    博客分类:
  • Jsf
阅读更多

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics