Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling bean methods with arguments from JSF pages

Tags:

jsf

primefaces

Is it possible to call bean methods & directly pass parameters to them from the view instead of requiring to first set the bean properties and then call methods without arguments using the commandButton or similar ?

I have a list of items with each item having a list of actions. To reduce the state, I am using a single primefaces remoteCommand, in place of several commandButton(s). On getting a action trigger from the view, I would call the remoteCommand from javascript but since the remoteCommand is one but used for multiple items thus I need to pass the id of the item as well. I am wondering if there is a way to pass the id of the item to the bean method directly as an argument instead of first setting it as a bean property ? Is there any way to do so ?

Actually I am looking at a better way to deal with multiple commandButtons on a page when there's a long list of items on the page.

Suggestions ? Thanks.


Using JSF 2.1.6 Mojarra with Primefaces 3.0RC1

like image 530
Rajat Gupta Avatar asked Dec 25 '11 19:12

Rajat Gupta


1 Answers

Passing method arguments is supported since EL 2.2 which is part of Servlet 3.0. So if your webapp runs on a Servlet 3.0 compatible container (Tomcat 7, Glassfish 3, etc) with a web.xml declared conform Servlet 3.0 spec (which is likely true as you're using JSF 2.1 which in turn implicitly requires Servlet 3.0), then you will be able to pass method arguments to bean action methods in the following form:

<h:commandButton value="Submit" action="#{bean.submit(item.id)}" />

with

public void submit(Long id) {
    // ...
}

You can even pass fullworthy objects along like as:

<h:commandButton value="Submit" action="#{bean.submit(item)}" />

with

public void submit(Item item) {
    // ...
}

If you were targeting a Servlet 2.5 container, then you could achieve the same by replacing the EL implementation by for example JBoss EL which supports the same construct. See also Invoke direct methods or methods with arguments / variables / parameters in EL.

like image 175
BalusC Avatar answered Sep 22 '22 21:09

BalusC