JSF: Passing parameters to JSF action methods from page directly, a nice feature of JavaEE 6+

One of the JSF 2+ nice features presented in Java enterprise edition JavaEE 6+, is that you can pass parameters to any action components action method like commandButton or commandLink components.


Based on that you can minimize the number of methods inside your managed bean.

In addition, to minimize many parameters to set inside the bean to be used by action to decide navigation logic, which reduce memory consumption if your beans in scopes greater than request scope.

How it works:

  1. Open your favorite IDE, I am going to use Netbeans 7.4.1. (Use any IDE that supports JavaEE 6 or 7).
  2. Create web project.
    File –> New Project –> Java Web (left pan) –> Web Application (right pan) –> Next.
  3. Name it whatever you like (JSFeatures for me)–> Next –> Server Glassfish4 –> Java EE 7 Web profile –> Context path “/JSFeatures” –> Next.

    JSF-FEAT-01

  4. From frameworks chose “Java Server Faces–> Finish.

    JSF-FEAT-02

  5. You should have project structure like this:

    JSF-FEAT-03

  6. Right click on the JSFeatures project –> new “JSF Managed Bean“. and its name and config like this:

    JSF-FEAT-04

  7. With the bean opened in the editor page, copy and paste the following code after package statement:
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.RequestScoped;
     
    /**
     * @author mohamed_taman
     */
    @ManagedBean(name = "jSFeatBean")
    @RequestScoped
    public class JSFeatursBean {
     
        private String result;
     
        public String getResult() {
            return result;
        }
     
        public void setResult(String result) {
            this.result = result;
        }
     
        public JSFeatursBean() {
        }
     
        public Object addNumbers(int num1,int num2) {
                setResult("Hi there I am an action method to add numbers.");
            return null;
        }
    }
  8. Open the index.xhtml which is generated by default, and copy the following code and past it in your file:
    <?xml version='1.0' encoding='UTF-8' ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:h="http://xmlns.jcp.org/jsf/html">
        <h:head>
            <title>Facelet Title</title>
        </h:head>
        <h:body>
            Hello from Facelets
            <h:form>
                <p>
                    <h:outputText value="#{jSFeatBean.result}"/>
                </p>
    <h:commandButton type="submit"
                     value="Submit"
                     action="#{jSFeatBean.addNumbers}"/>
            </h:form>
        </h:body>
    </html>
  9. Right click on the index.xhtml then –> Run; you should see something like this:

    JSF-FEAT-05

  10. Click submit button and watch h:outputText value, its value should be “Hi there I am an action method.
  11. Now everything is working fine. Let us do the actual work I need to demonstrate.
  12. Change addNumbers() method signature to the following (without restarting the application server):
    1. Bean method:
      public Object addNumbers(int num1) {
            int res = 0;
            res = num1;
            if (res == 0) {
                setResult("Hi there I am an action method to add numbers.");
            } else {
                setResult("Final result is: " + res);
            }
            return null;
        }
    2. Then your button call to:
      <h:commandButton type="submit"
                       value="Submit" 
                       action="#{jSFeatBean.addNumbers(1)}"/>
    3. Press the button and output text value should be:
      Final result is: 1
  13. Do it one more time:
    1. Bean method:
      public Object addNumbers(int num1, int num2) {
            int res = 0;
            res = num1 + num2;
            if (res == 0) {
                setResult("Hi there I am an action method to add numbers.");
            } else {
                setResult("Final result is: " + res);
            }
            return null;
        }
    2. Then your button call to:
      <h:commandButton type="submit"
                       value="Submit" 
                       action="#{jSFeatBean.addNumbers(1,2)}"/>
    3. Press the button and output text value should be:
      Final result is: 3

Note: the parameter could be with different parameters type not expected to be the same type, also method could return a value for navigation to other pages, in this example it returns null to be on the same page.

I liked this feature too much enjoy it, very helpful and handy, and happy coding.

Resources:

 

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


1 × eight =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close