Home > Articles > Programming > Java

  • Print
  • + Share This
  • 💬 Discuss
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

Attribute

Description

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.

actionListener

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.

immediate

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.

type

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.

value

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

Example

Result

<h:commandButton value="submit" type="submit"
   action="#{form.submitAction}"/>

04-16_submit-button.jpg

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

04-17_reset-button.jpg

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

04-18_js-button.jpg

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

04-19_disabled-button.jpg

<h:button value="#{form.buttonText}"
   outcome="#{form.pressMeOutcome"/>

04-20_button-with-model.jpg

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

Example

Result

<h:commandLink>register</h:commandLink>

04-21_command-link-simple.jpg

<h:commandLink style="font-style: italic">
   #{msgs.linkText}>
</h:commandLink>

04-22_command-link-styled.jpg

<h:commandLink>
   #{msgs.linkText}
   <h:graphicImage value="/registration.jpg"/>
</h:commandLink>

04-23_registration-lincoln.jpg

<h:commandLink value="welcome"
   actionListener="#{form.useLinkValue}"
   action="#{form.followLink}"/>

04-24_command-link-welcome.jpg

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

04-24_command-link-welcome.jpg

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';
   document.forms['_id0'].submit()">register</a>

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

Attributes

Description

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

Example

Result

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

04-25_java-dot-net.jpg

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

04-26_output-welcome-pg.jpg

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

04-27_outputlink-intro.jpg

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

04-28_outputlink-conclusion.jpg

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

04-29_toc.jpg

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" />
</h:commandLink>

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();
      context.getViewRoot().setLocale(Locale.ENGLISH);
      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"
 3."http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 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;
 2.
 3. import java.io.Serializable;
 4.
 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;
 9.
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;
16.
17.    public String getName() { return name; }
18.    public void setName(String newValue) { name = newValue; }
19.
20.    public String getPassword() { return password; }
21.    public void setPassword(String newValue) { password = newValue; }
22.
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;
 2.
 3. import java.io.Serializable;
 4. import java.util.Locale;
 5.
 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;
11.
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.    }
20.
21.    public String englishAction() {
22.       FacesContext context = FacesContext.getCurrentInstance();
23.       context.getViewRoot().setLocale(Locale.ENGLISH);
24.       return null;
25.    }
26.}
  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus