0% found this document useful (0 votes)
74 views11 pages

Java Beans 2017

1. JavaBean technology allows for the creation of reusable software components called beans. Beans can have customizable properties and behaviors and can be integrated into various Java applications. 2. A bean class must have a public no-argument constructor and public getter and setter methods to access properties. Common bean properties include name, value, state etc. 3. Bean builder tools allow visual editing of beans, including setting properties, connecting beans, and saving bean states. Popular tools include BeanBox and NetBeans. They use introspection and naming conventions to interact with bean properties and methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views11 pages

Java Beans 2017

1. JavaBean technology allows for the creation of reusable software components called beans. Beans can have customizable properties and behaviors and can be integrated into various Java applications. 2. A bean class must have a public no-argument constructor and public getter and setter methods to access properties. Common bean properties include name, value, state etc. 3. Bean builder tools allow visual editing of beans, including setting properties, connecting beans, and saving bean states. Popular tools include BeanBox and NetBeans. They use introspection and naming conventions to interact with bean properties and methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

INTRODUCTION TO JAVABEANS

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;

public int getN() {


return n;
}
public void setN(int n) {
this.n = n;
long prod = 1;
for(int i = 2; i <= n; i++)
prod *= i;
fact = prod;
}
public long getFact() {
return 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;
}

Providing a Writer Method


The following code is used to provide a writer method:
void getPropertyName(PropertyType value) {
propertyName = value;
}

6.2 Bound Properties


Sometimes, when a property of a bean changes, you might want to notify another object about this change. This object
typically reacts to the change by changing one of its properties. For example, consider two beans Parent and Child, each
having two properties, firstName and familyName. The familyName property of Child and Parent must have the same
value. So, whenever the familyName property of Parent changes, the familyName property of Child must also be changed
to make them synchronized.
This synchronization can be implemented using the bound property. The accessor or modifier methods for a bound
property are defined in the same way, except that whenever a bound property changes, a notification is sent to the
interested listeners. Whenever a property of a bean changes, a “PropertyChange” event gets fired. The bean generating the
event is called source bean. We can register one or more “Listener” objects with a source, so that these objects get notified
when a bound property of the source bean is updated.
Bean Development Kit (BDK) provides special classes to accomplish coordination between the notifier and listener.
PropertyChangeListener
If an object is interested in being notified about the property changes of a source bean, its class must implement the
PropertyChangeListener interface. This interface defines the following method:
void propertyChange(PropertyChangeEvent pce)

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.

1.1 Session Beans


Session beans perform specific tasks for a client. They are plain remote objects meant for abstracting business logic. A
client invokes methods of the session bean to access an application, which is deployed on the EJB server. The session
bean performs business tasks inside the server on behalf of the client, hiding all the complexities from the client. A
session bean, as its name suggests, can be considered as an interactive session. A session bean is not shared. It can handle
a single client in the same way that an interactive session may have just one client. A session bean, like an interactive
session, is not also persistent. This means that its state is not saved to a database. When the client finishes, its session bean
is also terminated.
There are two types of session beans:1. Stateless session bean 2. Stateful session bean.

1.1.1 Stateless Session Beans


A stateless session bean does not keep the state between client requests. When a client sends a request for method
invocation, the EJB container assigns an instance of a stateless bean. During the method invocation, bean’s instance
variables may have a state, but that is valid only during the method invocation. When the client makes another request, the
same instance may not be assigned to the client, possibly due to the reason that it is already assigned to another client.
Since a stateless bean can be assigned to any client, it supports multiple clients. Therefore, to support the same number of
clients, a lesser number of stateless session beans is required than stateful session beans. Session beans are useful for
applications that have a large number of clients.

1.1.2 Stateful Session Beans


The state of a bean consists of values of its instance variable. Unlike stateless session beans, stateful session beans
maintain their states. It means that a client sees the same state of the bean when it interacts with the stateful session bean
through multiple method invocation. This is accomplished by assigning the same session bean to the client across multiple
requests.
The stateful session bean loses its state when a client terminates. When the client terminates, the state is no longer
necessary.

1.2 Entity Beans

 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

 The parts of a bean:


o Remote interface
o Primary key (PK)
o Home interface
o Bean class

1.3 Message Driven Beans


A message driven bean is a type of enterprise bean which is invoked by EJB container when it receives a message from
queue or topic. Message driven bean is a stateless bean and is used to do task asynchronously.

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 1. Create table in database (Refer to EJB-Persistence chapter).

 Step 2. Create Entity class corresponding to table (Refer to EJB-Persistence chapter).

 Step 3. Create DataSource and Persistence Unit (Refer to EJB-Persistence chapter).

 Step 4. Create a stateless ejb having EntityManager instance (Refer toEJB-Persistence chapter).

 Step 5. Update stateless ejb.Add methods to add records and get records from database via entity manager (Refer
to EJB-Persistencechapter).

 Step 6. Create a Queue named BookQueue in JBoss defaultapplication directory.


 Step 7. A console based application client will send message to this queue.

 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.

26.12 INTRODUCTION TO STRUTS FRAMEWORK


Struts is an application framework for developing Java EE web applications. This is an open source framework and was
originally developed by Craig McClanahan and donated to Apache. Fundamentally, it uses and extends Java servlet API
and supports Model–View–Controller (MVC) architecture. It allows us to create flexible, extensible, and maintainable
large web applications based on standard technologies, such as Java servlets, JSP, JavaBeans, resource bundles and XML.
26.12.1 Basic Idea (struts architecture)
In a Java EE-based web application, a client usually submits data to the server using the HTML form. These data are then
handed over to a servlet or a Java Server Page, which processes them, typically interacts with the database, and finally
processes the HTML output that is sent to the client. Since servlet as well as JSP technologies mix application logic with
the presentation, they are inadequate for large web projects.
The primary task of struts is to separate application logic that interacts with the database, called model from HTML pages
that are sent to the client, called view and instance that passes information between model and view, called controller. For
this purpose, struts provide a controller as a servlet, called ActionServlet, and allows the writing of templates for the
presentation (view), typically in terms of JSP. This special servlet acts as a switchboard to route requests from clients to
the appropriate server page. This simple idea makes web applications much easier to design, develop, and maintain.
 Figure 26.10 describes the struts framework.

Execution flow of struts

1. User sends a request for the action


2. Container maps the request in the web.xml file and gets the class name of controller.
3. Container invokes the controller (StrutsPrepareAndExecuteFilter or FilterDispatcher). Since struts2.1, it is
StrutsPrepareAndExecuteFilter. Before 2.1 it was FilterDispatcher.
4. Controller gets the information for the action from the ActionMapper
5. Controller invokes the ActionProxy
6. ActionProxy gets the information of action and interceptor stack from the configuration manager which gets the
information from the struts.xml file.
7. ActionProxy forwards the request to the ActionInvocation
8. ActionInvocation invokes each interceptors and action
9. A result is generated
10. The result is sent back to the ActionInvocation
11. A HttpServletResponse is generated
12. Response is sent to the user
Example program for struts
Struts 2 Hello World Program

Let us see the Hello World program of struts 2, files required..

 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

<%@ taglib prefix="s" uri="/struts-tags" %>


<html>
<body>
 
<s:form action="verify">
 
<s:textfield name="uname" label="Enter Username" /><br>
<s:submit value="Click" align="center" />
 
</s:form>
</body>
</html>

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

You might also like