JavaBeans
This chapter discusses how JavaBeans can be used inside a JSP page. It is good idea to put all the logic inside
reusable components such as JavaBeans, when setting up an application development architecture that involves java server pages (JSP).
These components can then be plugged in to any JSP that requires them.
What is java bean?
Let us first define what is JavaBeans is. The JavaBean is a java class file that fits the following criteria
Public class
Public constructor with no arguments
Public set and get methods to simulate properties
JavaBeans are mostly used to encapsulate visual and non visual components of a GUI. A bean can also be serialized and a saved to latter use. When a bean component is serialized, it saves current state. Typically bean components are imported into a program, its properties are set and their methods are called. Thus we say JavaBeans are portable, platform independent components model written in java. when setting up an application development architecture that involves java server pages(JSP) it is a good idea to pull all your logic inside reusable components such as JavaBeans. These components can then be plugged into any JSP that requires them.
How to write a bean?
Let us see how a bean is written and how its properties are set. The bean conventions are what enable us to develop Beans. Because they allow a bean containers to analyze a java class file and interpret its methods as properties
The first rule of JSP bean building is that you must implement a constructor that takes no arguments. It is this constructor that the JSP container will use to instantiate your bean thought the <jsp:useBean> tag. If no constructor is explicitly specified a default zero arguments constructor is assumed.
Exposing your Beans access methods by declaring them public is the only way that JSP pages will be able to access them. The JSP container will not recognize properties without public access methods.
If the actual data being reflected by the components properties is stored in instance variables, it should be intentionally hidden form other classes. Such instance variable should be declared private, or at least protected. This helps ensure that developers restrict their interaction with the class to its access methods and not its internal workings.
The JSP container can interact with Bean objects without the benefit of a common interface or base class to fall back on, through a process called introspection that allows a class to expose its properties on request. The introspection process happens at run time, controlled by the Bean container.
Advantage of using JavaBeans
There are various advantages of using the JavaBeans-
It is simple to learn the structure of JavaBeans if one has the knowledge of java
-
JavaBeans need to be registered on the server. So in case of changes, the server does not need to be rebooted to reflect the changed. This is huge advantage if developers don’t have full access to the server.
-
Full libraries of JavaBeans can be created to suit the needs of the business. Allowing non programming web developers to use the library to develop dynamic web applications
-
Beans that are in byte-code format on the server and can manage database connections by protecting usernames and passwords hard coded in the file.
A simple bean example
As an example lets create a JSP components that know how to calculate the future value of money that is accumulating interest. Such a Bean would be useful for an application allowing the user to compare investment.
|
package Interest;
public class CompoundInterestBean implements java.io.Serializable
{
private double rate, principal ;
private int year, cmpd;
public double Calculate()
{
return principal*Math.pow(1+rate/100,(year*12)/cmpd);
}
public void setRate(double rate)
{ if(rate>0) this.rate = rate;
else this.rate=0;
}
public double getRate()
{ return this.rate ;
}
public void setYear(int year)
{ if(year>=1) this.year = year;
else this.year=0;
}
public int getYear()
{ return this.year ;
}
public void setPrincipal(double principal)
{ this.principal = principal;
}
public double getPrincipal()
{ return this.principal ;
}
public void setCmpd(int cmpd)
{ if(cmpd>=1) this.cmpd = cmpd;
else this.cmpd=0;
}
public int getCmpd()
{ return this.cmpd ;
}
}
|
CompountIntersetJSP.jsp
<%@ page import="java.text.NumberFormat, Interest.*" %>
<html>
<head> <title> A JSP Bean Example </title> </head>
<jsp:useBean
id="CIBean"
scope="session"
class="Interest.CompoundInterestBean"/>
<jsp:setProperty name="CIBean" property="*" />
</jsp:useBean>
<body bgcolor= "#eeffee">
<h2> Calculating Compound Interest </h2>
<% NumberFormat nf=NumberFormat.getCurrencyInstance();
out.println(nf.format(CIBean.Calculate() ) );
%>
<hr>
<p> Principal:<jsp:getProperty name="CIBean" property="principal"/>
<p> Rate:<jsp:getProperty name="CIBean" property="rate"/>
<p> Year:<jsp:getProperty name="CIBean" property="year"/>
<p> Compounds:<jsp:getProperty name="CIBean" property="cmpd"/>
<hr>
</body>
</html>
|
CompoundIntersetHeader.html
<html>
<body>
<form method="get" action="CompoundInterestJSP.jsp">
<center>
<h1> Compound Interest Calculator </h1>
<table border="2">
<tr> <td> Principal </td> <td> <input type="text" name="principal"> </td> </tr>
<tr> <td> Rate </td> <td> <input type="text" name="rate"> </td> </tr>
<tr> <td> Year </td> <td> <input type="text" name="year"> </td> </tr>
<tr> <td> Compound </td> <td> <input type="text" name="cmpd"> </td> </tr>
</table>
<input type="submit" value="Calculate">
</form>
</body>
</html>
|
Bean in JSP environment
Let us now see how bean is handled in a JSP environment.. When a user sends a request through the browser, it may be for static or dynamic information. It is a dynamic; it will be handled by the servlet. The servlet locates on or more JavaBeans needed to perform the request. It configures the bean using request parameter and involves the required business logic method. The servlet then stores a reference to the result bean so it is available to JSP.
The following example displays the name of the user and his machine. It first gets the name form the form saves it in the bean using, <jsp:setProperty> and then displays them using <jsp:getProperty>
|
Jspbeantest.jsp
<%@ page import="Hello.NameHandler" %>
<jsp:useBean id="myBean" scope="page" class="Hello.NameHandler"/>
<jsp:setProperty name="myBean" property="*"/>
<html>
<head> <title> A JSP - Bean Exmple </title></head>
<body>
<table border="0" width="50%">
<tr>
<td><h2> This is local host what is ur name ? </h2></td>
</tr>
<tr>
<td align="center">
<form method="get">
<input type="text" name="userName" size="25">
<br>
<input type="submit" value="submit">
<input type="reset" value="reset">
</td>
</tr> </form> </table>
<%
if( request.getParameter("userName") != null)
{ %>
<%@ include file="response.jsp" %>
<% } %>
</body>
</html>
|
response.jsp
<table border="0" width=700>
<tr>
<td width="150"> </td>
<td width="550">
<h1> Hello, <jsp:getProperty name="myBean" property="userName"/>
</h1> </td> </tr> </table>
|
The .java file that represents that bean can be seeing below
NameHandaler.java
package Hello;
public class NameHandler
{
private String userName;
public NameHandler()
{ userName=null; }
public void setUserName (String name)
{
userName=name;
}
public String getUserName()
{ return userName; }
}
|