Reading Bean Properties

A bean’s data is represented by its properties. The CartoonBean used in Example 6-1 has only one property, named fileName, but other beans may have many different properties. The fileName property’s value is the name of an image file that contains a cartoon. There are two ways to insert a bean property value in a JSP page. Let’s look at them one at a time.

Using the <jsp:getProperty> Action

Once you have created a bean and given it a name using the <jsp:useBean> action, you can get the bean’s property values with another JSP standard action, named <jsp:getProperty>. This action obtains the current value of a bean property and inserts it directly into the response body.

To include the current fileName property value in the page, simply use this tag:

<jsp:getProperty name="cartoon" property="fileName" />

The name attribute, set to cartoon, refers to the specific bean instance declared by the <jsp:useBean> action. The <jsp:getProperty> action locates this bean and asks it for the value of the property specified by the property attribute. In Example 6-1, the property value is used as the src attribute value for an HTML <img> element. The result is the page shown in Figure 6-1. The way this bean is implemented, the fileName property value changes every time you access the property; when you reload the page, a different cartoon strip is shown.

A JSP page with a dynamically inserted image file (Dilbert ©UFS. Reprinted by Permission)

Figure 6-1. A JSP ...

Get JavaServer Pages, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.