Friday, December 27, 2013

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.


  4. From frameworks chose "Java Server Faces" --> Finish.


  5. You should have project structure like this:


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

  7. With the bean opened in the editor page, copy and paste the following code after package statement:
  8. Open the index.xhtml which is generated by default, and copy the following code and past it in your file:

  9. Right click on the index.xhtml then --> Run; you should see something like this:

  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:

    2. Then your button call to:

    3. Press the button and output text value should be:

  13. 13. Do it one more time:
    1. Bean method:

    2. Then your button call to:

    3. Press the button and output text value should be:

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.

References:
1- JavaEE 7 tutorial (7.5 Navigation Model).

No comments :

Post a Comment