Selection Tags

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:outputLink

The h:commandButton and h:commandLink actions both represent JSF command components the JSF framework fires action events and invokes actions when a button or link is activated. See "Action Events" on page 275 of Chapter 7 for more information about event handling for command components.

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.

Table 4-14 lists the attributes shared by h:commandButton and h:commandLink.

Table 4-14. Attributes for h:commandButton and h:commandLink
Attribute Description
action 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.

actionListener A method expression that refers to a method with this signature: void methodName(ActionEvent).
charset For h:commandLink only The character encoding of the linked reference.
image For h:commandButton only The path to an image displayed in a button. If you specify this attribute, the HTML input's type will be image.
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 6 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 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, styleClass Basic attributes.[a]
accesskey, alt (h:commandLink only), coords (h:commandLink only), dir (in JSF 1.1), disabled (h:commandButton only in JSF 1.1), hreflang (h:commandLink only), lang, readonly (h:commandLink only), rel (h:commandLink only), rev (h:commandLink only), shape (h:commandLink only), style, tabindex, target (h:commandLink only), title HTML 4.0.[b]
onblur, onchange (h:commandLink only), onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselect (h:commandLink only) DHTML events.[c]


[a] See Table 4-4 on page 97 for information about basic attributes.

[b] See Table 4-5 on page 101 for information about HTML 4.0 attributes.

[c] See Table 4-6 on page 102 for information about DHTML event attributes.

Using Command Buttons

The h:commandButton tag generates an HTML input element whose type is button, image, submit, or reset, depending on the attributes you specify. Table 4-15 illustrates some uses of h:commandButton.

Table 4-15. h:commandButton Examples
Example Result

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

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

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

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

<h:commandButton value="#{form.buttonText}"    type="reset"/>


The third example in Table 4-15 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.

Caution

h:graphicImage and h:commandButton can both display images, but in JSF 1.1, the way in which you specify the image was not consistent between the two tags. h:commandButton required a context path, whereas the context path was added automatically by h:graphicImage. For example, for an application named myApp, here is how you specified the same image for each tag:

<h:commandButton image="/myApp/imageFile.jpg"/> <!-- JSF 1.1 --> <h:graphicImage value="/imageFile.jpg"/>

In JSF 1.2, you do not add the context path for either attribute. If the path is absolute (starting with a /), the context path is automatically added. If the path is relative to the enclosing page (i.e., not starting with a /), it is used without change.


The h:commandLink tag generates an HTML anchor element that acts like a form submit button. Table 4-16 shows some h:commandLink examples.

Table 4-16. h:commandLink Examples
Example Result

<h:commandLink>    <h:outputText value="register"/> </h:commandLink>

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

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

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

<h:commandLink>    <h:outputText value="welcome"/>    <f:param name="outcome" value="welcome"/> </h:commandLink>


h:commandLink generates JavaScript to make links act like buttons. For example, here is the HTML generated by the first example in Table 4-16:

  <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. See Chapter 3 for more information about JSF navigation.

You can place as many JSF HTML tags 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-16, the link's form will be submitted.

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

The last example in Table 4-16 embeds an f:param tag in the body of the h:commandLink 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. You can use that request parameter any way you like. See "Passing Data from the UI to the Server" on page 291 of Chapter 7 for an example.

Both h:commandButton and h:commandLink submit requests and subsequently invoke the JSF life cycle. Although those tags are useful, sometimes you just need a link that loads a resource without invoking the JSF life cycle. In that case, you can use the h:outputLink tag. Table 4-17 lists all attributes for h:outputLink.

Table 4-17. Attributes for h:outputLink
Attributes Description
binding, converter, id, lang, rendered, styleClass, value Basic attributes[a]
accesskey, charset, coords, dir, disabled (JSF 1.2), hreflang, lang, rel, rev, shape, style, tabindex, target, title, type HTML 4.0[b]
onblur, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup DHTML events[c]


[a] See Table 4-4 on page 97 for information about basic attributes.

[b] See Table 4-5 on page 101 for information about HTML 4.0 attributes.

[c] See Table 4-6 on page 102 for information about DHTML event attributes.

Like h:commandLink, 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-18 shows some h:outputLink examples.

Table 4-18. 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>

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

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

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

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


The first example in Table 4-18 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-18 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>    ...

Caution

If you use JSF 1.1, you need to use the f:verbatim tag for the last example in Table 4-18:

<h:outputLink...><f:verbatim>Table of Contents</f:verbatim></h:outputLink>

You cannot simply place text inside the h:outputLink tag the text would appear outside the link. In JSF 1.1, children of a component had to be another component, such as h:outputText or f:verbatim. This problem has been fixed in JSF 1.2.


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 112, 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. Using command links to change locales

4


The two links are implemented like this:

   <h:form>      ...      <h:commandLink action="#{localeChanger.germanAction}">         <h:graphicImage value="/german_flag.gif"            style="border: 0px"/>      </h:commandLink>      <h:commandLink action="#{localeChanger.englishAction}">         <h:graphicImage value="/britain_flag.gif"            style="border: 0px"/>      </h:commandLink>      ...    </h:form>

Both links specify an image, a request parameter, and an action method. Those methods look like this:

   public class ChangeLocaleBean {       public String germanAction() {          FacesContext context = FacesContext.getCurrentInstance();          context.getViewRoot().setLocale(Locale.GERMAN);          return null;       }       public String englishAction() {          FacesContext context = FacesContext.getCurrentInstance();          context.getViewRoot().setLocale(Locale.ENGLISH);          return null;       }    }

Both actions set the locale of the view. And because we have not specified any navigation for this application, 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 Listing 4-8 through Listing 4-11 show the associated JSF pages Java classes. Listing 4-11 shows the faces configuration file.

Figure 4-6. Directory structure of the flags example


Listing 4-8. flags/web/index.jsp

  1. <html>   2.    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>   3.    <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>   4.    <f:view>   5.       <head>   6.          <link href="styles.css" rel="stylesheet" type="text/css"/>   7.          <title>   8.             <h:outputText value="#{msgs.indexWindowTitle}"/>   9.          </title>  10.       </head>  11.       <body>  12.          <h:form>  13.             <table>  14.                <tr>  15.                   <td>  16.                      <h:commandLink immediate="true"  17.                         action="#{localeChanger.germanAction}">  18.                         <h:graphicImage value="/german_flag.gif"  19.                            style="border: 0px"/>  20.                      </h:commandLink>  21.                   </td>  22.                   <td>  23.                      <h:commandLink immediate="true"  24.                         action="#{localeChanger.englishAction}">  25.                         <h:graphicImage value="/britain_flag.gif"  26.                            style="border: 0px"/>  27.                      </h:commandLink>  28.                   </td>  29.                </tr>  30.             </table>  31.             <p>  32.                <h:outputText value="#{msgs.indexPageTitle}"  33.                   style="font-style: italic; font-size: 1.3em"/>  34.             </p>  35.             <table>  36.                <tr>  37.                   <td>  38.                      <h:outputText value="#{msgs.namePrompt}"/>  39.                   </td>  40.                   <td>  41.                      <h:inputText value="#{user.name}"/>  42.                   </td>  43.                </tr>  44.                <tr>  45.                   <td>  46.                      <h:outputText value="#{msgs.passwordPrompt}"/>  47.                   </td>  48.                   <td>  49.                      <h:inputSecret value="#{user.password}"/>  50.                   </td>  51.                </tr>  52.                <tr>  53.                   <td style="vertical-align: top">  54.                      <h:outputText value="#{msgs.tellUsPrompt}"/>  55.                   </td>  56.                   <td>  57.                      <h:inputTextarea value="#{user.aboutYourself}" rows="5"  58.                         cols="35"/>  59.                   </td>  60.                </tr>  61.                <tr>  62.                   <td>  63.                      <h:commandButton value="#{msgs.submitPrompt}"  64.                         action="thankYou"/>  65.                   </td>  66.                </tr>  67.             </table>  68.          </h:form>  69.       </body>  70.    </f:view>  71. </html>     

Listing 4-9. flags/src/java/com/corejsf/UserBean.java

  1. package com.corejsf;   2.   3. public class UserBean {   4.    private String name;   5.    private String password;   6.    private String aboutYourself;   7.   8.    // PROPERTY: name   9.    public String getName() { return name; }  10.    public void setName(String newValue) { name = newValue; }  11.  12.    // PROPERTY: password  13.    public String getPassword() { return password; }  14.    public void setPassword(String newValue) { password = newValue; }  15.  16.    // PROPERTY: aboutYourself  17.    public String getAboutYourself() { return aboutYourself; }  18.    public void setAboutYourself(String newValue) { aboutYourself = newValue; }  19. }     

Listing 4-10. flags/src/java/com/corejsf/ChangeLocaleBean.java

  1. package com.corejsf;   2.   3. import java.util.Locale;   4. import javax.faces.context.FacesContext;   5.   6. public class ChangeLocaleBean {   7.    public String germanAction() {   8.       FacesContext context = FacesContext.getCurrentInstance();   9.       context.getViewRoot().setLocale(Locale.GERMAN);  10.       return null;  11.    }  12.  13.    public String englishAction() {  14.       FacesContext context = FacesContext.getCurrentInstance();  15.       context.getViewRoot().setLocale(Locale.ENGLISH);  16.       return null;  17.    }  18. }

Listing 4-11. flags/web/WEB-INF/faces-config.xml

  1. <?xml version="1.0"?>   2. <faces-config xmlns="http://java.sun.com/xml/ns/javaee"   3.    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   4.    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   5.         http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"   6.    version="1.2">   7.    <navigation-rule>   8.       <from-view-id>/index.jsp</from-view-id>   9.       <navigation-case>  10.          <from-outcome>thankYou</from-outcome>  11.          <to-view-id>/thankYou.jsp</to-view-id>  12.       </navigation-case>  13.    </navigation-rule>  14.  15.    <managed-bean>  16.       <managed-bean-name>localeChanger</managed-bean-name>  17.       <managed-bean-class>com.corejsf.ChangeLocaleBean</managed-bean-class>  18.       <managed-bean-scope>session</managed-bean-scope>  19.    </managed-bean>  20.  21.    <managed-bean>  22.       <managed-bean-name>user</managed-bean-name>  23.       <managed-bean-class>com.corejsf.UserBean</managed-bean-class>  24.       <managed-bean-scope>session</managed-bean-scope>  25.    </managed-bean>  26.  27.    <application>  28.       <resource-bundle>  29.          <base-name>com.corejsf.messages</base-name>  30.          <var>msgs</var>  31.       </resource-bundle>  32.    </application>  33. </faces-config>     



Core JavaServerT Faces
Core JavaServer(TM) Faces (2nd Edition)
ISBN: 0131738860
EAN: 2147483647
Year: 2004
Pages: 84

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net