understanding java bean with example and best explanation

JAVA BEAN

A JavaBean is a special type of Java class that you can use in several interesting ways to simplify program development. Some beans, such as Swing components, are designed to be visual components that you can use in a GUI editor to quickly build user interfaces. Other beans, known as Enterprise JavaBeans, are designed to run on special EJB servers and can run the data access and business logic for large Web applications.
In this chapter, I look at a more modest type of JavaBean that’s designed to simplify the task of building Java Server Pages. In a nutshell, you can use the simple JavaBeans to build Java Server Pages without writing any Java code in the JSP itself. JavaBeans let you access Java classes by using special HTML-like tags in the JSP page.

Features of Java Beans
A JavaBean is any Java class that conforms to the following rules:
✦ It must have an empty constructor. That is, a constructor that accepts no parameters. If the class doesn’t have any constructors at all, it qualifies because the default constructor has no parameters. But if the class has at least one constructor that accepts one or more parameters, it must also have a constructor that has no parameters to qualify as a JavaBean.
✦ It must have no public instance variables. All the instance variables defined by the class must be either private or protected.
✦ It must provide methods named getProperty and setProperty to get and set the value of any properties the class provides, except for boolean properties that use isProperty to get the property value. The term property isn’t really an official Java term. In a nutshell (or should it be, in a
beanpod?), a property is any value of an object that can be retrieved by a get method (or an is method if the property is boolean) or set with a set method. For example, if a class has a property named lastName, it should use a method named getLastName to get the last name and setLastName to set the last name. Or, if the class has a boolean property named taxable, the method to set it is called setTaxable, and the method to retrieve it is isTaxable.
Note that a class doesn’t have to have any properties to be a JavaBean, but if it does, the properties have to be accessed according to this naming pattern. Also, not all properties must have both a get and a set accessor. A read-only property can have just a get accessor, and a write-only property can have just a set accessor.

The property name is capitalized in the methods that access it, but the property name itself isn’t. Thus, setAddress sets a property named address, not Address.

Any class that conforms to this pattern is a bean. There’s no JavaBean class you have to extend, nor is there a Bean interface you have to implement to be a bean. All a class has to do to be a bean is stick to the pattern.

Creating a Sample Bean
Listing  shows a sample JavaBean class named Triangle that calculates the Pythagorean Theorem, which calculates the long side of a right triangle if you know the length of the two short sides. This class defines three properties: sideA and sideB represent the two short sides of the triangle, and sideC represents the long side. The normal way to use this bean is to first use the setSideA and setSideB methods to set the sideA and sideB properties to the lengths of the short sides, and then use the getSideC method to get the length of the long side. TRIANGLE BEAN

package calculators;
public class Triangle
{
  private double sideA;
  private double sideB;
  public Triangle()
  {
this.sideA = 0.0;
this.sideB = 0.0;
   }
   public String getSideA()
   {
        return Double.toString(this.sideA);
   }
   public void setSideA(String value)
   {
    try  {
        this.sideA = Double.parseDouble(value);
           }
     catch (Exception e) {
        this.sideA = 0.0;  }
   }
   public String getSideB()
   {
      return Double.toString(this.sideB);
   }
   public void setSideB(String value)
  {
   try      {
this.sideB = Double.parseDouble(value);
      }
    catch (Exception e)  {
this.sideB = 0.0;  }
  }
  public String getSideC() {
if (sideA == 0.0 || sideB == 0.0)
    return “Please enter both sides.”;
else {
                         Double sideC;
         sideC = Math.sqrt( (sideA * sideA) + (sideB * sideB));
         return Double.toString(sideC); }
    }
}


Using Beans with JSP Pages
To work with a bean in a JSP page, you add special tags to the page to create the bean, set its properties, and retrieve its properties. Table lists these tags, and the following sections describe the details of using each one.
Table:
Tag Description
<jsp:useBean id=”name” Establishes a reference to the bean
class=”package.class” /> and creates an instance if necessary. The name specified in the id attribute is used by the
other tags to refer to the bean.

<jsp:getProperty name=”name” Retrieves the specified property
property=”property” /> from the bean identified by the name attribute.

<jsp:setProperty name=”name” Sets the specified property to the
property=”property” value= value specified in the value
”value” /> attribute.

<jsp:setProperty name=”name” Sets the specified property to the
property=”property” param= value of the parameter specified in.
”parameter” /> the param attribute The parameter is usually the name of a form field.

<jsp:setProperty name= Sets all the properties defined by
”name” property=”* “ /> the bean to corresponding parameter values, provided a
parameter with the correct name exists.
Creating bean instances
To include a bean in a JSP page, you add a special jsp:useBean tag to the
page. In its simplest form, this tag looks like this:
<jsp:useBean id=”name” class=”package.Class” />
The id attribute provides the name that you use elsewhere in the JSP to refer to the bean, and the class attribute provides the name of the class, qualified with the package name. For example, here’s a jsp:useBean tag to use the Triangle bean:
      <jsp:useBean id=”triangle” class=”calculators.Triangle”/>
The jsp:useBean tag creates an instance of the bean by calling the empty
constructor if an instance doesn’t already exist. However, if the bean already exists, the existing instance is used instead.
Here are a few additional things you should know about the jsp:useBean tag:
✦ The jsp:useBean tag can appear anywhere in the JSP document, but it
must appear before any other tag that refers to the bean.
✦ This and all bean tags are case sensitive, so be sure to code them
exactly as shown. <jsp:usebean.../> won’t work.
✦ If Tomcat complains that it can’t find your bean when you run the JSP,
double-check the package and class name — they’re case sensitive too —
and make sure the bean is stored in a directory under WEB-INF\classes
that’s named the same as the package. For example, store the Triangle
bean’s class file in WEB-INF\classes\calculators.

✦ The jsp:useBean element can have a body that contains jsp:setProperty tags that initialize property values. Then, the element is formed more like normal HTML, with proper start and end tags. For example:
<jsp:useBean id=”t1” class=”calculators.Triangle” >
<jsp:setProperty name=”t1” property=”sideA”
value=”3.0” >
<jsp:setProperty name=”t1” property=”sideB”
value=”3.0” >
</jsp:useBean>
Don’t worry about the details of the jsp:setProperty tags just yet.
Instead, just make a note that they’re executed only if a new instance of
the bean is actually created by the jsp:useBean tag. If an instance of
the bean already exists, the jsp:setProperty tags are not executed.

Getting property values
To get the value of a bean’s property, you use the jsp:getProperty tag.
The form of this tag is straightforward:
<jsp:getProperty name=”name” property=”property” />
For example, here’s a tag that gets the sideC property from the Triangle
bean created in the previous section:
<jsp:getProperty name=”triangle” property=”sideC” />
The name attribute must agree with the value you specify in the id attribute in the jsp:useBean tag that created the bean. And the property
attribute is used to determine the name of the getter method — in this case,
getSideC.
Remember to begin the property name with a lowercase letter. If you specify property=”SideC”, you get an error message from the server when you run the page.
In most cases, you use jsp:getProperty to insert the value of a property
into a page. However, you can also use it to specify the value of an attribute for some other tag in the JSP document. For example:
<input type=”text” name=”sideA”
value=”<jsp:getProperty name=”triangle”
property=”sideA” />” >
Here, the value of the sideA property is retrieved and used for the value
attribute of an input field named sideA. As a result, when this input field is
sent to the browser, its initial value is the value from the Triangle bean.
Be extra careful to match up the quotation marks and the open and close
brackets for the tags. In this example, the entire jsp:getProperty tag is
enclosed within the quotation marks that indicate the value of the input field’s value attribute. The right bracket that appears at the very end closes the input element itself.

Setting property values
To set a property value, you can use one of several variations of the jsp:
setProperty tag. If you want to set the property to a literal string, you
write the tag like this:
<jsp:setProperty name=”triangle”
 property=”sideA” value=”4.0”   />  
Here, the name attribute must match up to the id attribute from the jsp:
useBean tag that created the bean, the property attribute is used to
determine the name of the setter method (in this case, setSideA), and
the value attribute provides the value to be set.
Although this form of the jsp:setProperty tag is useful, the param form
is more useful. It lets you set the property to the value entered by the user
into a form field or passed to the JSP by way of a query string. For example, if your JSP contains a form that has an input field named FirstSide, you can assign that field’s value to the sideA property like this:
<input type=”text” name=”FirstSide” >
<jsp:setProperty name=”triangle”
property=”sideA”
param=”FirstSide” />
Here, if the user enters a value into the FirstSide field, that value is
assigned to the bean’s sideA property.
In the previous example, I purposely used a name other than sideA for the
input field so you wouldn’t be confused by the fact that the property and
param attributes specify the same value. In actual practice, you usually give the input field the same name as the property it’s associated with, like this:
<input type=”text” name=”sideA” >
<jsp:setProperty name=”triangle”
property=”sideA”
param=”sideA” />
If your input fields have names that are identical to the property names, you can assign all of them to their corresponding properties with one tag, like this:
<jsp:setProperty name=”triangle” property=”*” />
Here, the asterisk (*) in the property attribute indicates that all properties
that have names identical to form fields (or query string parameters) are
automatically assigned. For forms that have a lot of fields, this form of the
jsp:setProperty tag can save you a lot of coding.

A JSP page that uses a bean
So that you can see how these tags work together, Listing  shows a complete JSP page that uses the bean that was presented in Listing . This page displays two text input fields and a button. When the user enters the lengths of a triangle’s two short sides in the fields and clicks the button, the page displays the sideC property of the bean to show the length of the third side. Figure 1 shows how this page appears when it is run.





<html>
<jsp:useBean id=”triangle” class=”calculators.Triangle” />
<jsp:setProperty name=”triangle” property=”*” />
<head>
<title>Right Triangle Calculator</title>
</head>
<body>
<h1>The Right Triangle Calculator</h1>
<form action=”Triangle.jsp” method=”post”>
   Side A:&nbsp;
<input type=”text” name=”sideA” value=”<jsp:getProperty
name=”triangle” property=”sideA” />” >
<br><br>
Side B:&nbsp;
<input type=”text” name=”sideB”
value=”<jsp:getProperty name=”triangle” property=”sideB” />” >
<br><br>
Side C:&nbsp;
<jsp:getProperty name=”triangle” property=”sideC” />
<br><br>
<input type=”submit” value=”Calculate” >
</form>
</body>
</html>

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation