JSP Tutorial - JSP JavaBeans








A JavaBean is Java code following the JavaBeans API specifications.

A JavaBean has the following features.

  • It has a default, no-argument constructor.

  • It should implement the Serializable interface.

  • It has a list of properties for reading or writing.

  • It has a list of getter and setter methods for the properties.

The following code shows how to create a Student JavaBean.

The firstName, lastName and age are all properties. And each property has a getter method and a setter method.

For example, the getter method for firstName is getFirstName, it is created by uppercase the first letter of the property and append get to the front.

We can use the same way to create setter methods.

package com.java2s;

public class StudentsBean implements java.io.Serializable
{
   private String firstName = null;
   private String lastName = null;
   private int age = 0;

   public StudentsBean() {
   }
   public String getFirstName(){
      return firstName;
   }
   public String getLastName(){
      return lastName;
   }
   public int getAge(){
      return age;
   }
   public void setFirstName(String firstName){
      this.firstName = firstName;
   }
   public void setLastName(String lastName){
      this.lastName = lastName;
   }
   public void setAge(Integer age){
      this.age = age;
   }
}




Example

The useBean action declares a JavaBean in a JSP. The syntax for the useBean tag is as follows:

<jsp:useBean id="bean's name" scope="bean's scope" typeSpec/>

The scope attribute could be page, request, session or application.

The id attribute should be a unique name among other useBean declarations in the same JSP.

The following code shows how to use java Date bean.

<html>
<body>
<jsp:useBean id="date" class="java.util.Date" /> 
<p>The date/time is <%= date %>

</body>
</html>

To get JavaBean property, use <jsp:getProperty/> action. To set JavaBean property, use <jsp:setProperty/> action.

<jsp:useBean id="id" class="bean's class" scope="bean's scope">
   <jsp:setProperty name="bean's id" property="property name"  
                    value="value"/>
   <jsp:getProperty name="bean's id" property="property name"/>
   ...........
</jsp:useBean>

The following code shows how to get and set the StudentBean's properties.

<html>
<body>
<jsp:useBean id="students" class="com.java2s.StudentsBean"> 
   <jsp:setProperty name="students" property="firstName" value="Jack"/>
   <jsp:setProperty name="students" property="lastName" value="Smith"/>
   <jsp:setProperty name="students" property="age" value="24"/>
</jsp:useBean>

<p>Student First Name: <jsp:getProperty name="students" property="firstName"/>
</p>
<p>Student Last Name: <jsp:getProperty name="students" property="lastName"/>
</p>
<p>Student Age: <jsp:getProperty name="students" property="age"/>
</p>

</body>
</html>

Save StudentsBean.class available in CLASSPATH.