You are on page 1of 38

MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

4.1 JAVA DATABASE PROGRAMMING

A database system consists of a database, the software that stores and manages data in the
database, and the application programs that present data and enable the user to interact with the
database system. Almost all the current applications that we use require a database management
system at backend inorder to handle the data associated with the application. When you purchase a
database system, such as MySQL, Oracle, IBM, Microsoft, or Sybase, from a software vendor, you
actually purchase the software comprising a database management system (DBMS).All Data Base
systems make use of the universal query language SQL(Standard Query language) for manipulating
and accessing data associated with them.

Different database systems have surprisingly little in common: just a similar purpose and
a mostly compatible query language. Beyond that, every database has its own API that you must learn
to write programs that interact with the database. So writing code capable of interfacing with
databases from more than one vendor was a great challenge.

JDBC-Stands for Java Database Connectivity is Sun's attempt to create a platform-neutral


interface between databases and Java. An API, or Application Programming Interface is a set of
classes, methods, and resources that programs can use to do their work. JDBC is a Java API that
defines a set of interfaces and classes used to write Java programs for accessing and manipulating
relational databases. These interfaces encapsulate major database functionality like running queries,
processing results, and determining configuration information. A database vendor or third-party
developer writes a JDBC driver, which is a set of classes that implements these interfaces for a
particular database system. So depending upon database used at backend, a java database program
makes use of the driver provided by the specific database vendor. For example, you need MySQL
JDBC drivers to access the MySQL database, and Oracle JDBC drivers to access the Oracle database.

Since nearly all relational database management systems (RDBMSs) support SQL, and
because Java itself runs on most platforms, JDBC makes it possible to write a single database
application that can run on different platforms and interact with different DBMSs.. Only thing we
need to do is to make use of the driver which is specific to the database used at the backend.

In short JDBC helps the programmers to write java applications that manage these three
programming activities:

 Connect to a data source, like a database.


 Send queries and update statements to the database.
 Retrieve and process the results received from the database in answer to your query.

Dept.of Computer Science And Applications, SJCET, Palai Page 222


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

4.1.1 JDBC ARCHITECTURE

(Fig:4.1) JDBC Architecture

The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is
used to access each data source and it is capable of supporting multiple concurrent drivers connected
to multiple heterogeneous databases. JDBC drivers are normally provided by specific data base
vendors and they serve as the interface to facilitate communications between JDBC and a proprietary
database

4.1.1.1 JDBC DRIVER MANAGER

DriverManager is the very important part of the JDBC architecture whose main purpose
is to provide a means of managing the different types of JDBC database driver. On running an
application, it is the DriverManager's responsibility to load all the drivers found in the system
properly. It then matches connection requests from the java application with the proper database
driver. When opening a new connection to a database it is the Driver Manager's duty to choose the
most appropriate driver from the previously loaded drivers. Internally, JDBC DriverManager is a
class in JDBC API and objects of this class can connect Java applications to a JDBC driver

4.1.1.2 JDBC DRIVERS

JDBC Drivers are written by vendors and must support the basic features of the JDBC
specification ie, JDBC drivers should implement interfaces and classes defined by the JDBC API for a
particular DBMS vendor. It serves as the interface to facilitate communications between JDBC and a

Dept.of Computer Science And Applications, SJCET, Palai Page 223


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

proprietary database. It processes JDBC methods invocations, sends SQL statements to a specific data
source, and returns results back to the application. It translates and/or optimizes requests so the request
conforms to the syntax supported by the specific DBMS providing database independence.. If the back-
end database changes, only JDBC driver need to be replaced.

4.1.2 JDBC DRIVERS TYPES:


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:

Type 1 - JDBC-ODBC Bridge Driver


Type 2 - JDBC-Native Bridge Driver
Type 3 - JDBC-Net Bridge Driver
Type 4 - Direct JDBC Driver

4.1.2.1 TYPE 1 - JDBC-ODBC BRIDGE

(Fig:4.2) Type I Driver

Type 1 drivers use another technology such as Open Database Connectivity (ODBC) to
communicate with a database. ODBC is a proprietary format developed by Microsoft that enables
communication between databases clients running on Windows and DBMS available on the market.
Since there are different types of databases and each of them has its own way of dealing with SQL
queries and to return the results, ODBC provides identical results regardless of the type of database,
without the need for you to configure the program that sends the request. This is an advantage because

Dept.of Computer Science And Applications, SJCET, Palai Page 224


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

ODBC drivers exist for many Relational Database Management System (RDBMS) platforms This
driver is included in the Java 2 SDK within the sun.jdbc.odbc package and it translates JDBC method
calls into ODBC function calls and sends them to the ODBC driver. The Bridge implements JDBC for
any database for which an ODBC driver is available.

In order to use Type 1 drivers ODBC must be installed on the computer having the driver
and the database which is being connected to must support an ODBC driver. This is platform-
dependent as it makes use of ODBC which in turn depends on native libraries of the operating system.
Applications that make use of this driver cause performance overhead since the calls have to go
through the JDBC overhead bridge to the ODBC driver, then to the native db connectivity interface.
Type 1 drivers are not suitable for developing web applications as they need software to be installed on
client machine

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.

4.1.2.2 TYPE 2 - JDBC-NATIVE BRIDGE

Type 2 drivers use the Java Native Interface (JNI) to make calls to a local
database library API. This driver converts the JDBC calls into a database specific call for databases
such as SQL, ORACLE etc i.e. this driver is specific to a particular database. This driver
communicates directly with the database server and requires some native code to connect to the
database. These drivers 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 driver as it is specific to a database. Since
Native API must be installed in the Client System type 2 drivers cannot be used for the Internet. The
distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance
than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type1

(Fig: 4.3) Type II Driver

Dept.of Computer Science And Applications, SJCET, Palai Page 225


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

4.1.2.3 TYPE 3 - JDBC-NET BRIDGE

The JDBC type 3 driver, also known as the network-protocol driver is a database driver
implementation which makes use of a middle-tier between the calling program and the database. The
middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific
database protocol. Type 3 database requests are passed through the network to the middle-tier server
and the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers to translate the request to
the database. Since the communication between client and the middleware server is database
independent, there is no need for the vendor db library on the client machine.

This driver is very flexible as it allows access to multiple databases using one driver .The
number of data bases that can be accessed depends on the number of databases the middleware has
been configured to support. Type 3 driver is suitable for developing web applications since there is no
client side software needed. One of the disadvantages of this driver is that database-specific coding
should be done in the middle tier.

(Fig: 4.4) Type III Driver

4.1.2.4 Type 4 - Direct JDBC Driver

Type 4 drivers are pure Java drivers that implement a proprietary database protocol
to communicate directly with the database. Like Type 3 drivers, they do not require native database
libraries and can be deployed over the Internet without client installation. One drawback to Type 4
drivers is that they are database specific. Unlike Type 3 drivers, if your back-end database changes,
you may save to purchase and deploy a new Type 4 driver (some Type 4 drivers are available free of
charge from the database manufacturer). However, because Type 4 drivers communicate directly with
the database engine rather than through middleware or a native library, they are usually the fastest

Dept.of Computer Science And Applications, SJCET, Palai Page 226


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

JDBC drivers available. This driver directly converts the java statements to SQL statements. The
major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve
platform independence and eliminate deployment administration issues. This is the highest
performance driver available for the database and is usually provided by the vendor itself. The only
disadvantage is that we need to download a new driver for each database engine.

(Fig 4.5) Type IV Driver

Which Driver should be used?

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.

4.1.3 JAVA.SQL PACKAGE

The java.sql package contains the entire set of interfaces and classes defined by JDBC
API that sends SQL (Structured Query Language) statements to relational databases and retrieves the
results of executing those SQL statements.

Dept.of Computer Science And Applications, SJCET, Palai Page 227


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

(Fig: 4.6) Java.sql Package

Following are some of the classes and interfaces in java.sql:

4.1.3.1 DRIVERMANAGER CLASS

The cornerstone of the JDBC package is the DriverManager class. This class keeps track
of all the different available database drivers. The DriverManager manages loading and unloading
drivers. The DriverManager maintains a Vector that holds information about all the drivers that it
knows about. The elements in the Vector contain information about the driver such as the class name
of the Driver object, a copy of the actual Driver object, and the Driver security context. The
DriverManager, while not a static class, maintains all static instance variables with static access
methods for registering and unregistering drivers.

Dept.of Computer Science And Applications, SJCET, Palai Page 228


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

METHODS:

public static synchronized Connection getConnection(String URL) throws SQLException-


Establishes a connection to the given database URL, with the given parameters

public static Driver getDriver(String URL) throws SQLException- Finds a driver that
understands the JDBC URL from the registered driver list

4.1.3.2 DATE CLASS

The Date class is used to represent dates in the SQL format YYYY-MM-DD. It contains methods to
perform conversions of java.util.Date and the SQL DATE type

METHODS

public String toString()-Formats a Date object as YYYY-MM-DD

public static Date valueOf (String str)-Converts a String str to an sql.Date object

4.1.3.3 TIME CLASS

The Time class is used to represent times in the SQL format HH:MM:SS. It contains methods to
perform SQL TIME type and Java Time object conversions.

METHODS:

public String toString()-Returns a String with the Time formatted this way: HH:MM:SS

public static Time valueOf(String numStr)-Returns a Numeric object from the String numStr
parameter that is in the format: HH:MM:SS

4.1.3.4 TIMESTAMP

The Timestamp class is used to represent a combination of date and time values in the ANSI SQL
format YYYY-MMDD HH:MM:SS.F

METHODS:

public boolean equals(Timestamp tstamp) Compares the Timestamp object with the Timestamp
parameter tstamp; returns true if they match

public int getNanos()-Returns the Timestamp object’s nanoseconds

Dept.of Computer Science And Applications, SJCET, Palai Page 229


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

4.1.3.5 THE DRIVER INTERFACE

The Driver is the software wedge that communicates with the platform-dependent
database, either directly or using another piece of software. How it communicates really depends on
the database, the platform, and the implementation. So All JDBC Drivers must implement the Driver
interface and each driver should supply a class that implements the Driver interface.

4.1.3.6 THE CONNECTION INTERFACE

The Connection interface encapsulates the actual database connection into an


easy-to-use package. It is created by the DriverManager when its getConnection() method is called.
This method accepts a database connection URL and returns a database Connection to the caller. To
connect with a JDBC data source, a uniform resource locator, or URL, is used. The format follows:

jdbc:<sub-protocol>:<sub-name> , where

sub-protocol is the name of the driver set that defines a particular database connectivity method. This
can be represented by several drivers.
sub-name is the additional information necessary to complete the URL. This information is different
depending on the sub-protocol.
Eg:String url = “jdbc:odbc:mysource”;
Using the getConnection() method, the DriverManager asks each driver that has
registered with it whether the database connection URL is valid. If one driver responds positively, the
DriverManager assumes a match. If no driver responds positively, an SQLException is thrown. The
DriverManager returns the error "no suitable driver," which means that of all the drivers that the
DriverManager knows about, not one of them could figure out the URL you passed to it.

4.1.3.7 THE STATEMENT INTERFACE


A Statement object can represent any SQL statement, and the Statement interface
contains methods for defining and executing the SQL statement. From the Connection object, an
application can create three types of Statement objects. The base Statement object is used for
executing SQL statements directly. The PreparedStatement object (which extends Statement) is used
for precompiling SQL statements that may contain input parameters. The CallableStatement object
(which extends PreparedStatement) is used to execute stored procedures that may contain both input
and output parameters. Some of the methods in the Statement interface include

 int executeUpdate( String sqlStatement )


This method sends the SQL query contained in sqlStatement and returns an integer. This method is
useful when you send SQL INSERTs, DELETEs, and UPDATEs. These commands return a count of
rows that were affected by your query. This statement should not be used for queries that return result
sets.

Dept.of Computer Science And Applications, SJCET, Palai Page 230


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

 ResultSet executeQuery( String sqlStatement )


This method sends the SQL query contained in sqlStatement and returns a single set of results. This
method is best used in sending SELECT statements. These statements typically return a result set.

 boolean execute( String sqlStatement )


This method sends the sqlStatement to the database and returns true if the statement returns a result
set or false if the statement returns an integer. This method is best used when multiple result sets can
be returned.

The following methods can be used to easily navigate the results a query returns:

 boolean getMoreResults()
This moves to the next result set in the Statement. This, like the execute() method, returns true if the
next result is a result set or false if it is an integer. If you have already retrieved a ResultSet from the
Statement, this method will close it before returning.

 ResultSet getResultSet()
This method returns to you a result set in a ResultSet object. This result set is the current result set.

 int getUpdateCount()
This method returns to you the integer result that an execute() method returned.

4.1.3.8 THE RESULTSET CLASS

The SQL statements that read data from a database query return the data in a result set.
The SELECT statement is the standard way to select rows from a database and view them in a result
set. The java.sql.ResultSet interface represents the result set of a database query A ResultSet object
maintains a cursor that points to the current row in the result set. When a ResultSet object is created,
its position is always before the first row of data contained within the ResultSet. The methods of the
ResultSet interface can be broken down into three categories:

 Navigational methods used to move the cursor around.


 Get methods that are used to view the data in the columns of the current row being pointed to by
the cursor.
 Update methods that update the data in the columns of the current row.

NAVIGATIONAL METHODS:

A ResultSet provides access to a table of data generated by executing a Statement. The table rows
are retrieved in sequence and it maintains a cursor pointing to its current row of data. There are
several methods in the ResultSet interface that involve moving the cursor:

When you've retrieved all the data you can from a column, it is time to move on to the next row.
Moving to the next row is done with the next() method. This method returns a boolean value

Dept.of Computer Science And Applications, SJCET, Palai Page 231


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

indicating the status of the row. Internally, it moves the ResultSet's cursor to the next row, thereby
giving access to the data stored in the columns of that row.

public boolean next()-Moves the cursor to the next row. This method returns false if there are no
more rows in the result set. The first call to next() makes the first row available to your program

public int getRow()-Returns the row number that the cursor is pointing to

public boolean absolute(int row) -Moves the cursor to the specified row.

public boolean relative(int row)-Moves the cursor the given number of rows forward or backwards
from where it currently is pointing.

METHODS FOR VIEWING A RESULT SET

The ResultSet interface contains dozens of methods for getting the data of the current
row. There is a get method for each of the possible data types, and each get method has two versions:
one that takes in a column name, and one that takes in a column index.

For example, if the column you are interested in viewing contains an int, you need to use one of the
getInt() methods of ResultSet:

public int getInt(String columnName)-Returns the int in the current row in the column named
columnName.

public int getInt(int columnIndex) -Returns the int in the current row in the specified column index.
The column index starts at 1, meaning the first column of a row is 1, the second column of a row is 2,
and so on.

There are get methods in the ResultSet interface for each of the eight Java primitive types, as well as
common types such as java.lang.String and java.lang.Object. There are also methods for getting SQL
data types java.sql.Date, java.sql.Time, java.sql.TimeStamp.

METHODS FOR UPDATING A RESULT SET

The ResultSet interface contains a collection of update methods for updating the data of a
result set. As with the get methods, there are two update methods for each data type: one that uses the
column name and one that uses the column index. For example, to update a String column of the
current row of a result set, you would use one of the following updateString() methods:

public void updateString(int columnIndex, String s) -Changes the String in the specified column
to the value of s.

public void updateString(String columnName, String s)-Similar to the previous method, except
that the column is specified by its name instead of its index.

Dept.of Computer Science And Applications, SJCET, Palai Page 232


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

There are update methods for the eight primitive data types, as well as String and the SQL data types
in the java.sql package.

Updating a row in the result set changes the columns of the current row in the ResultSet object, but
not in the underlying database. To update your changes to the row in the database, you need to invoke
the following method:

public void updateRow()-Updates the current row by updating the corresponding row in the
database.

4.1.3.9 PREPAREDSTATEMENT INTERFACE

The PreparedStatement is used for pre-compiling an SQL statement, typically in


conjunction with parameters, and can be efficiently executed multiple times with just a change in a
parameter value; the SQL statement does not have to be not have to be parsed and compiled each time
The java.sql.PreparedStatement interface is used to represent a prepared SQL statement. Before a
prepared statement can be executed, each parameter needs to be assigned using one of the set
methods in the PreparedStatement interface. A question mark is used to denote a parameter.

For example, the following prepared statement inserts a new row in a table called Employees:

INSERT INTO Employees VALUES (?, ?, ?, ?)

This prepared statement contains four parameters. When the Prepared- Statement object is created
using the Connection object, this statement is sent to the database and precompiled, allowing the
database to execute the statement at a faster rate.

Using a prepared statement involves the following steps:

 Create a PreparedStatement object using one of the prepareStatement() methods of the


connection.

Connection Interface, contains different methods for creating a PreparedStatement. The method
public PreparedStatement prepareStatement(String sql) creates a prepared SQL statement. The
SQL is sent to the database for precompilation.

Eg: PreparedStatement insert =


connection.prepareStatement(“INSERT INTO Employees VALUES (?, ?, ?, ?)”);

Each question mark in a prepared statement denotes a parameter. The order in which the parameters
appear determines their index, with the first parameter being index 1, the second parameter index 2,
and so on. This is important when you go to set the values using the various set methods in the
PreparedStatement interface.

Dept.of Computer Science And Applications, SJCET, Palai Page 233


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

 Use the appropriate set methods of the PreparedStatement interface to set each of the
parameters of the prepared statement.

Before a prepared statement can be executed, each of its parameters must be assigned a value. The
PreparedStatement interface contains a set method for each of the possible data types of a
parameter. Each set method takes in an index to denote which parameter to set. For example, if the
data type of the parameter is a double, then you use the method.

Eg: The following statements prepare a statement and assign each of its four parameters a value using
the appropriate set method:

PreparedStatement insert =
connection.prepareStatement(“INSERT INTO Employees VALUES (?, ?, ?, ?)”);
insert.setDouble(2, 2.50);
insert.setInt(1, 103);
insert.setString(3, “George”);
insert.setString(4, “Washington”);

Notice that the order in which you set the parameters does not matter, as long as you set a
value for each parameter of the prepared statement.
 Invoke one of the execute() methods of the PreparedStatement interface to execute the
statement.

After the values of all the parameters are set, the prepared statement is executed using one of the
following methods in the PreparedStatement interface:

public ResultSet executeQuery()-Use this method if the SQL statement returns a result set, like a
SELECT statement.

public int executeUpdate()-Use this method for statements like INSERT, UPDATE, or DELETE.
The return value is the number of rows affected.

public boolean execute()-This method executes any type of SQL statement. Use the getResultSet()
method to obtain the result set if one is created

Eg: insert. executeUpdate();

4.1.3.10 CALLABLESTATEMENT INTERFACE

This is the primary interface to access stored procedures on a database. A stored procedure
allows you to repeat a sequence of tasks repeatedly in an efficient manner, much like writing a
method in Java. Use one of the prepareCall() methods of the Connection interface to create a
CallableStatement object:

Dept.of Computer Science And Applications, SJCET, Palai Page 234


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

public CallableStatement prepareCall(String sql)-Creates a callable statement using the given


SQL statement

The SQL for invoking a callable procedure is: {call procedure_name}

CallableStatement cs1 = con.prepareCall("{call HelloWorld}");


ResultSet rs1 = cs1.executeQuery();

4.1.4JAVA DATABASE CONNECTIVITY STEPS

Following are the different steps involved in using JDBC to access a database

 Importing java.sql package


 Load the driver (Only performed once)
 Establishing a Connection to the database (Save for later use)
 Obtain a Statement object from the Connection
 Use the Statement object to execute SQL. [Updates, inserts and deletes return Boolean.
Selects return a ResultSet]
 Retrieve and Navigate through ResultSet, using data as required
 Close Statement and connection

1. importing java.sql

java.sql package contains all the classes and interfaces we need to create and manage a
data base connection. Inorder to make use of these classes and interfaces we need to import them in
our program

2. Loading a database driver,

In this step of the jdbc connection process, we load the driver class by calling
Class.forName() with the Driver class name as an argument. Once loaded, the Driver class creates an
instance of itself. A client can connect to Database Server through JDBC Driver. Since most of the
Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used. The
return type of the Class.forName (String ClassName) method is “Class”. Class is a class in java.lang
package.

Dept.of Computer Science And Applications, SJCET, Palai Page 235


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

try
{
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver
}
catch(Exception x)
{
System.out.println( “Unable to load the driver class!” );
}

3. Connecting to DBMS

The JDBC DriverManager class defines objects which can connect Java applications to a
JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class
manages the JDBC drivers that are installed on the system. Its getConnection() method is used to
establish a connection to a database. It uses a username, password, and a jdbc url(that represents the
name of the data source) to establish a connection to the database and returns a connection object. A
jdbc Connection represents a session/connection with a specific database. Within the context of a
Connection, SQL, PL/SQL statements are executed and results are returned. An application can have
one or more connections with a single database, or it can have many connections with different
databases. A Connection object provides metadata i.e. information about the database, tables, and
fields. It also contains methods to deal with transactions.

JDBC URL Syntax: jdbc: <subprotocol>: <subname>

All JDBC URLs start with jdbc. The subprotocol is actually determined by the driver you
are using. The subname can contain additional information used by the satisfying subprotocol
(i.e.driver), such as the location of the data source, as well as a port number

EXAMPLE:

String url =“jdbc:odbc:CustomerInformation”;


String userID=“sjec”;
String password = “comp”
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);
Connection conn = DriverManager.getConnection(url,userID,password);
}

This method returns a Connection interface that is used throughout the process to reference the
database.

Dept.of Computer Science And Applications, SJCET, Palai Page 236


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

4. Creating a jdbc Statement object

Once a connection is obtained we can interact with the database. Connection interface defines
methods for interacting with the database via the established connection. To execute SQL statements,
you need to instantiate a Statement object from your connection object by using the createStatement()
method.

Statement statement = dbConnection.createStatement();

A statement object is used to send and execute SQL statements to a database. There are three
kinds of Statements

 Statement: It executes simple sql queries without parameters.


Statement createStatement() -Creates an SQL Statement object.
eg: Statement stmt = con.createStatement() ;

 Prepared Statement: Execute precompiled sql queries with or without parameters.


PreparedStatement prepareStatement(String sql) returns a new PreparedStatement object.
PreparedStatement objects are precompiled SQL statements.

EXAMPLE:

String insert = “Insert into CS4400 (?,?,?)”;


PreparedStatement stmt2 = con.prepareStatement(insert);
stmt2.setInt(1,123456789);
stmt2.setString(2,abc);
stmt2.setInt(3,100);
stmt2.executeUpdate();

 Callable Statement: Execute a call to a database stored procedure.


CallableStatement prepareCall(String sql) returns a new CallableStatement object.

CallableStatement cs = conn.prepareCall("{call StoreProcedureName}");


ResultSet rs = cs.executeQuery();

EXAMPLE:

CallableStatement cs1 = con.prepareCall("{call HelloWorld}");


ResultSet rs1 = cs1.executeQuery();

Dept.of Computer Science And Applications, SJCET, Palai Page 237


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

5. Use the Statement object to execute SQL

Statement interface defines methods that are used to interact with database via the
execution of SQL statements. The Statement class has three methods for executing statements:
executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is
executeQuery . For statements that create or modify tables, the method to use is executeUpdate. Note:
Statements that create a table, alter a table, or drop a table are all examples of DDL statements and
are executed with the method executeUpdate(). execute() executes an SQL statement that is written
as String object.

EXAMPLE:

String query = "SELECT col1, col2, col3 FROM sometable”;


ResultSet resultSet = statement.executeQuery(query);

6. Processing data returned by the DBMS

A result set provides access to a table of data generated by executing a Statement. The
table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of
data. The next() method is used to successively step through the rows of the tabular results. Within a
row,ResultSet provides various getXxx methods that take a column index or column name as an
argument and return the result as a variety of different Java types and the the first column in a
ResultSet row has index 1.

EXAMPLE:

while(resultSet.next())
{
System.out.println(results.getString(1) + " " + results.getString(2) + " ” +results.getString(3));
}

7. Close connection

To close the connection explicitly, we call connection.close();

We should postpone this step if we expect to perform additional database operations, since the
overhead of opening a connection is usually large. In fact, reusing existing connections is such an
important optimization.

import java.sql.*

public class JDBCSample


{
public static void main( String args[])

Dept.of Computer Science And Applications, SJCET, Palai Page 238


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

{
String userName = "testuser";
String password = "testpass";
String url = "jdbc:mysql://localhost/test";
try
{
Class.forName ("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (url, userName, password);
//Create a Statement class to execute the SQL statement
Statement stmt = con.createStatement();

//Execute the SQL statement and get the results in a Resultset


ResultSet rs = stmd.executeQuery("select moviename, releasedate from movies");

// Iterate through the ResultSet, displaying two values


// for each row using the getString method

while (rs.next())
System.out.println("Name= " + rs.getString("moviename") + " Date= " +
rs.getString("releasedate");
}
catch (SQLException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
// Close the connection
con.close();
}
}

Dept.of Computer Science And Applications, SJCET, Palai Page 239


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

(Fig: 4.7) Java Data Base Connectivity

4.2 NETWORKING-INTRODUCTION

A network represents interconnection of computers that is capable of sharing files


and information between multiple systems. The computer which receives service is called client and
the computer which provides service is called server. The term network programming refers to
writing programs that execute across multiple devices (computers), in which the devices are all
connected to each other using a network. There is a unique identification number called IP address
(Internet Protocol) allotted to every computer on a network or Internet. An IP address consists of
four dotted decimal numbers between 0 and 255, such as 130.254.204.36. The computers in a
network make use of this IP address in order to communicate with each other. Since it is not easy to
remember an IP address, they are often mapped to meaningful names called domain names or
hostnames. Special servers called Domain Name Servers (DNS) are available on the Internet that
translate host names into IP addresses. When a computer specifies a site address, it first asks the DNS

Dept.of Computer Science And Applications, SJCET, Palai Page 240


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

to translate this domain name into a numeric IP address and then sends the request using the IP
address.
We need to specify certain set of rules that needs to be followed when a system
communicates with another system. A protocol is a precise set of rules defining how computers
communicate: the format of addresses, how data is split into packets, etc. There are many different
protocols defining different aspects of network communication. For example HTTP is used to transfer
HTML documents on the Web and FTP allows you to transfer binary files over the Internet. Both
protocols have their own set of rules and standards on how data is transferred.

Each computer on the internet can provide a variety of services and the type of service must
be known before information can be transferred. Each computer with an IP address has several
thousand logical ports. These are purely abstractions in the computer's memory and do not represent
anything physical like a serial or parallel port. Each port is identified by a number from 1 to 65,535.
and each port can be allocated to a particular service.

For example, the HTTP service, which is used by the Web, generally runs on port 80: we
say that a web server listens on port 80 for incoming connections. SMTP or email servers run on port
25. When data is sent to a web server on a particular machine at a particular IP address, it is also sent
to a particular port (usually port 80) on that machine. The receiver checks each packet it sees for the
port and sends the data to any programs that are listening to the specified port. Port numbers from 1
to 1023 are reserved for well-known services such as finger, FTP, HTTP, and email.

Data transmitted over the internet follows a specific protocol and is accompanied by
addressing information that identifies the computer (IP address) and the port for which it is destined.
The receiver checks each packet it sees for the port and sends the data to any programs that are
listening to the specified port.

4.2.1 SOCKET COMMUNICATION

The socket is the software abstraction used to represent the "terminals" of a connection
between two machines. Network programming usually involves a server and one or more clients. The
client sends requests for information/services own by the Server. Once the connection is established
between Client and Server, they can start sending / receiving information. Socket acts as an interface
through which sever and client can send / receive information and it is identified by using the port
number and IP address In a nutshell, a socket on one computer that talks to a socket on another
computer creates a communication channel. A programmer can use that channel to send data between
the two machines.

Java treats socket communications much as it treats I/O operations; thus programs can read from
or write to sockets as easily as they can read from or write to files.

The socket associates the server program with a specific hardware port on the machine where it
runs so any client program anywhere in the network with a socket associated with that same port can

Dept.of Computer Science And Applications, SJCET, Palai Page 241


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

communicate with the server program. The server waits and listens to the socket for a client to make a
connection request

(Fig:4.8) Client Server Communication

The server accepts the connection request from client which contains the name of
the server and port number. Upon acceptance, the server creates a new socket bound to a different
port and this new socket is dedicated for serving the client that had sent request. The original socket
can continue to listen for further connection requests

(Fig:4.9) Client Server Communication

4.2.2 THE JAVA NETWORKING PACKAGE

The java.net package contains a collection of classes and interfaces that provide
functionalities for writing programs that execute across multiple devices (computers), in which the
devices are all connected to each other using a network. Some of the important classes available in
java.net Package are:

 InetAddress
 ServerSocket
 Socket
 DatagramPacket
 DatagramSocket
 URL

Dept.of Computer Science And Applications, SJCET, Palai Page 242


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

4.2.2.1 INETADDRESS CLASS

When you are establishing a connection across the Internet, addresses are fundamental. The
java.net.InetAddress class is Java's encapsulation of an IP address. It is used by most of the other
networking classes, including Socket, ServerSocket, URL, DatagramSocket, DatagramPacket. This
class represents an Internet address as two fields: hostName (a String) and address (an int).

There are no public constructors in the InetAddress class. However, InetAddress has three static
methods that return suitably initialized InetAddress objects, given a little information.

static InetAddress getLocalHost( ) throws UnknownHostException- returns the InetAddress of


the machine on which it's running.

Eg: InetAddress thisComputer = InetAddress.getLocalHost( );

static InetAddress getByName(String hostName) throws UnknownHostException- returns an


InetAddress for a host name passed to it and it throws an UnknownHostException if the host can't
be found

Eg: InetAddress address = java.net.InetAddress.getByName("www.oreilly.com");

static InetAddress[] getAllByName(String hostName) throw UnknownHostException- Some


computers have more than one Internet address. Given a hostname, this method returns an
InetAddress array that contains all the addresses corresponding to that name.

Eg:InetAddress[] addresses = InetAddress.getAllByName("www.google.com");

EXAMPLE:

import java.net.*;
class InetAddressTest
{
public static void main(String args[])throws UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("www.yahoo.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.google.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}

Dept.of Computer Science And Applications, SJCET, Palai Page 243


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

OUTPUT

COMPAQ-PC/192.168.2.2
www.yahoo.com/106.10.170.118
www.google.com/74.125.235.50
www.google.com/74.125.235.51
www.google.com/74.125.235.52
www.google.com/74.125.235.48
www.google.com/74.125.235.49

The InetAddress class contains getter methods that return the hostname and the IP address as a string

String getHostAddress(): Returns a string that represents the host address associated with the
InetAddress object.

String getHostName():Returns a string that represents the host name associated with the InetAddress
object.

The java.net package provides support for the two common network protocols:

TCP: TCP, Transmission Control Protocol is a connection oriented protocol which allows for
reliable communication between two applications. It guarantees that data sent from one end of the
connection actually gets to the other end and in the same order it was sent. Otherwise, an error is
reported

UDP: UDP, User Datagram Protocol, is a connection-less protocol that allows for packets of data to
be transmitted between applications. The destination port and IP addresses are written down in a
datagram and the datagram is sent to the destination. UDP does not guarantee that packets will be
received in the order they were sent

4.2.3 TRANSMISSION CONTROL PROTOCOL

Transmission Control Protocol (TCP) is often compared to making a telephone


call. If you want to telephone someone, the person needs to have a phone, needs a phone number, and
needs to be waiting for an incoming call. After the person you are calling answers the telephone, you
now have a reliable, two-way communication stream, allowing either person to talk to the other (even
at the same time). If one person hangs up the phone, the communication is over. With a TCP network
connection, the client computer is similar to the person placing the telephone call, and the server
computer is similar to the person waiting for a call. When the client attempts to connect to the server,
the server needs to be running, needs to have an address on the network, and needs to be waiting for
an incoming connection on a port. When a TCP connection is established, the client and server have a

Dept.of Computer Science And Applications, SJCET, Palai Page 244


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

reliable, two-way communication stream that allows data to be transmitted in either direction. Using
TCP provides a Stream-based communication for data transmission and it can detect lost
transmissions and resubmit them. The two computers can communicate until the connection is closed
or lost. The java.net.ServerSocket and java.net.Socket classes are the only two classes you will
probably ever need to create a TCP/IP connection between two computers for you. The
java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.

(Fig:4.10) Socket Communication

If TCP is similar to placing a telephone call, a socket is the telephone. Sockets


provide the communication mechanism between two computers using TCP. A client program creates
a socket on its end of the communication and attempts to connect that socket to a server. When the
connection is made, the server creates a socket object on its end of the communication. The client and
server can now communicate by writing to and reading from the socket.

The actual reading and writing of data over the socket is accomplished via the
familiar stream classes. After the connections are established, communication can occur using I/O
streams. Each socket has both an OutputStream and an InputStream. The client’s OutputStream
is connected to the server’s InputStream, and the client’s InputStream is connected to the server’s
OutputStream. TCP is a two way communication protocol, so data can be sent across both streams
at the same time.

Dept.of Computer Science And Applications, SJCET, Palai Page 245


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

4.2.3.1 SOCKET CLASS

The java.net.Socket class is Java's fundamental class for performing client-side


TCP operations. It contains constructor that is used to create stream socket that connects to specific
port number associated with exactly one host. Following are two most commonly used constructors
of Socket class.

Socket(String hostName, int port)


Creates a socket that connects to the given port number on the specified host. If the domain name
server cannot resolve the hostname or is not functioning, the constructor throws an
UnknownHostException. If the socket cannot be opened for some other reason, the constructor
throws an IOException

Socket(InetAddress ipAddress, int port)


Creates a socket that connects to the given port number at the specified IP address. It uses an
InetAddress object to specify the host rather than a hostname. It throws an IOException if it can't
connect

When the Socket constructor returns, it does not simply instantiate a Socket object. Within the
constructor, it actually attempts to connect to the specified server and port.

METHODS

InetAddress getInetAddress()-Given a Socket object, this method tells which remote host the
Socket is connected to or, if the connection is now closed, which host the Socket was connected to
when it was connected

int getPort() - tells you which port the Socket is (or was or will be) connected to on the remote host.

InputStream getInputStream()-returns an input stream that can read data from the socket into a
program. You can chain this InputStream to a filter stream or reader that offers more functionality
DataInputStream or InputStreamReader before reading input. It's also extremely helpful to buffer the
input by chaining it to a BufferedInputStream or a BufferedReader for performance reasons.

OutputStream getOutputStream()-returns a raw OutputStream for writing data from your


application to the other end of the socket. You can chain this stream to a more convenient class like
DataOutputStream or OutputStreamWriter before using it.

public void close()- Closes the socket, which makes this Socket object no longer capable of
connecting again to any server.

Dept.of Computer Science And Applications, SJCET, Palai Page 246


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

4.2.3.2 IMPLEMENTING A CLIENT

Java programs normally use client sockets in the following fashion:

1. The program creates a new socket with a Socket() constructor

2. The socket attempts to connect to the remote host.

3. Once the connection is established, the local and remote hosts get input and output streams from
the socket and use those streams to send data to each other.

4. When the transmission of data is complete, one or both sides close the connection.

EXAMPLE:

Socket clientSocket = new Socket("localhost", 6789);


OutputStreamWriter outToServer = new
OutputStreamWriter(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(“Hi from client”+’\n’);
String str = inFromServer.readLine();
System.out.println(“Message from server:”+ str);
clientSocket.close();

4.2.3.3 SERVERSOCKET Class

To establish a server, you need to create a server socket and attach it to a port, which is where
the server listens for connections. The java.net.ServerSocket class is used by server applications to
obtain a port and listen for client requests. It has constructors that create new ServerSocket objects,
methods that listen for connections on a specified port, and methods that return a Socket object when
a connection is made so that you can send and receive data.

A server socket waits for requests from client to come in over the network. When a client
Socket on a remote host attempts to connect to that port, the server wakes up, negotiates the
connection between the client and the server, and opens a regular Socket between the two hosts. Once
the server socket has set up the connection, the server uses a regular Socket object to send data to the
client. Following are the most commonly used constructors of this class.

public ServerSocket (int port)- creates a server socket on the port specified by the argument. The
constructor throws an IOException (specifically, a BindException) if the socket cannot be created
and bound to the requested port.

Dept.of Computer Science And Applications, SJCET, Palai Page 247


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

public ServerSocket(int port, int queueLength)- This constructor creates a ServerSocket on the
specified port with a queue length of your choosing. If the machine has multiple network interfaces or
IP addresses, then it listens on this port on all those interfaces and IP addresses. The queueLength
argument sets the length of the queue for incoming connection requests—that is, how many incoming
connections can be stored at one time before the host starts refuse connections

public ServerSocket(int port, int qLength, InetAddress address)- The InetAddress parameter
specifies the local IP address to bind to. The InetAddress is used for servers that may have multiple
IP addresses, allowing the server to specify which of its IP addresses to accept client requests on

METHODS

public int getLocalPort()-Returns the port that the server socket is listening on.

public Socket accept() - returns a Socket object representing the connection between the remote
client and the local server. It stops the flow of execution and waits until a client connects
We use the streams returned by this Socket's getInputStream() and getOutputStream() methods to
communicate with the client.

4.2.3.4 IMPLEMENTING SERVER

1. A new ServerSocket is created on a particular port using a ServerSocket() constructor.

2. The server invokes the accept() method of the ServerSocket class. accept() blocks until a client
attempts to make a connection, at which point accept() returns a Socket object connecting the
client and the server.

3. Depending on the requirement, either getInputStream() method, getOutputStream() method, or


both are called to get input and output streams that communicate with the client.

4. The server and the client interact according to an agreed-upon protocol until it is time to close the
connection.

5. The server, the client, or both close the connection.

6. The server returns to step 2 and waits for the next connection.

EXAMPLE:

ServerSocket server = new ServerSocket(5776);


Socket connection = server.accept( );
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));

Dept.of Computer Science And Applications, SJCET, Palai Page 248


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

String str= inFromClient.readLine();


System.out.println(“Message from client:”+str);
DataOutputStream outToclient= new DataOutputStream(connection.getOutputStream());
outToclient.writeBytes("You've connected to this server. Bye..“+’\n’);
connection.close();

(Fig:4.11) Client-Server interacts via TCP

The InputStream and OutputStream attributes of a Socket are the ways the two
computers communicate with each other. For example, if the server wants to send data to the client,
the server needs to write to the OutputStream of its socket, which is then read by the InputStream of
the client’s socket. Similarly, data can be sent from the client to the server using the client’s
OutputStream and the server’s InputStream.

CLIENT MACHINE CODE:


import java.io.*;
import java.net.*;

public class SimpleClient


{
public static void main(String args[]) throws Exception
{
String sentence;

Dept.of Computer Science And Applications, SJCET, Palai Page 249


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

String sent1;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

BufferedReader inFromServer = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence+'\n');
System.out.println("Message from Server:");
sent1= inFromServer.readLine();
System.out.println(sent1);
clientSocket.close();
}
}

SERVER MACHINE CODE:


import java.io.*;
import java.net.*;
public class SimpleServer
{
public static void main(String args[]) throws Exception
{
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReaderinFromClient=newBufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
System.out.println("Message from Client:");
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
outToClient.writeBytes("Thanks for greetings"+'\n');
}
}
}

Dept.of Computer Science And Applications, SJCET, Palai Page 250


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

4.2.4 USER DATAGRAM PROTOCOL

User Datagram Protocol (UDP) provides a protocol for sending packets of data
called datagrams between applications. If TCP is similar to placing a telephone call, UDP can be
compared to mailing someone a letter. The datagram packet is like a letter, where a client sends a
datagram to a server without actually connecting to the server. This makes UDP an unreliable
communication protocol when compared to TCP, where the client and server are directly connected.

If I mail you two letters on the same day, they might be delivered on the same day,
but this is hardly guaranteed. In fact, there is no guarantee that both letters will even get delivered at
all. It’s possible that one will be delivered the next day, whereas the other doesn’t arrive for two
weeks. The same is true for datagram packets. UDP does not guarantee that packets will be received
in the order they were sent or that they will even be delivered at all. If this type of unreliability is
unacceptable for the program you are developing, you should use TCP instead. However, if you’re
developing a network application in which reliable communication is not essential to the application,
UDP is probably a better option because it does not carry the overhead of TCP.

Datagram packets are used to implement a connectionless packet delivery service


supported by the UDP protocol. Each packet needs to have destination address and each packet might
be routed differently, and might arrive in any order.

The format of datagram packet is:


Msg | length | Host | serverPort

The java.net.DatagramPacket and java.net.DatagramSocket classes are used to


send and receive datagram packets. The DatagramPacket class stuffs bytes of data into UDP packets
called datagrams and lets you unstuff datagrams that you receive. A DatagramSocket sends as well as
receives UDP datagrams. To send data, you put the data in a DatagramPacket and send the packet
using a DatagramSocket. To receive data, you receive a DatagramPacket object from a
DatagramSocket and then read the contents of the packet. The sockets themselves are very simple
creatures. In UDP, everything about a datagram, including the address to which it is directed, is
included in the packet itself; the socket needs to know only the local port on which to listen or send.

This division of labour contrasts with the Socket and ServerSocket classes used by
TCP.UDP doesn't have any notion of a server socket. You use the same kind of socket to send data
and to receive data. Second, TCP sockets allow you to treat a network connection as a stream: you
send and receive with input and output streams that you get from the socket. UDP doesn't allow this;
you always work with individual datagram packets. All the data you stuff into a single datagram is
sent as a single packet and is either received or lost as a group. One packet is not necessarily related
to the next. Given two packets, there is no way to determine which packet was sent first and which
was sent second. Instead of the orderly queue of data that's necessary for a stream, datagrams try to
crowd into the recipient as quickly as possible, like a crowd of people pushing their way onto a bus.
A third difference, which is really a consequence of the first two, is that a single DatagramSocket can

Dept.of Computer Science And Applications, SJCET, Palai Page 251


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

send data to and receive data from many independent hosts. The socket isn't dedicated to a single
connection, as it is in TCP. In fact, UDP doesn't have any concept of a connection between two hosts;
it only knows about individual datagrams. Figuring out who sent what data is the application's
responsibility.

4.2.4.1 DATAGRAMSOCKET CLASS

The java.net.DatagramSocket class is used by both the sender and the recipient of
a datagram packet to send and receive a packet, respectively. There are two types of constructors for
DatagramSocket:

public DatagramSocket(int port) throws SocketException-Creates a datagram socket on the


localhost computer at the specified port.

public DatagramSocket(int port, InetAddress address) throws SocketException)-Creates a


datagram socket using the specified port and local address, which is useful if the computer has
multiple addresses.

METHODS

public void send(DatagramPacket packet) throws IOException-Sends the specified datagram


packet. The DatagramPacket object contains the destination information of the packet.

public void receive(DatagramPacket packet) throws IOException-This method receives a single


UDP datagram from the network and stores it in the pre-existing DatagramPacket object. Like the
accept() method in the ServerSocket class, this method blocks the calling thread until a datagram
arrives

4.2.4.2 DATAGRAMPACKET CLASS

In Java, a UDP datagram is represented by an instance of the DatagramPacket.


This class provides methods to get and set the source or destination address from the IP header, to get
and set the source or destination port, to get and set the data, and to get and set the length of the data.
There are two types of constructors for DatagramPacket. The first constructor is used to receive data
from the net; the second is for data that you will send to the net.

public DatagramPacket(byte[] buffer, int length)-Creates a datagram packet for receiving a packet
of the specified size. The buffer will contain the incoming packet. The array of bytes passed in to
these constructors is used to contain the data of the incoming packet, and typically are empty arrays.

public DatagramPacket(byte[] buffer, int length, InetAddress address, int port)- Creates a
datagram packet for sending a packet of the specified size. The buffer contains the data of the
packet, and the address and port denote the recipient.

Dept.of Computer Science And Applications, SJCET, Palai Page 252


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

METHODS

DatagramPacket has five methods that retrieve different parts of a datagram: the
actual data plus several fields from its header. These methods are mostly used for datagrams you
receive from the network.

public InetAddress getAddress()-The getAddress() method returns an InetAddress object


containing the address of the remote host. If the datagram was received from the Internet, the address
returned is the address of the machine that sent it (the source address). On the other hand, if the
datagram was created locally to be sent to a remote machine, this method returns the address of the
host to which the datagram is addressed.

public int getPort( ) -The getPort() method returns an integer specifying the remote port. If this
datagram was received from the Internet, this is the port on the host that sent the packet. If the
datagram was created locally to be sent to a remote host, this is the port to which this packet is
addressed on the remote machine.

public byte[ ] getData( )- The getData() method returns a byte array containing the data from the
datagram.

public int getLength( )-The getLength() method returns the number of bytes of data in the
datagram

public int getOffset( ) - This method simply returns the point in the array returned by getData()
where the data from the datagram begins

Java also provides four methods for changing the data, remote address, and remote port after the
datagram has been created

public void setData(byte [] buffer)-This method can be used to set the data of the packet.

public void setLength(int length)- Sets the length of the data to be sent or received.

public void setSocketAddress(SocketAddress address)-Sets the address of the remote host where
the message is being sent to or received from

4.2.4.3 RECEIVING A DATAGRAM PACKET

To receive a datagram packet, the following steps are performed:

1. Create an array of bytes large enough to hold the data of the incoming packet.

2. A DatagramPacket object is instantiated using the array of bytes.

Dept.of Computer Science And Applications, SJCET, Palai Page 253


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

3. A DatagramSocket is instantiated, and it is specified which port (and specific localhost address, if
necessary) on the localhost the socket will bind to.

4. The receive() method of the DatagramSocket class is invoked, passing in the DatagramPacket
object. This blocks the execution of further code until a datagram packet is received or a time
out occurs

EXAMPLE:

import java.net.*;
import java.io.*;
public class PacketReceiver
{
public static void main(String [] args) throws Exception
{
byte [] buffer = new byte[1024];
DatagramPacket packet =
new DatagramPacket(buffer, buffer.length);
DatagramSocket socket = new DatagramSocket(5002);
System.out.println(“Waiting for a packet...”);
socket.receive(packet);
System.out.println(“Just received packet from “+ packet.getSocketAddress());
buffer = packet.getData();
System.out.println(new String(buffer));
}
}

4.2.4.4 SENDING A DATAGRAM PACKET

1. Create an array of bytes large enough to hold the data of the packet to be sent, and fill the array
with the data.

2. Create a new DatagramPacket object that contains the array of bytes,


as well as the server name and port number of the recipient.

3. A DatagramSocket is instantiated, and it is specified which port (and specific localhost


address, if necessary) on the localhost the socket will bind to.

4. The send() method of the DatagramSocket class is invoked, passing in the DatagramPacket
object.

Dept.of Computer Science And Applications, SJCET, Palai Page 254


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

EXAMPLE:
import java.net.*;
import java.io.*;
public class PacketSender
{
public static void main(String [] args)
{
try
{
String data =
“You have just received a packet of data sent using UDP”;
byte [] buffer = data.getBytes();
DatagramPacket packet =
new DatagramPacket(buffer,buffer.length, InetAddress.getLocalHost(), 5002);
DatagramSocket socket = new DatagramSocket(5003);
System.out.println(“Sending a packet...”);
socket.send(packet);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}

(Fig 4.12) Client Server interaction via UDP

Dept.of Computer Science And Applications, SJCET, Palai Page 255


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

EXAMPLE:

CLIENT MACHINE CODE:


import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[])throws Exception
{
BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress=InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,
9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence =new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
SERVER MACHINE CODE:
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData= new byte[1024];
byte[] sendData= new byte[1024];
while(true)
{
DatagramPacket receivePacket =new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);

Dept.of Computer Science And Applications, SJCET, Palai Page 256


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

String sentence = new String(receivePacket.getData());


InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length,
IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
4.2.5 URL CLASS

URL stands for Uniform Resource Locator, represents a resource on the World
Wide Web, such as a Web page or FTP directory. A URL can be broken down into parts, as follows:

protocol://host:port/path?query#ref

Eg:http://www.javapassion.com:80/javaintro/index.html#Networking_A

PART MEANING REQUIRED

scheme or Internet protocol to be followed. e.g. http, https, ftp, mailto, etc. Yes
protocol This defines the syntax of the URL.

domain or This is the destination location for the URL. It can be a Yes
hostname hostname or ip address

Port The port to be used to connect to the location. No

path or This is typically a file or location on the web server. No


pathname

Query string This is the data to be passed to software running on the server. No
or search

Fragment This specifies a part or a position within the overall resource or No


id or ref document

(Table:4.1)

Dept.of Computer Science And Applications, SJCET, Palai Page 257


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

The java.net.URL class represents a URL. The URL class has several constructors for creating
URLs

public URL(String protocol, String host, int port, String file)-Creates a URL by putting together
the given parts

public URL(String url)- Creates a URL from the given String. The URL class contains many
methods for accessing the various parts of the URL being represented

The URL class contains many methods for accessing the various parts of the URL being represented.
Some of the methods in the URL class include the following:

public String getPath()-Returns the path of the URL.


public String getQuery()-Returns the query part of the URL.
public String getAuthority()-Returns the authority of the URL.
public int getPort()-Returns the port of the URL.
public int getDefaultPort()-Returns the default port for the protocol ofthe URL.
public String getProtocol()-Returns the protocol of the URL.
public String getHost()-Returns the host of the URL.
public String getFile()-Returns the filename of the URL.
public String getRef()-Returns the reference part of the URL.

EXAMPLE:
import java.net.*;
import java.io.*;
public class URLDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL(args[0]);
System.out.println("URL is:" + url.toString());
System.out.println("protocol is:"+ url.getProtocol());
System.out.println("file name is:" + url.getFile());
System.out.println("host is:" + url.getHost());
System.out.println("path is:" + url.getPath());
System.out.println("port is:" + url.getPort());
System.out.println("query is:" + url.getQuery());

Dept.of Computer Science And Applications, SJCET, Palai Page 258


MODULE IV MCA-301 Java and Web Programming ADMN 2011-‘14

System.out.println("ref is:" + url.getRef());


}
catch(IOException e)
{
e.printStackTrace();
}
}
}

OUTPUT
Java http://www.example.com:80/example.php?y=2#results
URL is:http://www.example.com:80/example.php?y=2#results
protocol is:http
file name is:/example.php?y=2
host is:www.example.com
path is:/example.php
port is:80
query is:y=2
ref is:results

Dept.of Computer Science And Applications, SJCET, Palai Page 259

You might also like