Page III
JavaServer Pages
Chapter 5
Generating Dynamic
Content
Click to Buy:
By Hans Bergsten
Printer Friendly Version
.
Accessing JavaBean Properties
The bean's data is represented by its properties. If you're a page author charged with
developing a JSP page to display the content represented by a bean, you first
need to know the names of all the bean's properties. This information should
be available from the Java programmers on the team or from a third-party
source. In this example, we use a standard Java class named java.util.Date as a bean with properties representing
date and time information. Table
5-1 describes the properties used in this example. (If you're not a
programmer, don't worry about the Java Type and Access columns at this
point.)
Table 5-1: Properties for java.util.Date
|
Property Name |
Java Type |
Access |
Description |
|
date |
int
|
read |
The day of the month as a number between 1 and
31 |
|
hours |
int
|
read |
The hour as a number between 0 (midnight) and
23 |
|
minutes |
int
|
read |
The number of minutes past the hour as a number
between 0 and 59 |
|
month |
int
|
read |
The month as a number from 0 to 11 |
|
year |
int
|
read |
The current year minus 1900 |
Once you have created a bean and given it a name, you can
retrieve the values of the bean's properties in the response page with another
JSP standard action, <jsp:getProperty>. This
action obtains the current value of a bean property and inserts it directly
into the response body.
To include the current date property
value in the page, use the following tag:
<jsp:getProperty name="clock" property="date" />
The name attribute, set to clock, refers to the specific bean instance we defined
with the <jsp:useBean> action previously.
This action locates the bean and asks it for the value of the property
specified by the property attribute. As documented
in Table
5-1, the date property contains the day of the
month as a number between 1 and 31. In Example
5-1, multiple <jsp:getProperty> actions
are used to generate a list of all the clock bean's
property values. The result is the page shown in Figure
5-2.
Input and Output
User input is a necessity in modern web pages. Most dynamic web
sites generate pages based on user input. Unfortunately, users seldom enter
information in exactly the format you need, so before you can use such input,
you probably want to validate it.
And it's not only the input format that's important. Web
browsers are also picky about the format of the HTML you send them. For
instance, when you generate an HTML form with values taken from a database, a
name such as O'Reilly can cause problems. The single quote character after the
O can fool the browser into believing that it's at the end of the string, so
you end up with just an O in your form.