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 |
A description of the component for use in error messages. Does not apply to h:inputHidden. |
binding, converter, converterMessage , id, rendered, required, requiredMessage , value, validator, validatorMessage |
Basic attributes.a |
accesskey, alt, dir, disabled, lang, maxlength, readonly, size, style, styleClass, tabindex, title |
HTML 4.0 pass-through attributesb—alt, 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"/> |
|
<h:inputSecret value="#{form.passwd}" redisplay="true"/> |
(shown after an unsuccessful form submit) |
<h:inputSecret value="#{form.passwd}" redisplay="false"/> |
(shown after an unsuccessful form submit) |
<h:inputText value="inputText" style="color: Yellow; background: Teal;"/> |
|
<h:inputText value="1234567" size="5"/> |
|
<h:inputText value="1234567890" maxlength="6" size="10"/> |
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"/> |
|
<h:inputTextarea cols="5"/> |
|
<h:inputTextarea value="123456789012345" rows="3" cols="10"/> |
|
<h:inputTextarea value="#{form.dataInRows}" rows="2" cols="15"/> |
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 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 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 < > and & 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 , lang |
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 |
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}"/> |
|
<h:outputText value="Number#{form.number}"/> |
|
<h:outputText value="#{form.htmlCode}" escape="false"/> where the getHtmlCode method returns the string "<input type='text' value='hello'/>" |
|
<h:outputText value="#{form.htmlCode}"/> where the getHtmlCode method returns the string "<input type='text' value='hello'/>" |
|
<h:graphicImage value="/tjefferson.jpg"/> |
|
<h:graphicImage library="images" name="tjefferson.jpg" style="border: thin solid black"/> |
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.