Using Java Beans in JSP
How is Beans used in JSP?
Explanation
Java bean is nothing but a class that implements java.io.Serializable interface and uses set/get methods to project its properties. Since they are reusable instance of a class Java beans provides the flexibility to JSP pages.
There are three basic actions or tags used to embedd a java bean into a jsp page they are <jsp:useBean>, <jsp:setProperty>, <jsp:getProperty>.
<jsp:useBean>
This tag is used to associate a bean with the given "id" and "scope" attributes.
<jsp:setProperty>
This tag is used to set the value for a beans property mainly with the "name" attribute which defines a object already defined with the same scope. Other attributes are "property", "param", "value"
<jsp:getProperty>
This tag is used to get the referenced beans instance property and stores in implicit out object.
Rules for Beans:
- Package should be first line of Java bean
- Bean should have an empty constructor
- All the variables in a bean should have "get", "set" methods.
- The Property name should start with an Uppercase letter when used with "set", "get" methods.
- For example the variable "name" the get, set methods will be getName(), setName(String)
- Set method should return a void value like "return void()"
Example :
package pack;
public class Counter
{
int count = 0;
String name;
public Counter() { }
public int getCount()
{
return this.count;
}
public void setCount(int count){
this.count = count;
} public String getName(){
return this.name; } public void setName(String name){
this.name=name; }
}
Example 2 :
<%@ page language="java" %>
<%@ page import="pack.Counter" %>
</body>
<jsp:useBean id="counter" scope="page" class="pack.Counter" />
<jsp:setProperty name="counter" property="count" value="4" />
Get Value: <jsp:getProperty name="counter" property="count" /><BR>
<jsp:setProperty name="counter" property="name" value="prasad" />
Get Name: <jsp:getProperty name="counter" property="name" /><BR>
In the above examples the bean that is being included is Counter.java, that has defined the set/get properties for the "counter", "name" objects. Using the bean.jsp page first the bean is included using the <jsp:useBean> action, using the <jsp;setProperty> we set the property of "counter" to "4" and for "name" it set to "prasad". With the <jsp:getProperty> we get the values.