0% found this document useful (0 votes)
20 views18 pages

Unit 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views18 pages

Unit 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIT -4

JAVA BEANS

Syllabus: -

Introduction to Java Beans

 Java Beans is a software component designed to be reusable in various environments.


 A bean is a reusable software component that can be manipulated visually by a builder tool.
 There is no restriction on the capability of a Bean.
 JB may perform a simple function, such as checking the spelling of a document, or a complex function, such
as forecasting the performance of a stock portfolio.
 It may be visible to an end user.
E.g. a button on a graphical user interface designed to work autonomously on a user’s workstation.
 The JavaBeans architecture allows the application developer to quickly and easily construct a full-featured
Java program simply by connecting one or more prewritten beans in a visual bean manipulation program
called a beanbox. Beans may also be assembled into an application by hand coding.
 Each bean exports a well-defined list of properties, events, and methods that may be accessed by other beans.
 Beans communicate with the "outside world" through events and public methods.

Advantages of Java Beans (Bean vs Java Library): -

 A bean obtains all the benefits of Java’s “write once, run-anywhere” paradigm.
 A bean's properties, events, and methods are exposed to an application builder tool and can be controlled.
 A bean may be designed to operate correctly in different locales, which makes it useful in global markets.
 Auxiliary software can be provided to help a person configure a bean.
 The configuration settings of a bean can be saved in persistent storage and restored later.
 A bean may register to receive events from other objects and generate events sent to other objects.

Features of a Bean: -

 Support for introspection: allows a builder tool to analyze how a bean works.
 Support for customization: allows a user to alter the appearance and behavior of a bean.
 Support for events: allows beans to fire events and informs builder tools about both the events they can fire
and the events they can handle.
 Support for properties allowing beans to be manipulated programatically, as well as to support the
customization mentioned above.
 Support for persistence: allow beans customized in an application builder to save and restore their state.

Creating a JavaBean

Steps: -

(i) Create a program and save it with .java extension


(ii) Compile the source file
(iii) Create a Manifest file and save it with .mft extension
(iv) Generate a JAR file.
(v) Start BDK
(vi) Load the Bean into the Toolbox and Drop a Bean instance into the BeanBox.
(vii) Inspecting the Bean’s properties, methods, and events.

Example: -
import java.awt.*;
import java.io.Serializable;
public class SimpleBean extends Canvas implements Serializable {
public SimpleBean() {
setSize(50,30);
setBackground(Color.blue);
}
}

What is BDK?

The JavaBeans Development Kit (BDK) is a set of technologies (BDK 1.1, J2SE SDK, and Java Plug-in
software) to support the development of JavaBeans components and to act as a standard reference base for both
component developers and tool vendors. The BDK provides a reference Bean container, the "BeanBox," and a
variety of reusable example source code for use by both tool and beans developers.

What is a JAR file in Java?

JAR stands for the Java Archive. This file format is used to distribute a set of java classes. This file helps you to
reduce the file size

What is a Manifest File?

A developer must provide a manifest file to indicate which of the Components in the JAR file are Java Beans. A
Manifest file may refer to several class files. If a class file is a Java Bean, the line “java-Bean: True” must
immediately follow its entry.

Use notepad to create a manifest file that contains the following text: -
Name: SimpleBean.class
Java_bean:True

BDK Introspection

Introspection is the process of analyzing a bean to determine its capabilities. It is an important feature of Java
Bean API because it allows an application builder tool to present information about a component to a software
designer. Without introspection, the Java beans technology could not operate. One way to expose Bean's
properties, events, and methods to the application builder tool is by using simple naming conventions.

Java Bean Properties

 A Java bean property is a named attribute that can affect its behavior or appearance.
 It includes color, label, font, font size, and display size.
 A JavaBean property may be read, write, read only, or write only.
 These are accessed through two methods in the JavaBean's implementation class: –

S.No. Method Description

getPropertyName(
For example, if property name is firstName, your method
)
1 name would be getFirstName() to read that property.
This method is called accessor.

setPropertyName() For example, if property name is firstName, your method


2 name would be setFirstName() to write that property.
This method is called mutator.

Types of Properties: -
 Simple - Property with a single value whose changes are independent of changes in any other property.
 Indexed - Property that supports a range of values instead of a single value.
 Bound - Property for which a change to the property results in a notification sent to some other bean.
 Constrained - Property for which a change to the property results in validation by another bean. The other
bean may reject the change if it is not appropriate.

Types of Beans

1. Control Bean (User Interface Bean)


− used to create GUI components that can be plugged into any application.
− Can be created by extending one of the swing component classes.
− Example- animated button, animation applet, etc.
2. Container Bean (Visible Bean)
− Used to hold other Java beans
− Can be created by extending one of the swing container class
− Example: Explorer window created by JTree, spreadsheet application, etc.
3. Invisible Bean
− used to create components that perform a specific task in the background of an application.
− During the bean's execution, these components are invisible to the end user.
− Example: Spelling checker, data access object, etc.

Java Beans API: -

Interface Description

Methods present in this interface are used to initialize Beans


AppletInitializer
that are also applets.
This interface allows a designer to specify information about a
BeanInfo
Bean's properties, events, and methods.
This interface allows a designer to provide a graphical user
Customizer
interface through which a Bean may be configured.
Methods in this interface determine if a Bean is executing in
DesignMode
design mode.
A method in this interface is invoked when a bound property is
PropertyChangeListener
changed.
Methods in this interface allow a bean to execute in
Visibility
environments where a GUI is unavailable.

Java Beans Class: -

Class Description

BeanDescriptor This class provides information about a Bean.


Beans This class is used to obtain information about a Bean
This event is generated when bound or constrained properties
PropertyChangeEvent are changed.
PropertyDescriptor Instances of this class describe a property of a Bean
An exception of this type is generated if a problem occurs when
IntrospectionException analyzing a bean.
Enterprise Java Beans (EJBs): -

 collection of Java classes and an XML file bundled into a single unit.
 Specifies certain rules and specific callback methods (with J2EE Environment) to be followed by Java
classes.
 standard server-side component model for CTM.
 The EJB architecture is a component architecture for developing and deploying component-based distributed
business applications.

EJB Client-Server System Architecture

 EJB component: A reusable, application-independent piece of code. It is a Java class written to implement
business logic.
 EJB Container: Represents an environment in which the component operates. An EJB component lives
inside an EJB container.
 EJBObject: Method by which the client programs execute remote EJB components.
 EJBServer: Application server that is EJB compliant.

Advantages of Enterprise Java Beans: -

 EJB repository yields system-level services to the enterprise. Rather than the bean developer, the EJB
repository is responsible for system-level services such as transaction
 Management and security authorization.
 Establishes roles for application development.
 Provides distributed transaction support.
 Are portable elements, the application assembler can build new applications from the beans that already
exist.
 Provides vendor-specific enhancements.

Disadvantages of Enterprise Java Beans: -

 Requires application server


 Requires only Java clients. For another language client, you need to go for a web service.
 Complex to understand and develop EJB applications.

Types of EJB: -

1. Entity Bean
− type of EJB that represents persistent data manipulated in a database.
− Does not contain business logic
For example, a business application might use a database to store business entity objects such as
accounts, customers, orders, etc.
− Entity beans are persistent, allow shared access, and have primary keys.
− Bean managed Persistence
− Container Managed Persistence
− Can be shared among multiple clients
− Each entity Bean has a unique object identifier called as Primary key
− A session bean is a client of Entity bean.
− Entity beans work within a transaction. EJB container provides transaction management
− Its interface is implemented by every entity enterprise bean class.
− It is of two types: -
i) Bean-Managed Persistence (BMP): Enables you to manage database queries and connectivity
issues. For this, you need to write code to establish connectivity and query database tables in the
bean class file.
ii) Container-Managed Persistence (CMP): Enables EJB container to manage database queries
and connectivity issues.

Methods of Entity Bean Interface: -

1. ejbCreate()
2. ejbPostCreate()
Entity Bean life cycle: -

2. Session Bean
− Encapsulates business logic
− can be invoked by local, remote, and web service clients.
− when a client or user requests a session bean, a separate instance of the bean is created and provided to
the caller.
− A client does not directly access an instance of the session bean. Instead, it accesses a session object
through the session beans' Home (Implement the Home interface) and Component (Implement the
Component interface) interfaces.
− A session bean is not persistent, i.e., data is stored temporarily, and data will be destroyed if some crash
occurs.
− Life is restricted by the life of the client session
− further classified into two types: -
i) Stateful:
− Represents that session EJB created to maintain a specific client's state between subsequent calls for
some maximum time.
− It is specific to a client.
− Maintains the state or some information of a client across multiple requests.
− Are mapped to a single client for that client's life.
ii) Stateless:
− Represents those session EJBs that have no regard for maintaining any state between subsequent calls
by the client.
− does not maintain the state of a client between multiple methods calls.
− Can be accessed by one client at a time.
− In case of concurrent access, EJB container routes each request to a different instance.
− Because stateless session beans support multiple clients, they can offer better scalability for
applications that require a large number of clients.

Life Cycle of a Stateless Session Bean: - Life Cycle of a Stateful Session Bean: -
3. Message-driven
− enterprise bean that allows J2EE (Java to Enterprise Edition) applications to process messages
asynchronously.
− Invoked by EJB container when it receives a message from the queue.
− Used for communication purposes only.
− acts as a JMS (Java Message Service) message listener, which is similar to an event listener
except that it receives messages instead of events.
− The messages may be sent by any J2EE component, such as an application client, another
enterprise bean, a web component, or a JMS application or system that does not use J2EE
technology.
− Message-driven beans currently process only JMS messages, but in the future, they may be
used to process other kinds of messages.

When to use Enterprise Java Beans?

1. When an application needs Remote Access, i.e., when it is distributed.


2. When an application needs to be scalable. EJB applications support load balancing, clustering, and fail-
over.
3. When an application needs encapsulated business logic. EJB application is differentiated from the
demonstration and persistent layer.
Java Database Connectivity (JDBC)

 Java API used to connect and execute query to database.


 Defines how a client may access a database.
 Is a part of Java Standard Edition from Oracle corporation.

Why Use JDBC?

Before JDBC, the ODBC API was used to connect to and execute queries to the database. However, ODBC
drivers were platform-dependent and unsecured, so JDBC was used.

Functions of JDBC: -

 To establish a connection with the database.


 To send SQL statements
 To process results

JDBC Basics
 JDBC program starts out by loading a JDBC driver class (in this case, Sun's JDBC-ODBC bridge).
 It uses the driver to create a database connection, represented by a Connection object.
 With the database connection, it creates a Statement object to represent a SQL statement.
 Executing an SQL statement produces a ResultSet containing a query's results.
 The program displays the results and then cleans up the resources it has used.
 If an error occurs, a SQLException is thrown, so our program traps that exception and displays some of the
information it encapsulates.
 Before using a driver, it must be registered with the JDBC DriverManager. This is typically done by loading
the driver class using the Class.forName( ) method: -
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("com.oracle.jdbc.OracleDriver");
}
catch (ClassNotFoundException e) {
/* Handle Exception */
}
 JDBC drivers are available for most database platforms from several vendors.

JDBC Drivers: -

 Used to translate API calls into operation for specific data sources.
 Enables Java applications to interact with the database.
 These are client-side adapters that convert Java program requests to a protocol that DBMS can understand.

Fig. JDBC drivers

 There are four categories of drivers in JDBC: -

Type 1: JDBC-ODBC Bridge Drivers


− Type 1 drivers use a bridge technology to connect a Java client to an ODBC database system.
− They require some non-Java software to be installed on the machine running your code and are implemented
using native code.
Type 2: Native API Partly Drivers
− Type 2 drivers use a native code library to access a database, wrapping a thin layer of Java around the native
library.
− These are implemented with native code, so they may perform better than all Java drivers, but they also add
− an element of risk as a defect in the native code can crash the Java virtual machine.

Type 3: Net Protocol All Java Drivers


− Type 3 drivers define a generic network protocol that interfaces with custom middleware.
− The middleware component might use any other type of driver to provide access to the actual database.
− These drivers are especially useful for applet deployment since the actual JDBC classes can be written entirely
in Java and downloaded by the client on the fly.
Type 4: Native Protocol all Java Drivers
− Type 4 drivers are written entirely in Java.
− They understand database-specific networking protocols and can access the database directly without additional
software.
− These drivers are also well-suited for applet programming, provided the Java security manager allows TCP/IP
connections to the database server.

JDBC URLs
 A JDBC driver uses a JDBC URL to identify and connect to a particular database.
 These URLs are generally of the form: -
jdbc:driver:databasename
 The Oracle JDBC-Thin driver uses a URL of the form: jdbc:oracle:thin:@site:port:database

Connecting to the Database


 The java.sql.Connection object forms the basis of all JDBC data-handling code.
 An application can maintain multiple connections up to the limits imposed by the database system itself.
 The DriverManager.getConnection( ) method creates a connection as: -
Connection con = DriverManager.getConnection("url", "user", "password");
JDBC 2 Tier Model

 The JDBC API is at the top layer. It communicates with the


JDBC manager driver API and sends data to various SQL
statements.
 As with any other layer, the manager communicates with
various third-party drivers that connect to the database and
return the information from the query or perform the actions
specified by the query.

JDBC 3 Tier Model

JDBC Architecture or JAVASoft Framework


JAVASoft provides 3 JDBC product components as part of the JDK. These are: -

1. JDBC Driver Manager: -


 Backbone of JDBC
 Primary function is to connect Java applications to correct JDBC drivers and subsequently get out of the way.
 It uses DriverManager class.

2. JDBC Driver Test Suite: -


 Provides some confidence so that JDBC drivers will run your program
 Used to test an operation being performed by JDBC drivers.

3. JDBC-ODBC Bridge: -
 Allows ODBC drivers to be used as JDBC drivers.
 It was implemented as a way to get JDBC off the ground quickly and, as a result, provide access to some of the
less popular DBMS.
If JDBC drivers are not implemented for them, it connects database drivers to the database.

Common JDBC Components: -


JDBC API provides the following interfaces and components: -
1. Driver manager: This class manages a list of database drivers.
2. Driver: It is an interface that handles communication with a database server.
3. Connection: This interface has all the methods for contacting a database. All communication with a
database is done through communication objects only.
4. Statements: Objects created from this interface submit the SQL statements to the database.
5. ResultSet: It is an object that holds the data retrieved from a database after an SQL query is executed using
a statement object. It acts as an iterator which allows you to move through data.
6. SQLException: It is a class that handles any error occurring in a database application

You might also like