The standard way to set JavaBeans component properties in a JSP page is by using the jsp:setProperty element. The syntax of the jsp:setProperty element depends on the source of the property value. Table 5–6 summarizes the various ways to set a property of a JavaBeans component using the jsp:setProperty element.
Syntax rules of attribute values used in this table:
beanName must be the same as that specified for the id attribute in a useBean element.
There must be a setPropName method in the JavaBeans component.
paramName must be a request parameter name.
A property set from a constant string or request parameter must have one of the types listed in Table 5–7. Because constants and request parameters are strings, the web container automatically converts the value to the property’s type; the conversion applied is shown in the table.
String values can be used to assign values to a property that has a PropertyEditor class. When that is the case, the setAsText(String) method is used. A conversion failure arises if the method throws an IllegalArgumentException.
The value assigned to an indexed property must be an array, and the rules just described apply to the elements.
You use an expression to set the value of a property whose type is a compound Java programming language type. The type returned from an expression must match or be castable to the type of the property.
Table 5–7 Valid Property Value Assignments from String Values
Property Type |
Conversion on String Value |
---|---|
Bean Property |
Uses setAsText(string-literal) |
boolean or Boolean |
As indicated in java.lang.Boolean.valueOf(String) |
byte or Byte |
As indicated in java.lang.Byte.valueOf(String) |
char or Character |
As indicated in java.lang.String.charAt(0) |
double or Double |
As indicated in java.lang.Double.valueOf(String) |
int or Integer |
As indicated in java.lang.Integer.valueOf(String) |
float or Float |
As indicated in java.lang.Float.valueOf(String) |
long or Long |
As indicated in java.lang.Long.valueOf(String) |
short or Short |
As indicated in java.lang.Short.valueOf(String) |
Object |
new String(string-literal) |
The Duke’s Bookstore application demonstrates how to use the setProperty element to set the current book from a request parameter in the database bean in tut-install/javaeetutorial5/examples/web/bookstore2/web/books/bookdetails.jsp:
<c:set var="bid" value="${param.bookId}"/> <jsp:setProperty name="bookDB" property="bookId" value="${bid}" />
The following fragment from the page tut-install/javaeetutorial5/examples/web/bookstore2/web/books/bookshowcart.jsp illustrates how to initialize a BookDB bean with a database object. Because the initialization is nested in a useBean element, it is executed only when the bean is created.
<jsp:useBean id="bookDB" class="database.BookDB" scope="page"> <jsp:setProperty name="bookDB" property="database" value="${bookDBAO}" /> </jsp:useBean>