JSP JavaBean Components
A JavaBeans component is a Java class with the following features:
- A no-argument constructor.
- Properties defined with accessors and mutators(getter and setter method).
- Class must not define any public instance variables.
- The class must implement the java.io.Serializable interface.
Example of a JavaBean
Let's take a simple Java code example to understand what do we mean when we say JavaBean,
import java.io.Serializable;
public class StudentBean implements Serializable
{
private String name;
private int roll;
// constructor
public StudentBean()
{
this.name = "";
this.roll = "";
}
// getters and setters
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public int getRoll()
{
return roll;
}
public void setRoll(int roll)
{
this.roll = roll;
}
}
As you can see in the code above, a JavaBean is nothing but a Java class which implements the interface Serializable
.
Using a JavaBean in JSP page
JavaBeans can be used in any JSP page using the <jsp:useBean>
tag, For example:
<jsp:useBean id="bean name" scope="fully qualified path of bean" typeSpec/>
Using any JavaBean property in JSP page
JavaBeans can be used in any JSP page using the <jsp:useBean>
tag, <jsp:setProperty>
tag and <jsp:getProperty>
tag , For example:
<jsp:useBean id="id" class="bean class name" scope="fully qualified path of bean">
<jsp:setProperty name="beans id" property="property name" value="value"/>
<jsp:getProperty name="beans id" property="property name"/>
...........
</jsp:useBean>
We will learn about the jsp:useBean
tag in details in the next tutorial.