Java Beans 2017
Java Beans 2017
JavaBean technology is a Java-based technology to design and develop reusable and platform independent software
components. These components can then be integrated virtually in all Java compatible applications. JavaBean components
are knows as beans. The appearance and features of a bean can be changed or customized using builder tools such as
BeanBox and NetBeans.
A bean class is nothing but a usual Java class with the following requirements:
• It must have a public no-argument constructor.
• It has public accessor methods to read and write properties.
• It should implement Serializable or Externalizable interface.
So, virtually all Java classes are already bean classes or they can be converted to beans with a little effort. For
example, the following is an example of a bean class.
//Factorial.java
import java.io.*;
public class Factorial implements Serializable
{
protected int n;
protected long fact;
2.1 Properties
A bean typically has one or more properties that control appearance and behaviour. Properties are discrete, named
attributes of a bean. They constitute the data part of a bean’s structure and represent the internal state of a bean. Properties
allow us to isolate component state information into discrete pieces that can be easily modified.
In our Factorial bean, there are two properties: n and fact. The property n holds an integer value, whose factorial is stored
in the property fact. Here, n is said to be independent property and fact is dependent on n as the value of fact can be
calculated from n.
2.2 Accessor Methods
The primary way to access bean properties is through accessor methods. An accessor method is a public method of the
bean that directly reads or writes the value of a particular bean. For example, the getN() method of the Factorial bean
returns the value of the property n. Similarly, setN() sets the value of n. For the fact property, only one method is
provided, which returns the value of the property fact. The methods that are responsible for reading property values are
called reader(getter) methods. Similarly, methods that are responsible for changing property values are called
writer(setter) methods.
3 BEAN BUILDER
Readymade applications are available that provide an environment in which we can build and test beans. Those tools are
known as builder tools. Some of the popular bean builder tools are Sun’s BeanBox and NetBeans, JBuilder, Borland’s
Delphi, etc.
A builder tool is able to display several beans simultaneously. It is also able to connect different beans together in a visual
manner. So, we can manipulate a bean without writing any piece of code. Most builder tools have a palette of components
from which developers can drag and drop components onto a graphical canvas.
The facilities supported by a bean builder vary widely, but there are some common features as follows:
• Introspection—ability to analyze a bean to discover properties, methods, and events
• Properties—used for customization of the state of a bean
• Events—a way used by beans to tell the outside that something is happening, or to react to something that
happened outside the bean
• Customization—a developer of a bean can customize the behaviour and appearance of the bean within a builder tool
• Persistence—a builder tool allows us to customize a bean, and have its state saved away and reloaded later
4 ADVANTAGES OF JAVABEANS
Write Once
A good software component technology should encourage component developers to write code only once. The component
should not require rewriting of code to add and/or improve features.
JavaSoft developed JavaBean technology, which allows us to add or improve functionality in the existing code, without
re-engineering the original code.
This means that developers can make changes to components incrementally, instead of rewriting significant portions from
scratch. This results in a steady improvement of functionality, which, in turn, dictates a more consistent software
component development through increasing versions.
Run Anywhere
A software technology must be platform independent to have a realistic meaning in today’s rapidly varying software
environment. This refers to the capability of software components developedusing a technology to be executed (run) in
any environment. Fortunately, JavaBeans components are ultimately Java components. Consequently, cross-platform
support comes automatically.
Good software components should also run across distributed network environments. This can be simply achieved using
Java’s powerful technology, Remote Method Invocation (RMI), Socket, and RMI-IIOP.
Use Everywhere
This is perhaps the most important part of the JavaSoft’s JavaBean mission statement. Well designed JavaBeans
components are capable of being used in a wide range of situations, which include applications, other components,
documents, websites, application builder tools, and so on.
JavaBeans are compact components and can be transferred across a low-bandwidth Internet connection that facilitates a
reasonable transfer time.
5 BDK INTROSPECTION
A bean builder usually uses Java core reflection API to discover methods of a bean. It then applies the design pattern to
discover other bean features (such as properties and events). This procedure is known as introspection.
5.1 Design Patterns
The JavaBeans framework introduces a lot of rules for names to be used for classes and methods. They are collectively
called design patterns.
Builder tools such as BeanBox, NetBeans, and JBuilder use these conventions and design patterns to introspect a bean’s
properties, methods, and events. Consequently, they can provide an environment where we can customize bean features.
Suppose, a bean has a property called “xxx”. JavaBean technology encourages us to use “getXxx” as the name of the
reader method and “setXxx” as the name of the writer method. If the property happens to be a Boolean, the reader method
could be named “isXxx”. For example, our State bean has the property state. So, the reader method is “getState” and the
writer method is “setState”.
A BeanInfo class is a class that is used to provide information about a bean explicitly. To do this, a class is created
implementing the BeanInfo interface. The name of this class should also follow a naming rule. The name of the BeanInfo
class must be the name of the target bean, followed by the string “BeanInfo”. For example, the name of the BeanInfo class
for the bean Person must be “PersonBeanInfo”.
BeanInfo
The java.beans.BeanInfo interface defines a set of methods that allow bean developers to provide information about their
beans explicitly. By specifying BeanInfo for a bean component, a developer can hide methods, specify an icon for the
toolbox, provide descriptive names for properties, define which properties are bound, etc.
Introspector
The java.beans.Introspector class provides descriptor classes with information about properties, methods, and events of a
bean.
The getBeanInfo() method of the Introspector class can be used by builder tools and other automated environments to
provide detailed information about a bean. The getBeanInfo() method relies on the naming conventions for the bean’s
properties, events, and methods.
The following example finds the properties and methods of our Factorial bean.
//IntrospectionDemo.java
import java.beans.*;
public class IntrospectionDemo {
public static void main( String[] args ) throws IntrospectionException {
BeanInfo info = Introspector.getBeanInfo( Factorial.class,Object.class );
System.out.println("properties: ");
for ( PropertyDescriptor pd : info.getPropertyDescriptors() )
System.out.println(" " + pd.getName());
System.out.println("methods: ");
for ( MethodDescriptor pd : info.getMethodDescriptors() )
System.out.println(" " + pd.getName());
}
}
6 PROPERTIES
The properties of a bean represent and control its behaviour and appearance. JavaBean API allows us to create the
following primary property types.
6.1 Simple Properties
Simple properties of a bean are those that do not depend on other beans or control properties of another bean. Properties
are typically declared as private. To access them, get and set methods are used. The names of the get and set methods
follow specific rules, known as design patterns. JavaBean-enabled builder/tester tools (such as NetBeans and BeanBox)
use these design patterns to do the following:
• Discover the properties of a bean
• Determine the types of the properties
• Display the properties in the property window
• Determine the read/write attribute of the properties
• Find the appropriate property editor for each property type
• Allow us to change the properties
Suppose a bean builder/tester tool encounters the following methods on a bean:
public int getValue() { ... }
public void setValue(int v) { ... }
The tool infers the following:
• There exists a property name value.
• Its type is int.
• It is readable and writable.
• It displays the value of this property in the property editor.
• Moreover, it finds the property editor that allows us to change the value of the property.
Creating a Simple Property
The following code is used in the bean to create the property propertyName: private PropertyType propertyName =
initialValue;
Providing a Reader Method
The following code is used to provide a reader method:
PropertyType getPropertyName() {
return propertyName;
}
PropertyChangeEvent
A PropertyChangeEvent object is generated whenever a bound property of a bean changes. This object is then sent from
the source bean to all registered PropertyChangeListener objects, as an argument of their respective PropertyChange()
method. This class encapsulates the property change information. It provides several useful methods as follows:
String getPropertyName()
Returns the name of the property that was changed and caused this event firing
Object getOldValue()
Returns the value of the property as an object before it was changed. The bean writer should typecast it to
the desired type.
Object getNewValue()
Returns the value of the property as an object after it was changed. The bean writer must typecast
it to the desired type.
26.7 BEANINFO INTERFACE
A bean builder typically uses the introspection process to discover features (such as properties, methods, and events). In
this case, the bean builder exposes all the features to the outside world. We can also expose the bean’s features by using
an associated class explicitly. By doing this we obtain the following benefits:
• Hide features we do not want to disclose
• Provide more information about bean features
• Associate an icon with the target bean
• Group bean features into different categories such as normal and advanced groups
• Specify a customizer class
• Expose some bean features explicitly using Java reflection API
The features of a bean are exposed using a separate special class. This class must implement the BeanInfo interface. The
BeanInfo interface defines several methods that can be used to inspect properties, methods, and events of a bean. The
following is the declaration of the BeanInfo interface:
public interface java.beans.BeanInfo{
public static final int ICON_COLOR_16x16;
public static final int ICON_COLOR_32x32;
public static final int ICON_MONO_16x16;
public static final int ICON_MONO_32x32;
public abstract java.beans.BeanDescriptor getBeanDescriptor();
public abstract java.beans.EventSetDescriptor[] getEventSetDescriptors();
public abstract int getDefaultEventIndex();
public abstract java.beans.PropertyDescriptor[] getPropertyDescriptors();
public abstract int getDefaultPropertyIndex();
public abstract java.beans.MethodDescriptor[] getMethodDescriptors();
public abstract java.beans.BeanInfo[] getAdditionalBeanInfo();
public abstract java.awt.Image getIcon(int);
}
26.8 PERSISTENCE
Sometimes, it is necessary to store the beans for later use. Persistence is a procedure to save a bean in non-volatile storage
such as a file. The bean can be reconstructed and used later. The important point is that persistence allows bean
developers to save the current state of the bean and retrieve the same at some later point of time.
Factorial f = new Factorial();
for(int i = 2; i <= 10; i++) {
f.setN(i);
System.out.println(i + "! = " + f.getFact()+ " ");
}
26.9 CUSTOMIZER
Bean customization allows us to customize the appearance and behaviour of a bean at design time, within a bean-
compliant builder tool. There are two ways to customize a bean:
• Using a property editor
• Using Customizers
Property editors are usually supplied by the builder tool, although you can write your own property editor.
1. Enterprise Java Beans
Enterprise JavaBeans (EJB) is a Java-based comprehensive component architecture for design and development of world-
class distributed modular enterprise applications. EJBs are not only platform-independent, but can also run in any
application server that implements EJB specifications.
The EJB component architecture integrates several enterprise-level requirements such as distribution, transactions,
security, messaging, persistence, and Enterprise Resource Planning (ERP) systems.
Benefits
Simplified development of large scale enterprise level application.
Application Server/ EJB container provides most of the system level services like transaction handling, logging,
load balancing, persistence mechanism, exception handling and so on. Developer has to focus only on business
logic of the application.
EJB container manages life cycle of ejb instances thus developer needs not to worry about when to create/delete
ejb objects.
Types of EJB
There are three kinds of beans in the EJB architecture: Session Beans, Entity Beans, and Message Driven Beans. EJB are
primarily of three types which are briefly described below:
Type Description
1.1 Session Bean Session bean stores data of a particular user for a single session. It can
be stateful or stateless. It is less resource intensive as compared to entity beans. Session
bean gets destroyed as soon as user session terminates.
1.2 Entity Bean Entity beans represents persistent data storage. User data can be saved to database via entity
beans and later on can be retrived from the database in the entity bean.
1.3 Message Driven Bean Message driven beans are used in context of JMS (Java Messaging Service). Message
Driven Beans can consumes JMS messages from external entities and act accordingly.
Entities
o The things that a business process manipulates
o E.g. Customers, Accounts, Orders, Flights
o The data they contain is stored in database tables
Entity Bean
o A bean representing a business entity
o The object representation of a row of data in a table
Entity beans are shared
Container creates a pool
Instances in use represent distinct entities
o
Entity beans differ from session beans:
o Entity beans are always stateful
o They are always persistent - they map to a database
o They are always shared
o Client can find existing ones as well as create new ones
Entity beans require a primary key
To demonstrate use of message driven bean, we'll make use of ejb-persistence chapter and we're going to do the
following tasks.
Step 5. Update stateless ejb.Add methods to add records and get records from database via entity manager (Refer
to EJB-Persistencechapter).
Step 8. Create a Message driven bean which will use the stateless bean to persist the client data.
Step 9. EJB Container of jboss will call the above message driven bean and pass it the message that client will be
sending to.
success.jsp
error.jsp
index.jsp
LogingEx.java [ in java4s package ]
web.xml [ in web-inf ]
struts.xml [ in web-inf/classes folder ]
index.jsp
success.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
You have been successfully executed struts 2 hello world program..
error.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
Login failed, wrong user name, user name must be mscjava
LogingEx.java
import com.opensymphony.xwork2.ActionSupport;
public class Login extends ActionSupport{
private static final long serialVersionUID = 1L;
private String uname;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String execute()
{
if(uname.equals("java4s"))
{
return SUCCESS;
}else
return ERROR;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml"/>
<package name="a" extends="struts-default">
<action name="verify" class="java4s.Login">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
OUTPUT