JSF Command Component Tags for Action and Navigation With Examples

JSF provides two command component tags for performing action and navigation. They are

  • <h:commandButton> tag
  • <h:commandLink> tag

Let’s look in detail what each of the above tags are capable of.

<h:commandButton> tag

The <h:commandButton> tag renders a button to submit a form, thereby paving a way for processing the data entered by the user. The commandButton specifies action attribute wherein one can specify the navigation details such as the page to be rendered on click of the button.

Consider an example to demonstrate the submit of form on click of the button.

Create a page mobile.xhtml as;

mobile.xhtml

Here we declare the fields company name, model number and color. We use commandButton tag to display the submit button and mention that the navigation be redirected to “mobdetails” page with the help of action attribute.

We will now create the mobdetails.xhtml page which displays the details entered by the user in mobile.xhtml page;

mobdetails.xhtml

Here we invoke the bean name with the dot operator followed by the field name to fetch the value from the bean class.

Create the managed bean Mobile.java as

Here we declare three fields company name, model and color and write the getter and setter methods for setting and retrieving the values.

Now run the mobile.xhtml page and it should produce the following output in the browser.

JSF_Command-Button-Example-1-450x226

JSF_Command-Button-Example-1-450x226

<h:commandLink> tag

The commandLink provides an hyperlink equivalent to anchor tag in HTML that acts like a submit button and can be associated with the backing beans or action class for event handling.
The action attribute can be used for specifying navigation or the actionListener can be used to handle the navigation from the bean class.

Consider an example that demonstrates the usage of commandLink tag to render a hyperlink. Create the page mobilehyperlink.xhtml as;

mobilehyperlink.xhtml

Here we specify two hyperlinks, one to add details of mobile and the other to display the details of the mobile by specifying the view page name in action attribute.

Create viewdetails.xhtml as;

viewdetails.xhtml

We are reusing the above created mobile.xhtml page to add the details of the mobile.

Now run the application and we see the following output.

JSF_Command-Link-Example-1-450x158

Finally below image shows the project structure.

JSF-Command-Button-Link-Project

I have left out web.xml and pom.xml dependencies details, you can check them out by downloading the project from below link.

By admin

Leave a Reply