Home > Articles > Programming > Java

Standard JSF Tags

This chapter is from the book

This chapter is from the book

Text Fields and Text Areas

Text inputs are the mainstay of most web applications. JSF supports three varieties represented by the following tags:

  • h:inputText
  • h:inputSecret
  • h:inputTextarea

Since the three tags use similar attributes, Table 4–12 lists attributes for all three.

Table 4–12. Attributes for h:inputText, h:inputSecret, h:inputTextarea, and h:inputHidden

Attributes

Description

cols

For h:inputTextarea only—number of columns.

immediate

Process validation early in the life cycle.

redisplay

For h:inputSecret only—when true, the input field's value is redisplayed when the web page is reloaded.

required

Require input in the component when the form is submitted.

rows

For h:inputTextarea only—number of rows.

valueChangeListener

A specified listener that is notified of value changes.

label jsf-1-2.jpg

A description of the component for use in error messages. Does not apply to h:inputHidden.

binding, converter, converterMessage jsf-1-2.jpg, id, rendered, required, requiredMessage jsf-1-2.jpg, value, validator, validatorMessage jsf-1-2.jpg

Basic attributes.a

accesskey, alt, dir, disabled, lang, maxlength, readonly, size, style, styleClass, tabindex, title

HTML 4.0 pass-through attributesbalt, maxlength, and size do not apply to h:inputTextarea. None apply to h:inputHidden.

autocomplete

If the value is "off", render the nonstandard HTML attribute autocomplete="off" (h:inputText and h:inputSecret only).

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

DHTML events. None apply to h:inputHidden.c

All three tags have immediate, required, value, and valueChangeListener attributes. The immediate attribute is used primarily for value changes that affect the user interface and is rarely used by these three tags. Instead, it is more commonly used by other input components such as menus and listboxes. See "Immediate Components" on page 320 of Chapter 8 for more information about the immediate attribute.

Three attributes in Table 4–12 are each applicable to only one tag: cols, rows, and redisplay. The rows and cols attributes are used with h:inputTextarea to specify the number of rows and columns, respectively, for the text area. The redisplay attribute, used with h:inputSecret, is a boolean that determines whether a secret field retains its value—and therefore redisplays it—when the field's form is resubmitted.

Table 4–13 shows sample uses of the h:inputText and h:inputSecret tags.

Table 4–13. h:inputText and h:inputSecret Examples

Example

Result

<h:inputText value="#{form.testString}"
   readonly="true"/>

04-02_input_text_twenty.jpg

<h:inputSecret value="#{form.passwd}"
   redisplay="true"/>

04-03_input_secret_twenty.jpg

(shown after an unsuccessful form submit)

<h:inputSecret value="#{form.passwd}"
   redisplay="false"/>

04-04_input_text.jpg

(shown after an unsuccessful form submit)

<h:inputText value="inputText"
   style="color: Yellow; background: Teal;"/>

04-05_inputtext-teal-yellow.jpg

<h:inputText value="1234567" size="5"/>

04-06_input_text_five.jpg

<h:inputText value="1234567890" maxlength="6"
   size="10"/>

04-07_input_text_6_10.jpg

The first example in Table 4–13 produces the following HTML:

<input type="text" name="_id0:_id4" value="12345678901234567890"
   readonly="readonly"/>

The input field is read-only, so our form bean defines only a getter method:

private String testString = "12345678901234567890";
public String getTestString() {
   return testString;
}

The h:inputSecret examples illustrate the use of the redisplay attribute. If that attribute is true, the text field stores its value between requests and, therefore, the value is redisplayed when the page reloads. If redisplay is false, the value is discarded and is not redisplayed.

The size attribute specifies the number of visible characters in a text field. But because most fonts are variable width, the size attribute is not precise, as you can see from the fifth example in Table 4–13, which specifies a size of 5 but displays six characters. The maxlength attribute specifies the maximum number of characters a text field will display. That attribute is precise. Both size and maxlength are HTML pass-through attributes.

Table 4–14 shows examples of the h:inputTextarea tag.

Table 4–14. h:inputTextarea Examples

Example

Result

<h:inputTextarea rows="5"/>

textarea-five-cols.jpg

<h:inputTextarea cols="5"/>

textarea-five-rows.jpg

<h:inputTextarea value="123456789012345" rows="3"
                 cols="10"/>

textarea_3_rows_10_cols.jpg

<h:inputTextarea value="#{form.dataInRows}" rows="2"
                 cols="15"/>

textarea_data_in_rows.jpg

The h:inputTextarea has cols and rows attributes to specify the number of columns and rows, respectively, in the text area. The cols attribute is analogous to the size attribute for h:inputText and is also imprecise.

If you specify one long string for h:inputTextarea's value, the string will be placed in its entirety in one line, as you can see from the third example in Table 4–14. If you want to put data on separate lines, you can insert newline characters (\n) to force a line break. For example, the last example in Table 4–14 accesses the dataInRows property of a backing bean. That property is implemented like this:

private String dataInRows = "line one\nline two\nline three";
public void setDataInRows(String newValue) {
   dataInRows = newValue;
}
public String getDataInRows() {
   return dataInRows;
}

Hidden Fields

JSF provides support for hidden fields with h:inputHidden. Hidden fields are often used with JavaScript actions to send data back to the server. The h:inputHidden tag has the same attributes as the other input tags, except that it does not support the standard HTML and DHTML tags.

Using Text Fields and Text Areas

Next, we take a look at a complete example that uses text fields and text areas. The application shown in Figure 4–3 uses h:inputText, h:inputSecret, and h:inputTextarea to collect personal information from a user. The values of those components are wired to bean properties, which are accessed in the thankYou.xhtml page that redisplays the information the user entered.

Figure 4–3

Figure 4–3 Using text fields and text areas

Three things are noteworthy about the following application. First, the JSF pages reference a user bean (com.corejsf.UserBean). Second, the h:inputTextarea tag transfers the text entered in a text area to the model (in this case, the user bean) as one string with embedded newlines (\n). We display that string by using the HTML <pre> element to preserve that formatting. Third, for illustration, we use the style attribute to format output. A more industrial-strength application would presumably use stylesheets exclusively to make global style changes easier to manage.

Figure 4–4 shows the directory structure for the application shown in Figure 4–3. Listings 4–5 through 4–8 show the pertinent JSF pages, managed beans, faces configuration file, and resource bundle.

Figure 4–4

Figure 4–4 Directory structure of the text fields and text areas example

Listing 4–5. personalData/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:outputText value="#{msgs.indexPageTitle}"
11.                     style="font-style: italic; font-size: 1.5em"/>
12.       <h:form>
13.          <h:panelGrid columns="2">
14.             #{msgs.namePrompt}
15.             <h:inputText value="#{user.name}"/>
16.             #{msgs.passwordPrompt}
17.             <h:inputSecret value="#{user.password}"/>
18.             #{msgs.tellUsPrompt}
19.             <h:inputTextarea value="#{user.aboutYourself}" rows="5" cols="35"/>
20.          </h:panelGrid>
21.          <h:commandButton value="#{msgs.submitPrompt}" action="thankYou"/>
22.       </h:form>
23.    </h:body>
24.</html>

Listing 4–6. personalData/web/thankYou.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.thankYouWindowTitle}</title>
 8.    </h:head>
 9.    <h:body>
10.       <h:outputText value="#{msgs.namePrompt}" style="font-style: italic"/>
11.       #{user.name}
12.       <br/>
13.       <h:outputText value="#{msgs.aboutYourselfPrompt}" style="font-style: italic"/>
14.       <br/>
15.       <pre>#{user.aboutYourself}</pre>
16.    </h:body>
17.</html>

Listing 4–7. personalData/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–8. personalData/src/java/com/corejsf/messages.properties

1. indexWindowTitle=Using Textfields and Textareas
2. thankYouWindowTitle=Thank you for submitting your information
3. thankYouPageTitle=Thank you!
4. indexPageTitle=Please enter the following personal information
5. namePrompt=Name:
6. passwordPrompt=Password:
7. tellUsPrompt=Please tell us about yourself:
8. aboutYourselfPrompt=Some information about you:
9. submitPrompt=Submit your information

Displaying Text and Images

JSF applications use the following tags to display text and images:

  • h:outputText
  • h:outputFormat
  • h:graphicImage

The h:outputText tag is one of JSF's simplest tags. With only a handful of attributes, it does not typically generate an HTML element. Instead, it generates mere text—with one exception: If you specify the style or styleClass attributes, h:outputText will generate an HTML span element.

In JSF 2.0, you don't usually need the h:outputText tag since you can simply insert value expressions, such as #{msgs.namePrompt} into your page. You would use h:outputText in the following circumstances:

  • To produce styled output
  • In a panel grid to make sure that the text is considered one cell of the grid
  • To generate HTML markup

The h:outputText and h:outputFormat tags have one attribute that is unique among all JSF tags: escape. By default, the escape attribute is true, which causes the characters < > & to be converted to &lt; &gt; and &amp; respectively. Changing those characters helps prevent cross-site scripting attacks. (See http://www.cert.org/advisories/CA-2000-02.html for more information about cross-site scripting attacks.) Set this attribute to false if you want to programmatically generate HTML markup.

Table 4–15 lists all h:outputText attributes.

Table 4–15. Attributes for h:outputText and h:outputFormat

Attributes

Description

escape

If set to true (default), escapes <, >, and & characters

binding, converter, id, rendered, value

Basic attributesa

style, styleClass, title, dir jsf-1-2.jpg, lang jsf-1-2.jpg

HTML 4.0b

The h:outputFormat tag formats a compound message with parameters specified in the body of the tag—for example:

<h:outputFormat value="{0} is {1} years old">
   <f:param value="Bill"/>
   <f:param value="38"/>
</h:outputFormat>

In the preceding code fragment, the compound message is {0} is {1} years old and the parameters, specified with f:param tags, are Bill and 38. The output of the preceding code fragment is: Bill is 38 years old. The h:outputFormat tag uses a java.text.MessageFormat instance to format its output.

The h:graphicImage tag generates an HTML img element. You can specify the image location with the url or value attribute, as a context-relative path—meaning relative to the web application's context root. As of JSF 2.0, you can place images into the resources directory and specify a library and name:

<h:graphicImage library="images" name="de_flag.gif"/>

Here, the image is located in resources/images/de_flag.gif. Alternatively, you can use this:

<h:graphicImage url="/resources/images/de_flag.gif"/>

You can also use the resources map:

<h:graphicImage value="#{resources['images:de_flag.gif']}"/>

Table 4–16 shows all the attributes for h:graphicImage.

Table 4–16. Attributes for h:graphicImage

Attributes

Description

binding, id, rendered, value

Basic attributesa

alt, dir, height, ismap, lang, longdesc, style, styleClass, title, url, usemap, width

HTML 4.0b

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

DHTML eventsc

library, name jsf-2-0.jpg

The resource library and name for this image

Table 4–17 shows some examples of using h:outputText and h:graphicImage.

Table 4–17. h:outputText and h:graphicImage Examples

Example

Result

<h:outputText value="#{form.testString}"/>

04-10_output_twenty.jpg

<h:outputText value="Number#{form.number}"/>

04-11_output_number.jpg

<h:outputText value="#{form.htmlCode}" escape="false"/> where the getHtmlCode method returns the string "<input type='text' value='hello'/>"

04-12_output_not_escaped.jpg

<h:outputText value="#{form.htmlCode}"/> where the getHtmlCode method returns the string "<input type='text' value='hello'/>"

04-13_output_escaped.jpg

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

04-14_tj.jpg

<h:graphicImage library="images"
   name="tjefferson.jpg"
   style="border: thin solid black"/>

04-15_tj-with-border.jpg

The third and fourth examples in Table 4–17 illustrate use of the escape attribute. If the value for h:outputText is <input type='text' value='hello'/>, and the escape attribute is false—as is the case for the third example in Table 4–17—the h:outputText tag generates an HTML input element. Unintentional generation of HTML elements is exactly the sort of mischief that enables miscreants to carry out cross-site scripting attacks. With the escape attribute set to true—as in the fourth example in Table 4–17—that output is transformed to harmless text, thereby thwarting a potential attack.

The final two examples in Table 4–17 show you how to use h:graphicImage.

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.

Overview


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.

Surveys

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.

Newsletters

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.

Security


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

Children


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

Marketing


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.

Choice/Opt-out


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.

Links


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