Unit - 1 CS-25 - Advance Java Programming (J2ee) : Two-Tier Architecture
Unit - 1 CS-25 - Advance Java Programming (J2ee) : Two-Tier Architecture
(J2ee)
Introduction to J2EE :
Today, more and more developers want to write distributed transactional applications for the
enterprise and thereby leverage the speed, security, and reliability of server-side technology. If
you are already working in this area, you know that in the fast-moving and demanding world of
e-commerce and information technology, enterprise applications must be designed, built, and
produced for less money, with greater speed, and with fewer resources than ever before.
To reduce costs and fast-track application design and development, the Java™ 2 Platform,
Enterprise Edition (J2EE™) provides a component-based approach to the design, development,
assembly, and deployment of enterprise applications. The J2EE platform offers a multitier
distributed application model, reusable components, a unified security model, flexible
transaction control, and Web services support through integrated data interchange on Extensible
Markup Language (XML)-based open standards.
Two-Tier Architecture
1
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
2
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
Three-Tier Architecture
- To address the issues of the two-tier architecture, the application logic will be placed in its
own tier.
- Thus applications can be portioned into three tiers.
- The first tier is referred to as the presentation layer, and consists of the application GUI.
- The middle tier, or the business layer, consists of the business logic to retrieve data for the
user requests.
- The back-end tier, or data layer, consists of the data needed by the application.
- Figure illustrates the three-tier architecture.
Note :- 1
- The three-tier architecture is the basis for J2EE applications.
- In which EJBs provide a mechanism to build application logic.
- While JSPs and servlets abstract the presentation layer and allow interaction with the business
layer.
- One important feature of the three-tier architecture is sharing system resources by all clients.
- Which results in :
o highly efficient,
o scalable (capable of being easily expanded or upgraded on demand a scalable computer
network),
o secure, and
o reliable applications.
3
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
Multitier J2EE Architecture
`- Java EE provides an environment for development and deployment of web-based enterprise
applications using multi-tier architecture, as signified below:
Above diagram demonstrates J2EE multi-tier architecture that surround several J2EE containers
each including its own J2EE components. Here is an overview about the different tiers of J2EE
architecture:
Client Tier – Components of Client Tier will run in the client devices / containers. Client
Tier components are standalone java applications, static and dynamic HTML pages, and
applets.
Middle Tier
o Web Tier – The web tier components namely JSP’s and Servlets execute with the
help of J2EE web server in a web container.
o Business Tier – Enterprise Java Beans (EJB) are the business tier components
that are executed within the EJB container using J2EE Application Server.
EIS Tier – In the EIS (enterprise information system) tier, the application related data are
stored in a database. EIS tier may also include ERP’s or legacy systems that can be
accessed via an API representing Java EE Connector Architecture.
4
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
At the client tier, J2EE supports pure HTML, as well as Java applets or applications. It
relies on Java Server Pages and servlet code to create HTML or other formatted data for
the client.
Enterprise JavaBeans (EJBs) provide another layer where the platform's logic is stored.
An EJB server provides functions such as threading, concurrency, security and memory
management. These services are transparent to the author.
Java Database Connectivity (JDBC), which is the Java equivalent to ODBC, is the
standard interface for Java databases.
Introduction to J2EE APIs (application program interface) (Servlet, JSP, EJB, JMS,
JavaMail, JSF, JNDI)
Servlet technology is used to create web application (resides at server side and generates
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was popular as a server-side programming
language. But there was many disadvantages of this technology. We have discussed these
disadvantages below.
Disadvantages of CGI
5
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
2. For each request, it starts a process and Web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantage of Servlet
1. Better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so we don't need to worry about memory leak,
garbage collection etc.
4. Secure: because it uses java language
JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic content.
This helps developers insert java code in HTML pages by making use of special JSP tags, most
of which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a
user interface for a Java web application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP actions and commands.
Using JSP, you can collect input from users through Webpage forms, present records from a
database or another source, and create Webpages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database or
registering user preferences, accessing JavaBeans components, passing control between pages,
and sharing information between requests, pages etc.
EJB stands for Enterprise Java Beans. EJB is an essential part of a J2EE platform. J2EE
platform has component based architecture to provide multi-tiered, distributed and highly
transactional features to enterprise level applications.
EJB provides an architecture to develop and deploy component based enterprise applications
considering robustness, high scalability, and high performance. An EJB application can be
deployed on any of the application server compliant with the J2EE 1.3 standard specification.
6
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
there are three kinds of enterprise beans: session beans, entity beans, and message-driven beans.
Enterprise beans often interact with databases.
The Java Message Service (JMS) API is a messaging standard that allows J2EE application
components to create, send, receive, and read messages. It enables distributed communication
that is loosely coupled, reliable, and asynchronous. JMS is for high-performance, reliable
application-to-application messaging. For eg. you doing a banking transaction thru a ATM
JavaMail API
The JavaMail is an API that is used to compose, write and read electronic messages (emails).
The JavaMail API provides protocol-independent and plateform-independent framework for
sending and receiving mails.The javax.mail and javax.mail.activation packages contains the
core classes of JavaMail API. JavaMail is for writing Java applications that send and receive e-
mail.
JSF
JavaServer Faces (JSF) is a MVC (Model View Controller) web framework that simplifies the construction
of User Interfaces (UI) for server-based applications using reusable UI components in a page.
The JNDI provides naming and directory functionality. It provides applications with methods for
performing standard directory operations, such as associating attributes with objects and
searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve
any type of named Java object.
J2EE Containers
Normally, thin-client multitiered applications are hard to write because they involve many lines
of intricate code to handle transaction and state management, multithreading, resource pooling,
and other complex low-level details. The component-based and platform-independent J2EE
architecture makes J2EE applications easy to write because business logic is organized into
reusable components.In addition, the J2EE server provides underlying services in the form of a
container for every component type. Because you do not have to develop these services yourself,
you are free to concentrate on solving the business problem at hand.
Container Services
Containers are the interface between a component and the low-level platform-specific
functionality that supports the component. Before a web component ,enterprise bean, or
7
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
application client component can be executed, it must be assembled into a J2EE module and
deployed into its container. The assembly process involves specifying container settings for each
component in the J2EE application and for the J2EE application itself. Container settings
customize the underlying support provided by the J2EE server, including services such as
security, transaction management, Java Naming and Directory
J2EE CONTAINERS
Interface™ (JNDI) lookups, and remote connectivity. Here are some of the high-lights:
• The J2EE security model lets you configure a web component or enterprise bean so that system
resources are accessed only by authorized users.
• The J2EE transaction model lets you specify relationships among methods that make up a
single transaction so that all methods in one transaction are treated as a single unit.
• JNDI lookup services provide a unified interface to multiple naming and directory services in
the enterprise so that application components can access naming and directory services.
• The J2EE remote connectivity model manages low-level communications between clients and
enterprise beans. After an enterprise bean is created, a client invokes methods on it as if it were
in the same virtual machine. Because the J2EE architecture provides configurable services,
application components within the same J2EE application can behave differently based on where
they are deployed. For example, an enterprise bean can have security settings that allow it a
certain level of access to database data in one production environment and another level of
database access in another production environment. The container also manages nonconfigurable
services such as enterprise bean and servlet life cycles, database connection resource pooling,
data persistence, and access to the J2EE platform APIs described in section J2EE 1.4
APIs. Although data persistence is a non configurable service, the J2EE architecture lets you
override container-managed persistence by including the appropriate code in your enterprise
bean implementation when you want more control than the default container-managed
persistence provides. For example, you might use bean-managed persistence to implement your
own finder (search) methods or to create a customized database cache.
J2EE Containers
Normally, thin-client multitiered applications are hard to write because they involve many lines
of intricate code to handle transaction and state management, multithreading, resource pooling,
and other complex low-level details. The component-based and platform-independent J2EE
architecture makes J2EE applications easy to write because business logic is organized into
reusable components. In addition, the J2EE server provides underlying services in the form of a
container for every component type. Because you do not have to develop these services yourself,
you are free to concentrate on solving the business problem at hand.
Container Services
Containers are the interface between a component and the low-level platform- specific
functionality that supports the component. Before a web component, enterprise bean, or
8
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
application client component can be executed, it must be assembled into a J2EE module and
deployed into its container .The assembly process involves specifying container settings for each
component in the J2EE application and for the J2EE application itself. Container settings
customize the underlying support provided by the J2EE server, including services such as
security, transaction management, Java Naming and Directory
The application server which control and provide services through an interface is known as a
container. J2EE container helps in deployment and execution of J2EE component. In J2EE
specification we can classify container types as five. Three of these are server-side containers:
9
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
Rather, Tomcat is more of a web server and web container. This does not mean it lacks
functionality, mind you. An open-source implementation of the Java Servlet, JavaServer
Pages, Java Expression Language, and Java WebSocket Technologies, it is intended as a
platform for powering large-scale, mission-critical web applications. It is used by major
enterprises across several industries , including development, finance, healthcare,
government, ecommerce, retail, and marketing.
1. <form action="process.jsp">
2. Enter Name:<input type="text" name="name" /><br/><br/>
3. <input type="submit" value="go"/>
4. </form>
Introduction of JDBC
10
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of
executables, such as −
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs).
11
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in
general, JDBC Architecture consists of two layers −
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −
12
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
Common JDBC Components
JDBC API The JDBC API gives access of programming data from the Java. To use this,
applications can execute SQL statements and retrieve results and updation to the
database. The JDBC API is part of the Java platform, it includes the Java Standard
Edition
JDBC DataType:
The following table summarizes the default JDBC data type that the Java data type is
converted to, when you call the setXXX() method of the PreparedStatement or
CallableStatement object or the ResultSet.updateXXX() method.
13
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
INTEGER Int setInt updateInt
BIGINT Long setLong updateLong
REAL Float setFloat updateFloat
FLOAT Float setFloat updateFloat
DOUBLE Double setDouble updateDouble
VARBINARY byte[ ] setBytes updateBytes
BINARY byte[ ] setBytes updateBytes
DATE java.sql.Date setDate updateDate
TIME java.sql.Time setTime updateTime
TIMESTAMP java.sql.Timestamp setTimestamp updateTimestamp
CLOB java.sql.Clob setClob updateClob
BLOB java.sql.Blob setBlob updateBlob
ARRAY java.sql.Array setARRAY updateARRAY
REF java.sql.Ref SetRef updateRef
STRUCT java.sql.Struct SetStruct updateStruct
JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The
ResultSet object now has updateBLOB(), updateCLOB(), updateArray(), and updateRef()
methods that enable you to directly manipulate the respective data on the server.
The setXXX() and updateXXX() methods enable you to convert specific Java types to
specific JDBC data types. The methods, setObject() and updateObject(), enable you to
map almost any Java type to a JDBC data type.
ResultSet object provides corresponding getXXX() method for each data type to retrieve
column value. Each method can be used with column name or by its ordinal position.
In general, to process any SQL statement with JDBC, you follow these steps:
1. Establishing a connection.
2. Create a statement.
3. Execute the query.
4. Process the ResultSet object.
5. Close the connection.
Exception handling allows you to handle exceptional conditions such as program-defined errors
in a controlled fashion.
14
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
When an exception condition occurs, an exception is thrown. The term thrown means that
current program execution stops, and the control is redirected to the nearest applicable catch
clause. If no applicable catch clause exists, then the program's execution ends.
JDBC Exception handling is very similar to the Java Exception handling but for JDBC, the most
common exception you'll deal with is java.sql.SQLException.
SQLException Methods
An SQLException can occur both in the driver and the database. When such an exception occurs,
an object of type SQLException will be passed to the catch clause.
The passed SQLException object has the following methods available for retrieving additional
information about the exception −
Method Description
By utilizing the information available from the Exception object, you can catch an exception and
continue your program appropriately. Here is the general form of a try block −
try {
// Your risky code goes between these curly braces!!!
15
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}
Example
Study the following example code to understand the usage of try....catch...finally blocks.
// Database credentials
static final String USER = "username";
static final String PASS = "password";
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result if there is no problem, otherwise
the corresponding error would be caught and error message would be displayed −
C:\>java JDBCExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
17
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
Try the above example by passing wrong database name or wrong username or password and
check the result.
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
For example, using JDBC drivers enable you to open database connections and to interact with it
by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK, contains various classes with their behaviours defined
and their actual implementaions are done in third-party drivers. Third party vendors implements
the java.sql.Driver interface in their database driver.
JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which is explained below −
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.
When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or
when no other alternative is available. This driver software is built-in with JDK so no need
to install separately.
It is a database independent driver.
18
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique
to the database. These drivers are typically provided by the database vendors and used in the
same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each
client machine.
If we change the Database, we have to change the native API, as it is specific to a database and
they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead. The Vendor client library needs to be installed on client
machine.
19
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases. Switch facility to switch over
from one database to another database.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's configuration
in order to effectively use this driver type. Your application server might use a Type 1, 2, or 4
driver to communicate with the database, understanding the nuances will prove helpful.
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself. This kind of driver is extremely flexible, you don't need
to install special software on the client or server. Further, these drivers can be downloaded
dynamically.
20
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.
The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.
Before you can use a Statement object to execute a SQL statement, you need to create one using
the Connection object's createStatement( ) method, as in the following example −
21
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
. . .
}
finally {
. . .
}
Once you've created a Statement object, you can then use it to execute an SQL statement with
one of its three execute methods.
boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can
be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements
or when you need to use truly dynamic SQL.
int executeUpdate (String SQL): Returns the number of rows affected by the execution
of the SQL statement. Use this method to execute SQL statements for which you expect
to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE
statement.
ResultSet executeQuery (String SQL): Returns a ResultSet object. Use this method
when you expect to get a result set, as you would with a SELECT statement.
Just as you close a Connection object to save database resources, for the same reason you should
also close the Statement object.
A simple call to the close() method will do the job. If you close the Connection object first, it
will close the Statement object as well. However, you should always explicitly close the
Statement object to ensure proper cleanup.
PreparedStatement
22
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
1. String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
1. public PreparedStatement prepareStatement(String query)throws SQLException{}
Method Description
23
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
CallableStatement
We can have business logic on the database by the use of stored procedures and functions that
will make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may create a
function that receives date as the input and returns age of the employee as the output.
The differences between stored procedures and functions are given below:
must not have the return type. must have the return type.
We can call functions from the procedure. Procedure cannot be called from function.
Procedure supports input and output parameters. Function supports only input parameter.
Exception handling using try/catch block can be Exception handling using try/catch can't be used
used in stored procedures. in user defined functions.
1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");
1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");
24
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
This package include classes and interface to perform almost all JDBC operation such as creating
and executing SQL Queries.
classes/interface Description
java.sql.BLOB Provide support for BLOB(Binary Large Object) SQL type.
java.sql.Connection creates a connection with specific database
java.sql.CallableStatement Execute stored procedures
java.sql.CLOB Provide support for CLOB(Character Large Object) SQL type.
java.sql.Date Provide support for Date SQL type.
java.sql.Driver create an instance of a driver with the DriverManager.
java.sql.DriverManager This class manages database drivers.
java.sql.PreparedStatement Used to create and execute parameterized query.
It is an interface that provide methods to access the result row-by-
java.sql.ResultSet
row.
java.sql.Savepoint Specify savepoint in transaction.
java.sql.SQLException Encapsulate all JDBC related exception.
java.sql.Statement This interface is used to execute SQL statements.
DriverManager: This class loads JDBC drivers in memory. It is a “factory” class and can
also be used to create java.sql.Connection objects to data sources(such as Oracle,
MySQL, etc.).
Connection: This interface represents a connection with a data source. The Connection
object is used for creating Statement, PreparedStatement, and CallableStatement objects.
DatabaseMetaData: This interface provides detailed information about the database as a
whole. The Connection object is used for creating Database MetaData objects.
Statement: This interface represents a static SQL statement. It can be used to retrieve
ResultSet objects.
PreparedStatement: This interface extends Statement and represents a precompiled SQL
statement. It can be used to retrieve ResultSet objects.
CallableStatement: This interface represents a database stored procedure. It can execute
stored procedures in a database server.
ResultSet: This interface represents a database result set generated by using SQL’s
SELECT statement. Statement, PreparedStatement, CallableStatement, and other JDBC
objects can create ResultSet objects.
ResultSetMetaData: This interface provides information about the types and properties of
the columns in a ResultSet object.
SQLException: This class is an exception class that provides information on a database
access error or other errors.
25
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
Java ResultSetMetaData
The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column type
etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the
ResultSet object.
public String getColumnName(int index)throws it returns the column name of the specified
SQLException column index.
public String getColumnTypeName(int index)throws it returns the column type name for the
SQLException specified index.
public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.
DatabaseMetaData interface provides methods to get meta data of a database such as database
product name, database product version, driver name, name of total number of tables, name of
total number of views etc.
26
Unit – 1 CS-25 - Advance Java Programming
(J2ee)
27