JavaBean Components

JavaBean components are considered as the java classes that can be used by composing together in an application and these classes can also be reused. The javaBean is a java class which has no argument constructor. These classes have the feature or properties of the getter and setter methods. These classes also do not define the instance variables as public. The javaBean class must also implement the java.io.Serializable interface.

 

Example of JavaBean:

Consider the following example in which we have used the javaBean class which has setter and getter methods for the name and roll number of the employee:

CODE:

import java.io.Serializable;

public class EmpBean implements Serializable

{

 private String n;

 private int r;

   public EmpBean()

   {

    this. n =””;

    this. r =””;

   }

   public void settingName (String n)

   {

    this. n = n;

   }

   public String gettingName()

   {

    return n;

   }

public int getID()

   {

    return r;

   }

public void setID (int r)

   {

    this. r = r;

   }

}

In the above example first we imported java. io. serializable by using the import key keyword then we have a class and in the class we have declared two variables that are n and r for name and the id of the employee respectively. Note that we have a constructor with no arguments and in the constructor the variables n and r are initialized to avoid garbage values and we used the this keywork.

In the settingName () method the name of the employee is set and in gettingName () method the name of the employee is returned. Similarly we have done with the variable r for the id of the employee.

 

Using a JavaBean in JSP page:

In any JSP page we can use the Javabeans by simply using the jsp: useBeans tag. Consider the following line of code in which we have used the jsp: useBean tag:

CODE:

<jsp: useBean id = “beanId” />

 

Use any JavaBean property in JSP page:

In a JSP page we can use the javaBeans by simply using either of the actions tags: <jsp: useBean > tag, <jsp: setproperty > tag, and <jsp: getproperty > tag. Consider the following example in which we have used al the three tags to add javaBeans to the JSP page:

CODE:

<jsp: useBean id=”id” class=”name of bean class” >

<jsp: setProperty name=”id of beans” property=”name of property” value = “Any value”/>

<jsp:getProperty name=”id of beans” property=”name of property” / >

</jsp:useBean>