Jee 1
Jee 1
The Java 2 platform, Enterprise Edition reduces the cost and complexity of developing multi-
tier services.
It can be rapidly deployed and easily enhanced as the enterprise responds to competitive
pressures.
J2EE is an open standard which is provided by Sun Microsystems for application which run
on servers.
It includes J2SE+ most of the other java technologies including JavaMail, Activation,
Servlets, JSF, JMS, EJB and others. Most of the API is component- oriented. They are used
to provide interfaces for business oriented components for enterprise and distributed internet
applications.
Java has emerged as one of the most of the mature and commonly used programming
language for building enterprise software.
1. J2SE – stands for Java 2 Standard Edition and is normally used for Desktop
Applications
2. J2EE - stands for Java 2 Enterprise Edition for applications which run on server. For
example: Web Site/Web Applications.
3. J2ME - stands for Java 2 Micro Edition for applications which run on small scale devices
like cell phones .for example: games
The 2-Tier architecture is generally data driven with application existing entirely on the local
machine and the Database deployed at a specific and secure location in the Organization.
§ Single-Tier Architecture
§ 2 -Tier Architecture
§ 3-Tier Architecture
§ N-Tier Architecture
Simple Software application is written to run on a single computer such architecture is called
as Single tier architecture. Because all of the logical application services presentation, the
business rules and the data access layer exit in a single computing layer.
Such systems are relatively easy to manage and Data consistency is simple because the Data
is stored at only one single location. The only problem with such systems is it can not handle
multiple users and do not provide easy means of Sharing the Data across the Firm.
Advantages:
Single tier system is relatively easy to manage and data consistency is simple
because data is stored at only one place.
Disadvantages:
-> Now a day’s single location is not sufficient because of changing business needs.
-> We can not share the data in large amount
-> It can not handle multiple users.
2-Tier Architecture:
Application which is divided into two separate tiers namely Client machine and database Server
machine called as Two Tier Architecture. This is the traditional method of enterprise
development. It includes presentation and business logic. In a 2-Tier application the
processing load is given to the client while to the server simply controls the Traffic between
the application and the Data as shown in figure.
Thin Client:
With 2 tier architecture, if the presentation manager resides only with client tier then the
client is called as thin client. other presentation logic, application logic, business logic,
database logic and database manager resides with the server side.
Request
Server Tier
Client Tier
Presentation Presentation Logic
manager
Application Logic
Response Business Logic
Database Logic
Database Manager
Thick Client:
With 2 tier architecture,if the presentation manager, presentation logic, application logic
resides with the client side then the client is called as thick client other like business
logic,database logic and database manager resides with the server side.
Server Tier
Client Tier
Disadvantages:
- In case of limited resource pc, the performance would be suffered due to pc resources.
- It supports a lmited number of users.
- Each client requires its own connection and each connection requires CPU and
memory.
3 –Tier architecture:-
Application which is divided into 3 tier namely Client tier, middle tier, and database (Enterprise
Information System-EIS) tier is known as Three Tier Architecture. Logic physically separates
the business rules. Presentation layer and logic runs on Client machine, application and business
logic runs on J2EE server and database logic is there with database layer.
Thin Client:
With 3 tier architecture,if the presentation manager resides only with client tier then the client
is called as thin client, other presentation logic,application logic,business logic,database logic
and database manager resides with the EIS tier(databse).
Thick Client:
Advantages:
Disadvantages:
It increases the complexity because to develop the 3 tier application is more difficult than
developing a 2 tier application.
N-Tier Architecture:-
An application which is divided into more than 3 tier can be called as N Tier [Link]
N tier architecture it is not decided how many tiers can be there,it depends on computing and
network hardware on which application is deplolyed.
Basically it is divided into four layers: Application layer, Client tier, business tier (EJB) and
database tier (EIS).
Client Tier:
It consists of the user interface for user request and print the [Link] runs on client
machinme .It basically uses the browser or applet as client side application.
Web Tier:
It consists of JSP and Servlet dynamic webpages to handle HTTp specific request logons,
sessions, accesses the business services and finally constructs response and send back to the
client.
Business Tier:
It consists of the business logic for the J2EE application .For Example: EJB (Enterprise Java
BeanS) the benefit of having a centralized business tier is same business logic can support
different type of client like browser, WAP, other stand alone application.
EIS Tier:
It consists of the DBMS/RDBMS. It handles the users SQL request and generates appropriate
response base on queries. It is responsible for communicating with external recourses such as
legacy systems, ERP systems, messaging systems like MQSeries [Link] also stores all
persistent data in the database.
J2EE is based on N tier architecture application. J2EE makes easy to develop the
Enterprise application based on 2, 3, more application layers. Here it also proves that J2EE is
distributing computing framework and multi-tiered application.
· Advantages
· Disadvantages
It is having complex structure and difficult to setup and mainjtain all separated layers.
[1] J2EE
Runtime:-
The J2EE architecture provides the uniform mean of accessing platform level
services via its runtime environment such services includes messaging, security,
distributed transaction etc. The runtime infrastructure of it specifies the role and
interface for the application and the run time on which the application could be
deployed.
[2] J2EE
API:-
In the enterprise services, the distributed services require access.
These enterprise services include fraction processes, managing, multi-threading,
database
access to such services in its services APIs. The application programs in the J2EE can
access there APIs through the container.
The jdbc API lets you invoke SQL commands from the java programming
method. This API is useful to connect our java database application with any
relational database like ORACLE, MYSQL, MSACCESS. You can also use the jdbc
API from a servlet or JSP page to access your database directly. The jdbc API is divided
into two part.
This API provides easy way for building dynamic web application. The JSP
technology allows you to put the combines snippets(general UDF) of java programming
language code with static markup text based documents. A JSP page is a document
which contains two types of text.
- Static template data in text based format like html, xml.
- JSP elements that determine how the page constructs the dynamic contain.
(6) CONTAINERS:
· Introduction to J2EE Containers :-
Definition:
Containers are the central thing of J2EE architecture container are like the rooms in house,
people and thing exists in a room and interface with the infrastructure through well defined
interface.
Types of
Container
Tomcat
Servlet container
Tomcat implements the Java Servlet and the Java Server Pages (JSP) specifications from Sun
Microsystems, and provides a "pure Java" HTTP web server environment for Java code to
run.
Tomcat should not be confused with the Apache web server, which is a C implementation of
an HTTP web server; these two web servers are not bundled together.
Apache Tomcat includes tools for configuration and management, but can also be configured
by editing XML configuration files.
Tomcat 4.x
· Released 2001
· implements the Servlet 2.3 and JSP 1.2 specifications
· servlet container redesigned as Catalina
· JSP engine redesigned as Jasper
· Coyote HTTP connector
· Java Management Extensions (JMX), JSP and Struts-based administrations
Tomcat 5.x
· implements the Servlet 2.4 and JSP 2.0 specifications
· reduced garbage collection, improved performance and scalability
· native Windows and Unix wrappers for platform integration
· faster JSP parsing
Tomcat 6.x
· implements the Servlet 2.5 and JSP 2.1 specifications
· support for Unified Expression Language 2.1
· designed to run on Java SE 5.0 and later
· support for Comet through the CometProcessor interface
· is not packaged with an admin console as in past releases
CLASSPATH:
For Web applications, these components are usually performed in the same running
environment as its web server(s), and their main job is to support the construction of dynamic
pages.
Many application servers target much more than just Web page generation: they implement
services like clustering, fail-over, and load-balancing, so developers can focus on
implementing the business logic.
In the case of Java application servers, the server behaves like an extended virtual machine
for running applications, transparently handling connections to the database on one side, and,
often, connections to the Web client on the other.
Other uses of the term may refer to the services that a server makes available or the computer
hardware on which the services run.
Java Platform, Enterprise Edition or Java EE (was J2EE) defines the core set of API and
features of Java Application Servers.
Some Java Application Servers leave off many Java EE features like EJB and JMS
including Tomcat from Apache, and Jetty from Eclipse Foundation. Their focus is more on
Java Servlets and JavaServer Pages.
There are many open source Java application servers that support Java EE like
GlassFish server from
Oracle.
A Java Server Page (JSP) executes in a Web container. JSPs provide a way to create
HTML pages by embedding references to the server logic within the page. HTML coders and
Java programmers can work side by side by referencing each other's code from within their
own.
The application servers mentioned above mainly serve Web applications, and services via
RMI, EJB, JMS and SOAP. Some application servers target networks other than web-based
ones: Session Initiation Protocol servers, for instance, target telephony networks.
7.
JDBC
JDBC-ODBC:
ODBC
so sun Microsystems has accepted ODBC as Universal driver and java has developed
[Link] package for this interface.
To connect JDBC by using ODBC we have to develop one ODBC driver by using the
Control panel 32-bit ODBC program from your window application.
· ODBC can not be directly used with Java because it uses C interface. Calls from Java to
native C code have number of drawbacks in the security, implementation, robustness
and automatic portability of applications.
· ODBC make use of Pointer which has been totally removed from java.
· ODBC mixes simple advanced features together and has complex options for simple
[Link] JDBC is designed to keep things simple while allowing advanced capabilities
when required.
· ODBC requires manual installation of the ODBC driver manager and driver on all
client [Link] drivers are wriiten in Java and JDBC code is automatically
installable, secure and portable on all java platform.
· JDBC API is a natural Java interface and is built on ODBC JDNC retains some of the
basic features of ODBC like SQL call level interface.
JDBC API
JDBC API Is collection of methods, classes and interfaces that enable java applications to
communicate with database.
For this database should be installed on the computer and RDBMS should provide a driver.
JDBC classes and interfaces defined in the package [Link] constitute the JDBC API.
The relations between a java program, JDBC API, the JDBC driver and database is shown in
figure 3.1
Java
Program
JDBC API
JDBC
DRIVER
Database
Using JDBC API a java application can perform insert, delete, update and select rows
in a [Link] can also retrieve the data from the database and show itin a proper formate to
the user according to the SQL query.
In 2 ier architecture,java programs invoke the method of JDBC API and communicate
with the database server. so there is a direct interaction with the database server.
database. The JDBC architecture is divided into two parts: JDBC Driver
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 [Link]() method.
JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types.
SQL's use of NULL values and Java's use of null are different concepts. So how do
you handle SQL NULL values in Java?
(1) Avoid using getXXX( ) methods that return primitive data types.
(2) Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( )
method to test whether the wrapper class variable that received the value returned by
the getXXX( ) method should be set to null.
int id = [Link](1);
if( [Link]( ) ) {
id = 0;
}
3. How do you handle SQL NULL values in Java? Avoid using getXXX ( )
Advantages:
It allows access to any database
Disadvantages:
Advantages:
They offer better performance than JDBC-ODBC [Link] as the layers of
communication are less than type-1 driver and also use native API which is database specific.
Disadvantages:
- Native API must be installed in client system and hence type-2 driver cannot be
used for internet.
- It is not written in java which forms a portability issues
- If we change the database we have to change Native Api as it is specific to
database.
- Mostly outdated because it is not thread safe.
- It is not suitable for distributed application.
Advantages:
- It is sever based so no need for any vendor database library to be present on client
machine.
- This is fully written in java and hence portable, so it is suitable for web
application.
- It provides portability, performance, security and scalability.
- Net protocol can be designed to make client JDBC driver very small and fast to
load.
- It provides support for feature such as caching, load balancing, advanced system
administration such as logging and auditing.
- Very flexible and allows access to multiple database using one driver
- They are efficient among all drivers.
Disadvantages:
Type-3 driver requires database specific coding to be done on middle tier and it requires
additional server for that. Additionally traversing the recordset may take longer because the
data comes-through the backend server or backend database
Disadvantages
:
Different driver is needed for each database.
Advantages
:
In general, to process any SQL statement with JDBC, you follow these steps:
· Establishing a connection.
· Create a statement.
· Execute the query.
· Process the ResultSet object.
· Close the connection.
First, establish a connection with the data source you want to use. A data source can be a
DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver.
This connection is represented by a Connection object.
A Statement is an interface that represents a SQL statement. You execute Statement objects,
and they generate ResultSet objects, which is a table of data representing a database result
set. You need a Connection object to create a Statement object.
To execute a query, call an execute method from Statement such as the following:
· execute: Returns true if the first object that the query returns is a ResultSet object.
Use this method if the query could return one or more ResultSet objects. Retrieve
the ResultSet objects returned from the query by repeatedly
calling [Link].
· executeQuery: Returns one ResultSet object.
You access the data in a ResultSet object through a cursor. Note that this cursor is not a
database cursor. This cursor is a pointer that points to one row of data in the ResultSet
object. Initially, the cursor is positioned before the first row. You call various methods
defined in
the ResultSet object to move the cursor.
When you are finished using a Statement, call the method [Link] to immediately
release the resources it is using. When you call this method, its ResultSetobjects are
closed.
JDBC Exception handling is very similar to Java Excpetion handling but for JDBC, the
most common exception you'll deal with is [Link].
SQLException Methods:
A 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
getErrorCode( ) Gets the error number associated with the exception.
Gets the JDBC driver's error message for an error
getMessage( ) handled by the driver or gets the Oracle error number
and message for a database error.
Gets the XOPEN SQLstate string. For a JDBC driver
error, no useful information is returned from this
getSQLState( )
method. For a database error, the five-digit XOPEN
SQLstate code is returned. This method can return null.
getNextException( ) Gets the next Exception object in the exception chain.
Prints the current exception, or throwable, and its
printStackTrace( )
backtrace to a standard error stream.
printStackTrace(PrintStream Prints this throwable and its backtrace to the print stream
s) you specify.
printStackTrace(PrintWriter Prints this throwable and its backtrace to the print writer
w) you specify.
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!!!
}
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.
}
(1) createStatement()
It is used to create a Statement object for sending SQL Statements to the database.
For example:
Statement st;
St=[Link]
();
OR
St=[Link](ResultSet.TYPE_SCROLL_INSENSITIVE,[Link]
_
UPDATABLE);
(2) prepareStatement()
It is used to create a Prepared Statement object for sending SQL request to [Link]
statement with or without IN Parameters can be pre compiled /parameterized and stored in a
Prepared Statement [Link] is used to execute this statements multiple times. For example:
PreparedStatement pstm;
pstm=[Link] ();
(3) PrepareCall ()
It is used to create a Callable Statement object for calling stored procedure of database. Callable
Statement object provides method for setting up it’s IN and OUT parameters and methods for
executing call to stored procedure. For example:
CallableStatement cstm;
cstm=[Link] (“{ call insertdata (?,?)}”);
[Link](1,sid);
[Link](2,sname);
[Link]();
(4) Close ()
(5) Commit ()
It is used to save all the state of the database which are changed by transaction. It can be
written as follows:
[Link]();
(6) rollback ()
(7) SetAutoCommit ()
It is used to do auto commit all the transaction .if we set auto commit with connection
all SQL statements executed and committed together as individual [Link] has
Boolean type parameter .If we pass true then it enables the auto commit and if we
pass false it disables the auto commit.
(8) getAutoCommit ()
(9) isClosed()
Boolean
following syntax
(10) getMetaData()
For example: JDBC Drivers for MS ACCESS is different from ORACLE Driver. It
controls interface between application and JDBC Drivers.
It is used to fetch records from database using select [Link] passes SQL statement as a
[Link] returns single Resultset Objects that contains rows, columns and metadata that
represent data requested by [Link]:
Statement st;
St=[Link] ();
ResultSet rs=[Link] (“select * from tablename”);
Syntax:
Public static ResultSet executeQuery (String url) throws SQLException
Statement st;
St=[Link] ();
ResultSet rs=[Link] (“insert into tablename values (val1, val2…, valn”);
Syntax:
Public int executeUpdate (String url) throws SQLException
(3) execute ()
The execute () Statement is used when they returns Multiple result. It returns Boolean
indication that if it returns true it defines that next result is ResultSet object and if it returnd
false then it defines no of records updated or no more results.
Statement st;
St=[Link] ();
String sql=”create table tablename (fieldname type (size), fieldname
type(size))”;
[Link] (sql);
Syntax: Public Boolean execute (String url) throws SQLException
If you want to execute SQL statements many times Prepared Statement object reduces
execution time in comparision to other Statement object.
Main feature of it is SQL statements is given to Prepared Statement object when SQL
statements is [Link] advantage of Prepared Statement object is that in many of the cases
SQL statements is sent to database immediately,where it is compiled.
· setInt(int parameterindex,int x)
· setString(int parameterindex,int x)
· setChar(int parameterindex,int x)
· setFloat(int parameterindex,int x)
· setDouble(int parameterindex,int x)
· setLong(int parameterindex,int x)
· setShort(int parameterindex,int x)
· setDate(int parameterindex,int x)
· setByte(int parameterindex,int x)
· setBlob(int parameterindex,int x)
Execute methods:
(1) executeQuery ():
It is used to fetch records from database using select [Link] passes SQL statement as a
[Link] returns single Resultset Objects that contains rows, columns and metadata that
represent data requested by [Link]:
String sql=“select * from tablename where fieldname=? ”;
setString(1,”C01”);
PreparedStatement pst =[Link] ();;
ResultSet rs=[Link] ();
Syntax:
Public static ResultSet executeQuery throws SQLException
It is used to perform insert, update, and delete operation on record of [Link] returns
integer value indicating no. of records updated in [Link] passes SQL as a parameter.
Statement st = [Link] ();
Int n=[Link] (“insert into tablename values (val1,val2,…..,valn”);
Syntax:
Public int executeUpdate throws SQLException
(3) execute ()
It is used to execute SQL statements which returns multiple [Link] returns the Boolean
indicating that value if it returns true then it defines that next result is ResultSet obkect and if it
returns false then it defines that number of records updated or no more results is [Link] passes
any sql statements as parameter.
The callable statement uses three types of parameters when calling a stored procedure. These
The IN parameter contains any data that needs to be passed to the stored procedure and
whose value is assign using the setXxx ().
The OUT parameter contains the value return by the stored procedure if any OUT parameter
must be registered using the register OUT parameter () and then his later retrieve by J2EE
component by using getXxx ().
The INOUT parameter is a single parameter that is use for both that is to pass information to
stored procedure and to retrieve information from stored procedure.
In above program, the statement of try block creates a query that will call the stored
procedure last no. order which retrieve the most recently used order number.
Thestoredprocedurerequiresoneparameterthatisrepresentedby“?“.
The parameter is an OUT parameter that will contain last order no. following the execution
of stored procedure.
The registeroutParameter () requires two parameters. The first parameter is an integer that
represents no. of the parameter. Here one means, the first parameter of stored procedure and
second parameter is data type of value return by the stored procedure.
The execute() of callable statement will be useful to execute the query. After the stored
procedure is executed, getString() is called to return the value of specified parameter of
stored procedure.
(19) ResultSet :-
It is used to access the data of the table from database.
Resultset object stores the data of the table by executing the query.
It also maintains the cursor position for navigation of the [Link] can ove on first() ,
last() , previous() ,next() from the current row [Link] also fetch data from the table using
getXXX() method depends on columnType(getString(),getInt()etc.).It can fetch data either using
getXXX().Index number always starts with one.
There are six methods of ResultSet object that are used to position the virtual cursor. They
are first() , last() , previous() , next(),absolute() , relative() , and getRow().
-TYPE_SCROLL_INSENSITIVE: It defines that the cursor can scroll but can not be
modified or updated.
-TYPE_SCROLL_SENSITIVE: It defines that the cursor can scroll and also be modified
or updated.
-TYPE_FORWARD_ONLY: It defines that the cursor from the current row moves forward
only.
-CONCURE_READ_ONLY: It defines that cursor can scroll and also can be modified or
updated.
(1) getString() : It is used to fetch the string type of records from [Link] returns the String
object.
(2) getInt() : It is used to fetch the integer type of records from [Link] returns the String
object.
(3) getBoolean() : It is used to fetch the boolean type of records from [Link] returns either
true/false.
(4) getDouble() : It is used to fetch the decimal type of records from [Link] returns the
double value.
(5) getFloat() : It is used to fetch the float type of records from [Link] returns the String
object.
(6) getDate() : It is used to fetch the date type of records from table. (7)
getLong() : It is used to fetch the long type of records from table. (8)
getShort() : It is used to fetch the short type of records from table. (9)
getByte() : It is used to fetch the string type of records from table.
(10) getBlob() : It is used to fetch binary representing large object from table can be image
file,audio file,video file.
Metadata is about data (data about data). There are two types of metadata interface are available
(1) ResultsetMetadata and (2) Database Metadata. The DatabaseMetaData interface is used to
retrieve information about databases, tables, columns and indexes among other information
about the DBMS.
· ResultSetMataData:
This interface is used to obtain information about type and properties of the column in a
ResultSetMataData are used to store following information of Resultset object:
Method Description
getColumnCount() Returns the number of columns contained in the
ResultSet
getColumnName(int n) Returns the name of the column specified by the
column number
getColumnType(int n) Returns the data type of the column specified by the
column number.
isNullable(int column); Indicates the null ability of values in the designated
columns.
· Import JDBC Packages: Add import statements to your Java program to import
required classes in your Java code.
· Register JDBC Driver: This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.
· Database URL Formulation: This is to create a properly formatted address that points to
the database to which you wish to connect.
You need to do this registration only once in your program. You can register a driver in one
of two ways.
· getConnection(String url)
Here each form requires a database URL. A database URL is an address that points to your
database.
Formulating a database URL is where most of the problems associated with establishing a
connection occur.
Following table lists down popular JDBC driver names and database URL.
All the highlighted part in URL format is static and you need to change only remaining part
as per your database setup.
You should make a habit of always closing the connection with the close() method associated
with connection object.
To ensure that a connection is closed, you could provide a finally block in your code. A
finally block always executes, regardless if an exception occurs or not.
To close above opened connection you should call close() method as follows:
[Link]();
Explicitly closing a connection conserves DBMS resources, which will make your database
administrator happy.