Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass HTTP GET parameter to a JSF bean method

i want to pass GET parameter from URL to a method, that called by clicking on button. For example i have URL: /someurl/semepage.xhtml?id=1. And i have a button on my page:

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

The bean looks like:

@ManagedBean
@ViewScoped
public class Test{
    public void sayIt(String value){
        System.out.println(value);
    }
}

But when i am clicking on button, its just not react. Why is this happen ? Method even not called.

If i pass arguments staticaly like here:

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

everything is ok.

like image 616
Vovan Avatar asked Mar 09 '14 11:03

Vovan


2 Answers

Here is one way - using the <f:param, like this:

<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>

And in your bean

HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
        .getRequest();

String id = request.getParameter("id");
like image 148
Daniel Avatar answered Sep 25 '22 19:09

Daniel


@Daniel's response is OK, but here it goes a simpler JSF 2-ish alternative for your case, using <f:viewParam /> and EL parameter passing. Note the <f:ajax /> is not needed in this case, as <p:commandButton /> has ajax behaviour by default.

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

}

Tested with JSF 2.2.5 and Primefaces 4. Remember changing tag namespaces in case of using JSF 2.1.x.

like image 26
Xtreme Biker Avatar answered Sep 26 '22 19:09

Xtreme Biker