JavaBean Notes

I got my information researching various internet sites and the book Core Servlet and JavaServer Pages.



3 Points to Remember When Using JavaBeans
  1. A bean class must have an empty constructor.
  2. A bean class should have no public fields.
  3. Use consistent naming convention for access data (setXxx/getXxx or isXxx/setXxx for accessing xxx).

Loading a JavaBean to be Used in a JSP page

Warning!!
Since jsp:useBean uses XML syntax, its format (along with any jsp:xxx elements) differs from HTML syntax in 3 ways:
Simple syntax:
< jsp:useBean id="variableName" class="package.Class" / > 
means instantiate an object of type Class and bind it to the variable variableName 
ex:
< jsp:useBean id="emp" class="EmployeeDatabase.Worker" / > 
is equivalent to the scriplet
< % EmployeeDatabase.Worker emp =  new EmployeeDatabase.Worker(); % >
By the way, the jsp:useBean action instantiates a new object only if there
isn't one existing with the same id and scope (an additionaly attribute).
Otherwise, it shares the existing bean.

Accessing a JavaBean's Properties

To print out the property, there are 2 ways. The 2nd is useful when using
the property in code other than displaying. name should match the id used in the jsp:useBean tag.
    < jsp:getProperty name = "beanName" property = "propertyName" / >
    or
    < % = beanName.getPropertyName() % >  
     FYI: A bean property is a private data field of the class that has 
methods to get and set the value of the field.

Setting a JavaBean's Properties

The simplest ways to set a bean's property are as follows:
    < jsp:setProperty name="beanName" property = "propertyName"  value = "theValue" / >
    or
    < % beanName.setPropertyName(theValue); % > 
    Put theValue in double quotes if string type is expected
To associate a property with an input parameter, use param instead of value:
< jsp:setProperty name="beanName" property = "propertyName" param = "paramName" >
This action is nice because it automatically converts the param type to property's type.
If all properties of a bean have input parameters with the EXACT same name, 
you can assign all the properties to equal their corresponding parameters this way: < jsp:setProperty name="beanName" property="*" />

Sharing Beans

Scope
 Beans, all bound to local variables, are stored in 1 out of 4 different locations 
depending on the value of the optional scope attribute of jsp:useBean:



Documentation and tutorials from Sun



Go home
Go back to subjects page 1