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 🙂

50 comments on “4 ways to pass parameter from JSF page to backing bean

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

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

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

    Reply
  4. 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.

    Reply
  5. 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.

    Reply
  6. 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

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

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

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

    Reply
  9. 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 ?

    Reply
  10. 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

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

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

    Reply
  12. 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.

    Reply
    1. AJ.. AJ.. AJEY.. Hey Yavrum Hey..

      44 > 23

      SAYGI

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

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

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

    Reply
  14. 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.

    Reply
  15. 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

    Reply
  16. Hello,

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

    thanks

    Caio.

    Reply
  17. 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

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

      Reply
  18. Please tell me about Difference between managed bean and backing bean?

    Reply
  19. 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!

    Reply
  20. 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.

    Reply
  21. A simple bug

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

    Reply
  22. 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?

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

    Reply
  24. 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

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

    
    

    Very nice post, bookmarked.

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

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

    Reply
  27. There are actually at least two other ways for specific situations, though both not extremely pretty.

    Often the parameter you want to pass to a backing bean is an item from some iteration, e.g. a row from a data table. When your action method is executed, this row is directly available in the request scope under the name assigned to it on the page.

    E.g. consider this code:

    In your action method, you can now fetch “row” from the request scope and it will be the correct row on which the user clicked.

    In this example, yet another way to get to the same thing is to make sure “model” is some JSF DataModel. In your action method, the current row of this model instance will then also point to the correct row.

    All in all, I personally think method expressions with parameters are the clearest and most elegant solution.

    Reply
    1. Hi,

      Can you please write the code. I also tried to pass a value from an iteration to the action method but i couldn’t get the value in the action method. If i use a constant value as parameter, i can get it but if the parameter is from an iteration (dynamic value) then i can’t get it. (jsf 1.2 with icefaces 1.8.2).

      Reply

Leave a Comment

Your email address will not be published. Required fields are marked *