5

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.

Aritz
  • 29,795
  • 13
  • 135
  • 209
Vovan
  • 1,784
  • 5
  • 24
  • 40

3 Answers3

5

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");
Daniel
  • 36,273
  • 9
  • 115
  • 187
5

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

BalusC
  • 1,040,783
  • 362
  • 3,548
  • 3,513
Aritz
  • 29,795
  • 13
  • 135
  • 209
  • Thank you for your answer, but for some reason this way is not working for me, i've mentioned it [here](http://stackoverflow.com/questions/22018409/what-is-the-correct-way-to-get-parameter-from-url-in-jsf). I am using **GlassFish Server Open Source Edition 4.0**; **Mojarra 2.2.0**; **PrimeFaces 4.0**; **Java 1.7.0_40**. – Vovan Mar 11 '14 at 14:14
  • I've tried it on tomcat server and its work! So the problem in glassfish, but i can not use tomcat for my project. – Vovan Mar 11 '14 at 14:27
  • 1
    Found it ;-) And posted as an answer in your linked question. Hope you to get it working... – Aritz Mar 11 '14 at 14:41
  • Easier: `#{bean.sayIt(param.id)}` – BalusC Jan 26 '16 at 21:17
1

Just for the fun of it, have you tried request.getParameter('id')?

boky
  • 785
  • 4
  • 10