将HTTP GET参数传递给JSF Bean方法

6

我想把从URL中获取的GET参数传递给一个通过点击按钮调用的方法。例如,我有这样一个URL:/someurl/semepage.xhtml?id=1。而且我页面上有一个按钮:

<p:commandButton value="say it" action="#{test.sayIt(param['id'])}"/>

这个bean看起来像:
@ManagedBean
@ViewScoped
public class Test{
    public void sayIt(String value){
        System.out.println(value);
    }
}

但是当我点击按钮时,它就没有反应。为什么会这样?方法甚至没有被调用。

如果我像这样静态地传递参数:

<p:commandButton value="say it" action="#{test.sayIt('someword')}"/> 

一切正常。

3个回答

6

这是一种方法 - 使用<f:param,像这样:

<h:commandButton value="Test The Magic Word" action="#{test.sayIt}">
    <f:param name="id" value="#{param['id']}"></f:param>
    <f:ajax execute="something" render="something_else"></f:ajax>
</h:commandButton>

在你的bean中
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
        .getRequest();

String id = request.getParameter("id");

这个可以工作!但是当我点击按钮后,浏览器中的“?id=1”会被移除。不管怎样,谢谢! - Vololodymyr
如果你不想要整个页面重新加载 -> 添加 <f:ajax>,更新我的答案。 - Daniel

5

@Daniel的回答没问题,但是这里有一个更简单的JSF 2-ish替代方案,使用和EL参数传递。请注意,在此情况下不需要,因为默认具有ajax行为。

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:p="http://primefaces.org/ui">
<h:head />
<h:body>
    <f:metadata>
        <f:viewParam name="id" />
    </f:metadata>
    <h:form>
        <p:commandButton value="say it" action="#{bean.sayIt(id)}" />
    </h:form>
</h:body>
</html>

@ManagedBean
@ViewScoped
public class Bean implements Serializable {

    public void sayIt(String value) {
        System.out.println(value);
    }

}

已在JSF 2.2.5和Primefaces 4上进行测试。如果使用JSF 2.1.x,请记得更改标签名称空间。


谢谢您的回答,但出于某些原因,这种方法对我不起作用,我在这里提到了它(https://dev59.com/tXzaa4cB1Zd3GeqPWOxy)。 我正在使用GlassFish Server Open Source Edition 4.0; Mojarra 2.2.0; PrimeFaces 4.0; Java 1.7.0_40。 - Vololodymyr
我已经在Tomcat服务器上尝试过了,它可以工作!所以问题出在Glassfish上,但是我不能在我的项目中使用Tomcat。 - Vololodymyr
1
找到了;-) 并在您链接的问题中发布为答案。希望您能让它正常工作... - Aritz
更简单的写法:#{bean.sayIt(param.id)} - BalusC

1

只是为了好玩,你试过使用request.getParameter('id')吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接