4 ways to pass parameter from JSF page to backing bean

As i know,there are 4 ways to pass a parameter value from JSF page to backing bean :

  1. Method expression (JSF 2.0)
  2. f:param
  3. f:attribute
  4. f:setPropertyActionListener

Let see example one by one :

1. Method expression

Since JSF 2.0, you are allow to pass parameter value in the method expression like this #{bean.method(param)}.

JSF page…


<h:commandButton action="#{user.editAction(delete)}" />

Backing bean…


@ManagedBean(name="user")
@SessionScoped
public class UserBean{

	public String editAction(String id) {
	  //id = "delete"
	}

}	
Note
If you are deploy JSF application in servlet container like Tomcat, make sure you include the “el-impl-2.2.jar” properly. For detail, please read this article – JSF 2.0 method expression caused error in Tomcat.

2. f:param

Pass parameter value via f:param tag and get it back via request parameter in backing bean.

JSF page…


<h:commandButton action="#{user.editAction}">
	<f:param name="action" value="delete" />
</h:commandButton>

Backing bean…


@ManagedBean(name="user")
@SessionScoped
public class UserBean{
 
	public String editAction() {

	  Map<String,String> params = 
                FacesContext.getExternalContext().getRequestParameterMap();
	  String action = params.get("action");
          //...

	}

}

See a full f:param example here.

3. f:atribute

Pass parameter value via f:atribute tag and get it back via action listener in backing bean.

JSF page…


<h:commandButton action="#{user.editAction}" actionListener="#{user.attrListener}"> 
	<f:attribute name="action" value="delete" />
</h:commandButton>

Backing bean…


@ManagedBean(name="user")
@SessionScoped
public class UserBean{
 
  String action;
  
  //action listener event
  public void attrListener(ActionEvent event){
 
	action = (String)event.getComponent().getAttributes().get("action");
 
  }
  
  public String editAction() {
	//...
  }	
  
}

See a full f:attribute example here.

4. f:setPropertyActionListener

Pass parameter value via f:setPropertyActionListener tag, it will set the value directly into your backing bean property.

JSF page…


<h:commandButton action="#{user.editAction}" >
    <f:setPropertyActionListener target="#{user.action}" value="delete" />
</h:commandButton>

Backing bean…


@ManagedBean(name="user")
@SessionScoped
public class UserBean{
 
	public String action;
    
	public void setAction(String action) {
		this.action = action;
	}
 
	public String editAction() {
	   //now action property contains "delete"
	}	
  
}

See a full f:setPropertyActionListener example here.

P.S Please share your idea, if you have any other ways :)

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Raul Serra
Guest
Raul Serra

Hello everyone,
And if you want to use the data entered in a

as JasperReport step for availing the user you have entered ??
Thank you.

Enissay
Guest
Enissay

Hi thank’s for the explications

in my managedBean I have a method that needs parametres, and i want to get that parameter from an anther class.

so I do that :

but I get ejb exception, but when I give the value manualy ( ) it works

Hoang
Guest
Hoang

Thanks for helpful tutorial

Hai Ba Tu?i
Guest
Hai Ba Tu?i
Method expression: cartBean : public String addToCart(Product p) { this.pro = p; int index = -1; for (ProductItem item : listProductItem) { if(item.getProduct().getIdProduct()==p.getIdProduct()){ item.setQuantity(item.getQuantity()+1); return “cartInfo”; } } ProductItem i = new ProductItem(); i.setProduct(p); i.setQuantity(1); listProductItem.add(i); return “cartInfo”; } WARNING: #{cartShopBean.addToCart(productInfoBean.product)}: java.lang.NullPointerException javax.faces.FacesException: #{cartShopBean.addToCart(productInfoBean.product)}: java.lang.NullPointerException at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118) at javax.faces.component.UICommand.broadcast(UICommand.java:315) at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790) at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at… Read more »
Cong Pham
Guest
Cong Pham

Comment demo

saum
Guest
saum

could you please tell me how can we populate the values of page1 to next page2. I new to JSF.. Please help!!

ArunRaj
Guest
ArunRaj

Can I pass Client side JS value in the param attribute ? For eg: Consider collecting values in JS array or JSON array at the client side. Can I pass those array values in the server side by parameter attribute ?

jado pado
Guest
jado pado

why copy paste? why? why?

ram
Guest
ram
before executing the page is showing error with red color below piece of code: Even The sample code i imported to my local machine ,it is not working plz get rid of me this problem My Server is : jboss-as-7.1.1.Final pom.xml is 4.0.0 com.mkyong.common JavaServerFaces war 1.0-SNAPSHOT JavaServerFaces Maven Webapp http://maven.apache.org <!– For Java EE Application Server, uncomment this library and comment the rest of the libraries javax.faces jsf-api 2.0 provided –> com.sun.faces jsf-api 2.1.0-b03 com.sun.faces jsf-impl 2.1.0-b03 org.glassfish.web el-impl 2.2 javax.servlet jstl 1.2 javax.servlet javax.servlet-api 3.0.1 javax.servlet.jsp jsp-api 2.1 <!– too old com.sun.el el-ri 1.0 –> java.net.m2 java.net m2… Read more »
jado pado
Guest
jado pado

ram why is your ram going out of order? clean it well

Bharat
Guest
Bharat

Map params =
FacesContext.getExternalContext().getRequestParameterMap();

Use this
Map params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

max
Guest
max

true, hope that mkyong update the post.

Kadir
Guest
Kadir

I am from Turkey. I am trying to develop a web site by using JSF (with PrimeFaces showcase) framework. But i am new for this subject. I find the answers to all the questions on JSF in your site. Congratulations for this. Thank you.

Vursana Lan
Guest
Vursana Lan

AJ.. AJ.. AJEY.. Hey Yavrum Hey..

44 > 23

SAYGI

Hey yavrum hey türke bak ingilizce yorum vay be Kadir

LOun
Guest
LOun

VUR MUSTO VUR DUVARA.

Ankaral? Hakk?
Guest
Ankaral? Hakk?

LAN KADIR CEVAP VERSENE OGLEM

Hakan Hakki
Guest
Hakan Hakki

BIR KABUS DEGIL DEGILSE NE KENDINE GELEMEZ CIKARSA MUHAREBE.. AJ.. AJ.. AJEY… EFSANE… ?EKIL…

mlblount45
Guest
mlblount45

Can you update the first option to include the single quotes around the input parameter delete

tegoo
Guest
tegoo

I thing the 4th method is the best. Thank’s a lot for you. Also hidden forms may be used, but I don’t think it is a good idea.

tegoo
Guest
tegoo

*think

Carlos Arturo
Guest
Carlos Arturo

Hello friends, greets, Please I need send a Object that represent a POJO with getters and setters to other xhtml and this can see it in a datatable, bone I have a object person so var=person from datatable and showit in other datatable sending to bean or from other way, Please helpme and exuse me my english thanks. to everyone

Caio
Guest
Caio

Hello,

how can I parameterize a list with an “a4j:commandButton”?

thanks

Caio.

Shubham
Guest
Shubham
Holger
Guest
Holger

Is method 1 still valid and if yes can complex types be used?

e.g.

<h:commandButton action="#{user.addUser(user)}" />
@ManagedBean(name="user")
@SessionScoped
public class UserBean{
	public String addUser(User user) {
	  //do something with the user
	}
}

Don’t seem to be able to get something like this working…

Thanks

Gawro
Guest
Gawro

I do use complex type using the first method and yes, it works for me

vijayan
Guest
vijayan

Please tell me about Difference between managed bean and backing bean?

tunnaruto
Guest
tunnaruto

There is not, they are the same thing

Maoduy
Guest
Maoduy

I don’t know why i used the first way, and i got following error:

javax.servlet.ServletException: /index.xhtml @47,103 action=”#{dbBean.getEditAction(list)}” Failed to parse the expression [#{dbBean.getEditAction(list)}]
javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)

Please help me!

saeed
Guest
saeed

thank you very much.

LG
Guest
LG

Very nice post, Helpfull .
Keep writing .

hannibaldaturn
Guest
hannibaldaturn

Is possible use for the example below:

<h:outputText id="field1" value="#{myMB.methodWithParam('teste')}" />

or

<h:inputText id="field1" value="#{myMB.methodWithParam('teste')}" />

?

Thanks for your post.

Douglas Junior
Guest
Douglas Junior

I have the same question as you.

Gonzalo
Guest
Gonzalo

A simple bug

Method 1
Map params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

Markus
Guest
Markus

Hi. Thanks for the post! Helped me out allready TWICE.

Jim
Guest
Jim

Examples 1,3 & 4 doesn’t work if the Bean’s uses the RequestScope. Did you any idea’s how to solve this without fetching the request param’s in the @PostConstruct method?

Eddy
Guest
Eddy

Thank you for this article! Really helped me :-)

curious
Guest
curious

Do they have advantage one over the other, i mean if 1 can why 4 ways to do the same thing.

Kawu
Guest
Kawu

The most complicated variant I’ve successfully used is a call including a parameter from within a ui:include’d sub view (Method 1 + ui:include):

Client:

<ui:include src="...">
  <ui:param name="documentId" value="#{doc.id}" />
  <ui:param name="acceptButtonBean" value="#{repoHome}" />
  <ui:param name="acceptButtonAction" value="removeIndividualDocument(documentId})" />
</ui:include>

Sub view:

<h:commandButton value="Continue"
                 action="#{acceptButtonBean[acceptButtonAction]}" />
  ...
</h:commandButton>

This works great for lists that have a delete button to the right. HTH anybody

Kawu
Guest
Kawu

Please delete the above, it’s not working.

domgom
Guest
domgom

Before of getting mad trying to make EL 2 working in tomcat I would suggest this minor change:


Very nice post, bookmarked.

domgom
Guest
domgom

The change is in method 1, using quotation marks in the parameter.
action=”#{user.editAction(‘delete’)}

mightySephiroth
Guest
mightySephiroth

Nice resume!! before reading, I just knew the method expression!! thx

trackback
JSF 2.0 Tutorials

[…] How to pass parameter from JSF page to backing bean […]