Today, Budi walks us through a refresher and brief overview of server JSP programming. Today's portion covers JavaServer Pages (JSP), with a thorough overview of JavaBeans and Tags. This excerpt comes from chapter one of JavaServer Faces Programming, by Budi Kurniawan (McGraw-Hill/Osborne, ISBN 0-07-222983-7, 2004).
To access a property in a bean, use the jsp:getProperty and jsp:setProperty action elements. The jsp:getProperty element obtains the value of an internal variable, and the bean must provide a getter method. A jsp:getProperty element returns the property value converted into String. The return value is then automatically fed into an out.print method, so it will be displayed in the current JSP page. The syntax of the jsp:getProperty element is as follows:
The name attribute must be assigned the name of the bean instance from which the property value will be obtained. The property attribute must be assigned the name of the property.
The jsp:setProperty action element sets the value of a property. Its syntax has four forms:
In this book, you will learn about and use only the first form. The name attribute is assigned the name of the bean instance available in the current JSP page. In the first form of the syntax, the property attribute is assigned the name of the property whose value is to be set, and the value attribute is assigned the value of the property.
The following example demonstrates the use of the jsp:getProperty and jsp:setProperty action elements.
Listing 8 shows a variation of the AdderBean used in the previous example. It has a private integer called memory. (Note that the variable name starts with a lowercase m.) It also has a getter method called getMemory and a setter method named setMemory. (Note that in both access methods, memory is spelled using an uppercase M.)
Listing 8The AdderBean with Access Methods
package ch01
; public class AdderBean { private int memory; public void setMemory(int number) { memory = number; }
public int getMemory() { return memory; } public int add(int x, int y) { return (x + y); } }
Using the jsp:setProperty and jsp:getProperty action elements, you can set and obtain the value of memory, as demonstrated in the JSP page in Listing 9.
Listing 9Accessing a Bean Property Using jsp:setProperty and jsp:getProperty
<jsp:useBean id="theBean" class="ch01.AdderBean"/> <jsp:setProperty name="theBean" property="memory" value="169"/> The value of memory is <jsp:getProperty name="theBean" property="memory"/>
Remember: This is part two of the first chapter of JavaServer Faces Programming, by Budi Kurniawan (McGraw-Hill/Osborne, ISBN 0-07-222983). Stay tuned for more chapters of developer books from McGraw-Hill/Osborne. Buy this book!