Home > Articles > Programming > Java

Standard JSF Tags

This chapter is from the book

This chapter is from the book

Buttons and Links

Buttons and links are ubiquitous among web applications, and JSF provides the following tags to support them:

  • h:commandButton
  • h:commandLink
  • h:button
  • h:link
  • h:outputLink

The h:commandButton and h:commandLink are the primary components for navigating within a JSF application. When a button or link is activated, a POST request sends the form data back to the server.

JSF 2.0 introduced the h:button and h:link components. These components also render buttons and links, but clicking on them issues a bookmarkable GET request instead. We discussed this mechanism in Chapter 3.

The h:outputLink tag generates an HTML anchor element that points to a resource such as an image or a web page. Clicking the generated link takes you to the designated resource without further involving the JSF framework. These links are most suitable for navigating to a different web site.

Table 4–18 lists the attributes shared by h:commandButton, h:commandLink, h:button, and h:link.

Table 4–18. Attributes for h:commandButton, h:commandLink, h:button, and h:link



action (h:commandButton and h:commandLink only)

If specified as a string: Directly specifies an outcome used by the navigation handler to determine the JSF page to load next as a result of activating the button or link.

If specified as a method expression: The method has this signature: String methodName(); the string represents the outcome.

If omitted: Activating the button or link redisplays the current page.

outcome (h:button and h:link only)

The outcome, used by the navigation handler to determine the target view when the component is rendered.

fragment (h:button and h:link only)

A fragment that is to be appended to the target URL. The # separator is applied automatically and should not be included in the fragment.


A method expression that refers to a method with this signature: void methodName(ActionEvent).

image (h:commandButton and h:button only)

The path to an image displayed in a button. If you specify this attribute, the HTML input's type will be image. If the path starts with a /, the application's context root is prepended.


A Boolean. If false (the default), actions and action listeners are invoked at the end of the request life cycle; if true, actions and action listeners are invoked at the beginning of the life cycle. See Chapter 8 for more information about the immediate attribute.


For h:commandButton—The type of the generated input element: button, submit, or reset. The default, unless you specify the image attribute, is submit.

For h:commandLink and h:link—The content type of the linked resource; for example, text/ html, image/gif, or audio/basic.


The label displayed by the button or link. You can specify a string or a value expression.

binding, id, rendered

Basic attributes.a

accesskey, charset (h:commandLink and h:link only), coords (h:commandLink and h:link only), dir jsf_1-1.jpg, disabled (h:commandButton only in JSF 1.1), hreflang (h:commandLink and h:link only), lang, rel (h:commandLink and h:link only), rev (h:commandLink and h:link only), shape (h:commandLink and h:link only), style, styleClass, tabindex, target (h:commandLink and h:link only), title

HTML 4.0.b

onblur, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup

DHTML events.c

Using Buttons

The h:commandButton and h:button tags generate an HTML input element whose type is button, image, submit, or reset, depending on the attributes you specify. Table 4–19 illustrates some uses of these tags.

Table 4–19. h:commandButton and h:button Examples



<h:commandButton value="submit" type="submit"


<h:commandButton value="reset" type="reset"/>


<h:commandButton value="click this button..."
   onclick="alert('button clicked')"


<h:commandButton value="disabled"
   disabled="#{not form.buttonEnabled}"/>


<h:button value="#{form.buttonText}"


The third example in Table 4–19 generates a push button—an HTML input element whose type is button—that does not result in a form submit. The only way to attach behavior to a push button is to specify a script for one of the DHTML event attributes, as we did for onclick in the example.

The h:commandLink and h:link tags generates an HTML anchor element that acts like a form submit button. Table 4–20 shows some examples.

Table 4–20. h:commandLink and h:link Examples





<h:commandLink style="font-style: italic">


   <h:graphicImage value="/registration.jpg"/>


<h:commandLink value="welcome"


<h:link value="welcome"
   <f:param name="id" value="#{form.userId}"/>


The h:commandLink and h:link tags generate JavaScript to make links act like buttons. For example, here is the HTML generated by the first example in Table 4–20:

<a href="#" onclick="document.forms['_id0']['_id0:_id2'].value='_id0:_id2';

When the user clicks the link, the anchor element's value is set to the h:commandLink's client ID, and the enclosing form is submitted. That submission sets the JSF life cycle in motion and, because the href attribute is "#", the current page will be reloaded unless an action associated with the link returns a non-null outcome.

You can place as many children as you want in the body of an h:commandLink tag—each corresponding HTML element is part of the link. So, for example, if you click on either the text or image in the third example in Table 4–20, the link's form will be submitted.

The next-to-last example in Table 4–20 attaches an action listener, in addition to an action, to a link. Action listeners are discussed in "Action Events" on page 312 of Chapter 8.

The last example in Table 4–20 embeds an f:param tag in the body of the h:link tag. When you click the link, a request parameter with the name and value specified with the f:param tag is created by the link. In Chapter 2, we discussed how the request parameters can be processed. You can also use request parameters with an h:commandLink or h:commandButton. See "Passing Data from the UI to the Server" on page 324 of Chapter 8 for an example.

Like h:commandLink and h:link, h:outputLink generates an HTML anchor element. But unlike h:commandLink, h:outputLink does not generate JavaScript to make the link act like a submit button. The value of the h:outputLink value attribute is used for the anchor's href attribute, and the contents of the h:outputLink body are used to populate the body of the anchor element. Table 4–21 lists all attributes for h:outputLink., and Table 4–22 shows some h:outputLink examples.

Table 4–21. Attributes for h:outputLink



binding, converter, id, lang, rendered, value

Basic attributesa

accesskey, charset, coords, dir, disabled jsf-1-2.jpg, hreflang, lang, rel, rev, shape, style, styleClass, tabindex, target, title, type

HTML 4.0b

onblur, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup

DHTML eventsc

Table 4–22. h:outputLink Examples



<h:outputLink value="http://java.net">
   <h:graphicImage value="java-dot-net.jpg"/>
   <h:outputText value="java.net"/>


<h:outputLink value="#{form.welcomeURL}">


<h:outputLink value="#introduction">
   <h:outputText value="Introduction"
      style="font-style: italic"/>


<h:outputLink value="#conclusion"
      title="Go to the conclusion">


<h:outputLink value="#toc"
      title="Go to the table of contents">
   <h2>Table of Contents</h2>


The first example in Table 4–22 is a link to http://java.net. The second example uses properties stored in a bean for the link's URL and text. Those properties are implemented like this:

private String welcomeURL = "/outputLinks/faces/welcome.jsp";
public String getWelcomeURL() {
   return welcomeURL;
private String welcomeLinkText = "go to welcome page";
public String getWelcomeLinkText() {
   return welcomeLinkText;

The last three examples in Table 4–22 are links to named anchors in the same JSF page. Those anchors look like this:

<a name="introduction">Introduction</a>
<a name="conclusion">Conclusion</a>
<a name="toc">Table of Contents</a>

Using Command Links

Now that we have discussed the details of JSF tags for buttons and links, we take a look at a complete example. Figure 4–5 shows the application discussed in "Using Text Fields and Text Areas" on page 127, with two links that let you select either English or German locales. When a link is activated, an action changes the view's locale and the JSF implementation reloads the current page.

Figure 4–5

Figure 4–5 Using command links to change locales

The links are implemented like this:

<h:commandLink action="#{localeChanger.englishAction}">
    <h:graphicImage library="images" name="en_flag.gif" style="border: 0px" />

Both links specify an image and an action method. The method to change to the English locale looks like this:

public class LocaleChanger {
   public String englishAction() {
      FacesContext context = FacesContext.getCurrentInstance();
      return null;

Because we have not specified any navigation for this action, the JSF implementation will reload the current page after the form is submitted. When the page is reloaded, it is localized for English or German, and the page redisplays accordingly.

Figure 4–6 shows the directory structure for the application, and Listings 4–9 through 4–11 show the associated JSF pages and Java classes.

Figure 4–6

Figure 4–6 Directory structure of the flags example

Listing 4–9. flags/web/index.xhtml

 1.<?xml version="1.0" encoding="UTF-8"?>
 2.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4.<html xmlns="http://www.w3.org/1999/xhtml"
 5.      xmlns:h="http://java.sun.com/jsf/html">
 6.    <h:head>
 7.       <title>#{msgs.indexWindowTitle}</title>
 8.    </h:head>
 9.    <h:body>
10.       <h:form>
11.          <h:commandLink action="#{localeChanger.germanAction}">
12.             <h:graphicImage library="images" name="de_flag.gif"
13.                             style="border: 0px; margin-right: 1em"/>
14.          </h:commandLink>
15.          <h:commandLink action="#{localeChanger.englishAction}">
16.             <h:graphicImage library="images"
17.                             name="en_flag.gif" style="border: 0px"/>
18.          </h:commandLink>
19.          <p><h:outputText value="#{msgs.indexPageTitle}"
20.          style="font-style: italic; font-size: 1.3em"/></p>
21.          <h:panelGrid columns="2">
22.             #{msgs.namePrompt}
23.             <h:inputText value="#{user.name}"/>
24.             #{msgs.passwordPrompt}
25.             <h:inputSecret value="#{user.password}"/>
26.             #{msgs.tellUsPrompt}
27.             <h:inputTextarea value="#{user.aboutYourself}" rows="5" cols="35"/>
28.          </h:panelGrid>
29.          <h:commandButton value="#{msgs.submitPrompt}" action="thankYou"/>
30.       </h:form>
31.    </h:body>
32. </html>

Listing 4–10. flags/src/java/com/corejsf/UserBean.java

 1.package com.corejsf;
 3. import java.io.Serializable;
 5. import javax.inject.Named;
 6.    // or import javax.faces.bean.ManagedBean;
 7. import javax.enterprise.context.SessionScoped;
 8.    // or import javax.faces.bean.SessionScoped;
10. @Named("user") // or @ManagedBean(name="user")
11. @SessionScoped
12. public class UserBean implements Serializable {
13.    private String name;
14.    private String password;
15.    private String aboutYourself;
17.    public String getName() { return name; }
18.    public void setName(String newValue) { name = newValue; }
20.    public String getPassword() { return password; }
21.    public void setPassword(String newValue) { password = newValue; }
23.    public String getAboutYourself() { return aboutYourself; }
24.    public void setAboutYourself(String newValue) { aboutYourself = newValue; }
25. }

Listing 4–11. flags/src/java/com/corejsf/LocaleChanger.java

 1.package com.corejsf;
 3. import java.io.Serializable;
 4. import java.util.Locale;
 6. import javax.inject.Named;
 7.    // or import javax.faces.bean.ManagedBean;
 8.  import javax.enterprise.context.SessionScoped;
 9.    // or import javax.faces.bean.SessionScoped;
10. import javax.faces.context.FacesContext;
12. @Named // or @ManagedBean
13. @SessionScoped
14. public class LocaleChanger implements Serializable {
15.    public String germanAction() {
16.       FacesContext context = FacesContext.getCurrentInstance();
17.       context.getViewRoot().setLocale(Locale.GERMAN);
18.       return null;
19.    }
21.    public String englishAction() {
22.       FacesContext context = FacesContext.getCurrentInstance();
23.       context.getViewRoot().setLocale(Locale.ENGLISH);
24.       return null;
25.    }

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020