Main Tutorials

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 Author

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

Comments

Subscribe
Notify of
50 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Bharat
10 years ago

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

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

max
9 years ago
Reply to  Bharat

true, hope that mkyong update the post.

Player
5 years ago

This is not very interesting considering you are passing hardcoded values. The whole thing only gets complex when you want to pass for example the value of an input.
I cant get it to work, it’s incredible. All I want is a get request to a target view with the content of an input field. I am sitting here since TWO hours and I have NOT found a solution, this is seriously fucked up.

Naresh
3 years ago

Hello team,

I have following logic in xhtml, when loading page editbean.init() method will execute couple of minutes at that time dialog box should display with specified h:graphicImage, but not working.

Could you please help.

<html>
<h:body>
<h:form id=”form”>
<p:remoteCommand name=”rc” action=”#{editbean.init()}”
onstart=”PF(‘statusDialog’).show()”
oncomplete=”PF(‘statusDialog’).hide()” autoRun=”true”
process=”@this” partialSubmit=”true” />
</h:form>
<p:dialog widgetVar=”statusDialog” draggable=”false”
closable=”false” resizable=”false” showHeader=”false” modal=”true”>
<h:graphicImage name=”/images/loading.gif” />
</p:dialog>
</h:body>
</html>

Thanks in advance.

Julia
3 years ago

If anyone can help …
I have to take the tuple data from a table and insert it into the form. please

Julia
3 years ago

If anyone can help …
I have to take the tuple data from a table and insert it into the form.

Enissay
8 years ago

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
9 years ago

Thanks for helpful tutorial

Hai Ba Tu?i
9 years ago

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 java.lang.Thread.run(Unknown Source)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
… 26 more
Caused by: java.lang.NullPointerException
at controller.cartShopBean.addToCart(cartShopBean.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
… 27 more

thg 12 26, 2014 12:56:51 SA com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
SEVERE: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
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 java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at controller.cartShopBean.addToCart(cartShopBean.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
… 27 more

Vimal
3 years ago
Reply to  Hai Ba Tu?i

Hi, can you please tell me why are we getting this kind of error ?

Cong Pham
9 years ago

Comment demo

saum
9 years ago

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

ArunRaj
10 years ago

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
6 years ago
Reply to  ArunRaj

why copy paste? why? why?

ram
10 years ago

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 repo
http://download.java.net/maven/2

JavaServerFaces

org.apache.maven.plugins
maven-compiler-plugin
2.3.1

1.6
1.6

jado pado
6 years ago
Reply to  ram

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

Kadir
10 years ago

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
10 years ago
Reply to  Kadir

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

44 > 23

SAYGI

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

LOun
10 years ago
Reply to  Vursana Lan

VUR MUSTO VUR DUVARA.

Ankaral? Hakk?
9 years ago
Reply to  LOun

LAN KADIR CEVAP VERSENE OGLEM

Hakan Hakki
9 years ago
Reply to  Ankaral? Hakk?

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

mlblount45
10 years ago

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

tegoo
10 years ago

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
10 years ago
Reply to  tegoo

*think

Carlos Arturo
10 years ago

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
10 years ago

Hello,

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

thanks

Caio.

Shubham
10 years ago
Holger
10 years ago

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
8 years ago
Reply to  Holger

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

vijayan
11 years ago

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

tunnaruto
11 years ago
Reply to  vijayan

There is not, they are the same thing

Maoduy
11 years ago

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
11 years ago

thank you very much.

LG
11 years ago

Very nice post, Helpfull .
Keep writing .

hannibaldaturn
11 years ago

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
11 years ago
Reply to  hannibaldaturn

I have the same question as you.

Gonzalo
11 years ago

A simple bug

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

Markus
11 years ago

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

Jim
11 years ago

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
12 years ago

Thank you for this article! Really helped me 🙂

curious
12 years ago

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

Kawu
12 years ago

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
12 years ago
Reply to  Kawu

Please delete the above, it’s not working.