You are on page 1of 296

ALAGAPPA UNIVERSITY

[Accredited with ‘A+’ Grade by NAAC (CGPA:3.64) in the Third Cycle


and Graded as Category–I University by MHRD-UGC]
(A State University Established by the Government of Tamil Nadu)
KARAIKUDI – 630 003

Directorate of Distance Education

M.Sc. (Computer Science)


I - Semester
341 13

ADVANCED JAVA PROGRAMMING


Authors
Deepak Gupta, Assistant Professor, GL Bajaj Institute of Technology and Management, Greater Noida
Units: (1, 2, 4.0-4.4, 7, 8.2, 10, 11-12 )
Rohit Khurana, CEO, ITL Education Solutions Ltd.
Units: (3, 9, 13, 14.3-14.8)
Vikas® Publishing House, Units (4.5-4.12, 5, 6, 8.0-8.1, 8.3-8.9, 14.0-14.2.2)

"The copyright shall be vested with Alagappa University"

All rights reserved. No part of this publication which is material protected by this copyright notice
may be reproduced or transmitted or utilized or stored in any form or by any means now known or
hereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recording
or by any information storage or retrieval system, without prior written permission from the Alagappa
University, Karaikudi, Tamil Nadu.

Information contained in this book has been published by VIKAS® Publishing House Pvt. Ltd. and has
been obtained by its Authors from sources believed to be reliable and are correct to the best of their
knowledge. However, the Alagappa University, Publisher and its Authors shall in no event be liable for
any errors, omissions or damages arising out of use of this information and specifically disclaim any
implied warranties or merchantability or fitness for any particular use.

Vikas® is the registered trademark of Vikas® Publishing House Pvt. Ltd.


VIKAS® PUBLISHING HOUSE PVT. LTD.
E-28, Sector-8, Noida - 201301 (UP)
Phone: 0120-4078900  Fax: 0120-4078999
Regd. Office: 7361, Ravindra Mansion, Ram Nagar, New Delhi 110 055
 Website: www.vikaspublishing.com  Email: helpline@vikaspublishing.com

Work Order No. AU/DDE/DE1-238/Preparation and Printing of Course Materials/2018 Dated 30.08.2018 Copies - 500
SYLLABI-BOOK MAPPING TABLE
Advanced Java Programming

BLOCK I: INTRODUCTION
UNIT - 1: Introduction : JDBC Overview, Connection Class, MetaData Function Unit 1: Introduction to JDBC
(Pages 1-26)

UNIT - 2: SQL Exception, SQL Warning Unit 2: SQL Exception


and Warning
(Pages 27-33)

UNIT - 3: Statement, ResultSet, Other JDBC Classes Unit 3: JDBC Classes and
Statements
(Pages 34-56)

BLOCK II: INETADDRESS


UNIT - 4: Inetaddress, TCP/IP Client Sockets, TCP/IP Server Sockets Unit 4: InetAddress, TCP/IP
Client and Server Sockets
(Pages 57-82)

UNIT - 5: URL, URL Connection, DataGrams Unit 5: URL Connection and


Datagrams
(Pages 83-93)

UNIT - 6: Client/Server Applications Using RMI Unit 6: Client and Server


Applications Using RMI
(Pages 94-120)

BLOCK III: BDK AND DESIGN PATTERNS


UNIT - 7: Bean Development Kit, JAR Files, Introspection Unit 7: BDK and JAR Files
(Pages 121-134)

UNIT - 8: Design Patterns for Properties, Events and Methods Unit 8: Design Patterns and
Event Handling
(Pages 135-163)

UNIT - 9: Constrained Properties, Persistence, Customizers Unit 9: Bean Properties and


Persistence
(Pages 164-171)
BLOCK IV: SERVLETS
UNIT - 10: Life Cycle of Servlet, Generic Servlet, HTTP Servlet Unit 10: Java Servlets
(Pages 172-209)

UNIT - 11: Reading Initialization, Parameters, Reading Servlet Parameters Unit 11: Servlet Parameters
(Pages 210-228)

UNIT - 12: Cookies, Session Tracking Unit 12: Cookies and Session
Tracking
(Pages 229-242)

BLOCK V: JAPPLET AND AWT CLASSES


UNIT - 13: JApplet, Buttons, Combo, Trees, Tables, Panes Unit 13: Java Interface
Components
(Pages 243-265)

UNIT - 14: AWT Classes, Working with Graphics, Color and Font Unit 14: AWT Classes and
Working with Graphics
(Pages 266-284)
CONTENTS
INTRODUCTION
BLOCK I: INTRODUCTION
UNIT 1 INTRODUCTION TO JDBC 1-26
1.0 Introduction
1.1 Objectives
1.2 JDBC: Overview
1.2.1 JDBC Drivers
1.2.2 Seven Steps to Create the JDBC Programs and Applications
1.3 JDBC Metadata API
1.4 A JDBC-Servlet Example
1.5 A JDBC-JSP Example
1.6 Answers to Check Your Progress Questions
1.7 Summary
1.8 Key Words
1.9 Self Assessment Questions and Exercises
1.10 Further Readings
UNIT 2 SQL EXCEPTION AND WARNING 27-33
2.0 Introduction
2.1 Objectives
2.2 SQL Exception and SQL Warning Concepts
2.2.1 Exception Retrieval
2.2.2 Introduction to SQL Warning
2.2.3 Special SQL Exceptions
2.3 Answers to Check Your Progress Questions
2.4 Summary
2.5 Key Words
2.6 Self Assessment Questions and Exercises
2.7 Further Readings
UNIT 3 JDBC CLASSES AND STATEMENTS 34-56
3.0 Introduction
3.1 Objectives
3.2 The java.sql Package
3.2.1 The DriverManager Class
3.2.2 The Connection Interface
3.2.3 The Statement Interface
3.2.4 The ResultSet Interface
3.2.5 The PreparedStatement Interface
3.2.6 The ResultSetMetaData Interface
3.2.7 The CallableStatement Interface
3.2.8 The SQLException Class
3.3 Answers to Check Your Progress Questions
3.4 Summary
3.5 Key Words
3.6 Self Assessment Questions and Exercises
3.7 Further Readings

BLOCK II: INETADDRESS


UNIT 4 INETADDRESS, TCP/IP CLIENT AND SERVER SOCKETS 57-82
4.0 Introduction
4.1 Objectives
4.2 The InetAddress Class
4.3 Getter Methods
4.4 Inet4Address and Inet6Address
4.5 Using IP Addresses and InetAddress
4.6 Networking Protocols
4.7 Ports and Sockets
4.7.1 Using TCP/IP Sockets
4.8 Answers to Check Your Progress Questions
4.9 Summary
4.10 Key Words
4.11 Self Assessment Questions and Exercises
4.12 Further Readings
UNIT 5 URL CONNECTION AND DATAGRAMS 83-93
5.0 Introduction
5.1 Objectives
5.2 URL and URL Connection Classes
5.3 Using UDP Sockets
5.3.1 Creating a Server Program
5.3.2 Creating a Client Program
5.4 Answers to Check Your Progress Questions
5.5 Summary
5.6 Key Words
5.7 Self Assessment Questions and Exercises
5.8 Further Readings
UNIT 6 CLIENT AND SERVER APPLICATIONS USING RMI 94-120
6.0 Introduction
6.1 Objectives
6.2 N-Tier Architecture
6.3 Overview of RMI
6.4 Distributed Object Technologies
6.5 Locating and Loading Remote Classes
6.6 Locating Remote Objects
6.7 Enabling Remote Method Class
6.8 Creating a Client Class
6.9 Transferring Non Remote Objects
6.10 Handling Exceptions
6.11 Executing RMI
6.12 Implementing Callbacks
6.13 Distributing the RMI Application
6.14 Using Applets with RMI
6.14.1 Defining Server Class
6.14.2 Defining Remote Interfaces
6.14.3 Defining Client Class
6.14.4 Creating the HTML File
6.14.5 Executing the RMI with Applet
6.15 RMI Architecture
6.15.1 Application Layer
6.15.2 Proxy Layer
6.15.3 Transport Layer
6.16 Socket versus RMI Programming
6.17 Answers to Check Your Progress Questions
6.18 Summary
6.19 Key Words
6.20 Self Assessment Questions and Exercises
6.21 Further Readings

BLOCK III: BDK AND DESIGN PATTERNS


UNIT 7 BDK AND JAR FILES 121-134
7.0 Introduction
7.1 Objectives
7.2 Java Beans
7.3 Java Archive File (JAR)
7.4 Introspection
7.5 Answers to Check Your Progress Questions
7.6 Summary
7.7 Key Words
7.8 Self Assessment Questions and Exercises
7.9 Further Readings
UNIT 8 DESIGN PATTERNS AND EVENT HANDLING 135-163
8.0 Introduction
8.1 Objectives
8.2 Design patterns for Java Bean Properties
8.3 Introducing Event Handling
8.3.1 Event Classes
8.3.2 Sources of Events
8.3.3 Event Listener Interfaces
8.4 Process of Handling Events
8.4.1 ActionListener
8.4.2 AdjustmentListener
8.4.3 MouseListener
8.4.4 MouseMotionListener
8.4.5 WindowListener
8.4.6 KeyListener
8.5 Answers to Check Your Progress Questions
8.6 Summary
8.7 Key Words
8.8 Self Assessment Questions and Exercises
8.9 Further Readings
UNIT 9 BEAN PROPERTIES AND PERSISTENCE 164-171
9.0 Introduction
9.1 Objectives
9.2 Bound and Constrained Properties
9.2.1 Persistence
9.2.2 Customization
9.2.3 Bean Conventions
9.2.4 A Simple Bean
9.3 The Java Beans API
9.4 Answers to Check Your Progress Questions
9.5 Summary
9.6 Key Words
9.7 Self Assessment Questions and Exercises
9.8 Further Readings

BLOCK IV: SERVLETS


UNIT 10 JAVA SERVLETS 172-209
10.0 Introduction
10.1 Objectives
10.2 Introduction to Java Servlets
10.2.1 Servlets Vs CGI
10.3 Servlet Developmental History
10.4 Prerequisites for Servlets
10.4.1 HTML
10.4.2 Servers
10.4.3 Servlet Container
10.4.4 Installing and Configuring the Apache Tomcat Server
10.4.5 Starting and Stopping Tomcat
10.4.6 Testing Tomcat
10.5 Basics of Servlets
10.5.1 The Java Servlet API
10.5.2 Servlet Life Cycle
10.6 Coding a Servlet
10.6.1 GenericServlet Class
10.6.2 An Example of GenericServlet Class implementation
10.6.3 The Dissection
10.6.4 Output
10.7 Http Servlet Class
10.7.1 Methods of Http Servlet Class
10.7.2 An Example of Http Servlet Class implementation
10.7.3 The Dissection
10.8 The First Run
10.9 First Web Application Using Servlet
10.10 A Web Application based on HTML Web Page and Servlet
10.11 A Web Application Handling User Inputs via Forms Using Servlets
10.12 Answers to Check Your Progress Questions
10.13 Summary
10.14 Key Words
10.15 Self Assessment Questions and Exercises
10.16 Further Readings
UNIT 11 SERVLET PARAMETERS 210-228
11.0 Introduction
11.1 Objectives
11.2 Understanding the Servlet Requests and Servlet Responses Mechanism
11.3 Servlet Responses
11.4 HttpServletResponse Interface
11.5 Servlets Interactions
11.6 Answers to Check Your Progress Questions
11.7 Summary
11.8 Key Words
11.9 Self Assessment Questions and Exercises
11.10 Further Readings
UNIT 12 COOKIES AND SESSION TRACKING 229-242
12.0 Introduction
12.1 Objectives
12.2 Session Management/Tracking
12.3 Servlet Debugging
12.4 Answers to Check Your Progress Questions
12.5 Summary
12.6 Key Words
12.7 Self Assessment Questions and Exercises
12.8 Further Readings

BLOCK V: JAPPLET AND AWT CLASSES


UNIT 13 JAVA INTERFACE COMPONENTS 243-265
13.0 Introduction
13.1 Objectives
13.2 Swing Components and Containers
13.2.1 Swing Components (JComponent Class)
13.2.2 Swing Containers
13.3 Creating a Swing Applet and Application
13.4 User Interface Components
13.4.1 JApplet
13.4.2 JFrame
13.4.3 Label
13.4.4 Button
13.4.5 ToggleButton
13.4.6 CheckBox
13.4.7 TextField
13.4.8 TextArea
13.4.9 RadioButton
13.4.10 Panel
13.4.11 ScrollPane
13.4.12 ComboBox
13.4.13 JTree Class
13.5 Programming using Panes
13.5.1 Layered Panes
13.5.2 Split Panes
13.5.3 Tabbed Panes
13.6 JTable
13.7 Answers to Check Your Progress Questions
13.8 Summary
13.9 Key Words
13.10 Self Assessment Questions and Exercises
13.11 Further Readings
UNIT 14 AWT CLASSES AND WORKING WITH GRAPHICS 266-284
14.0 Introduction
14.1 Objectives
14.2 Introducing Abstract Window Toolkit
14.2.1 Component Class
14.2.2 Container Class
14.3 Working with Graphics
14.3.1 Using Graphics Class
14.3.2 Using Color Class
14.3.3 Using Font Class
14.3.4 Using Image Class
14.4 Answers to Check Your Progress Questions
14.5 Summary
14.6 Key Words
14.7 Self Assessment Questions and Exercises
14.8 Further Readings
Introduction
INTRODUCTION

Java was developed by a group of engineers at Sun Microsystems Inc. in l991


and is one of the most popularly used programming languages. The need to create NOTES
a language that is architecture neutral led to the development of Java. This concept
allows Java users across the world to execute software applications developed in
java under different environments. With this concept of platform independence
gaining popularity, the use of Java for developing the Internet applications has
increased considerably. The Internet users across the world cover a wide range of
platforms that includes Windows, Linux and UNIX. At the same time, developing
a language that caters to the need of all segments of the Internet users, based on a
single language, was one of the major challenges among the developers. Java is
widely used in various ways ranging from application software to Web applications.
It is a general purpose, class based and object oriented language that is specifically
designed to have the least number of implementation dependencies possible. All
these features led to the process of using it as the language for the Internet. It also
supports various Internet protocols and Web services, and is used for all applications
of the Internet. Java inherited most of the concepts and fundamentals from
languages, such as C and C++. It is also an Object Oriented Programming (OOP)
language. The inheritance of OOPs and programming concepts helped in the early
conception of Java by C and C++ users. In addition, Java allows developers to
create two types of programs: applications and applets. Applications are programs
that run on the user operating system and perform tasks based on the input provided
by the user and the processing logic defined by the programmer. Applets are small
applications that can be transmitted over the internet and are executed on the user
computer by using the java compatible web browser.
Besides the need to develop a language that can be distributed over the
Internet, there was a need to make the language secure and robust before
distribution. Each time a program is downloaded from the Internet; there is high
probability that the downloaded program is infected with a virus. Another challenge
for developers was to ensure that any application developed in Java language
maintained integrity of personal information entered by the user on web based
forms. Use of java by programmers for web based applications proved to be a
boon, both in terms of security and robustness. Users can safely download
applications from the internet by using java applets without any fear of hackers
and virus attacks. The key feature that makes java both secure and portable is the
java bytecode. Bytecode is the optimized set of instructions that executes on the
java runtime environment known as Java Virtual Machine or JVM. In order to
execute Java on different environments, developers only need to ensure that JVM
can be implemented on different environments.

Self-Instructional
Material 11
Introduction Inheritance facilitates a class to acquire the properties and functionality of
another class. It also facilitates classes to reuse the existing code. Java provides an
approach known as interface as a convenient alternative to implement multiple
inheritance. A named collection of classes is known as a package. Any number of
NOTES related classes can be grouped into a single package. There are two types of
common errors which can arise in java programs, namely compile-time and run-
time errors. These errors in Java code can be detected and removed by exhaustive
testing and debugging. Java supports input and output of data through the classes
included in the java.io package. Applets are small java programs which are
specifically designed to be used over the Web. In other words, applets provide a
programmer to develop a full-featured multimedia application. Java applets are
used to create graphical and user-interactive applications. Java supports creation
of sockets and exchange information using different protocols through the classes
defined in java.net package. Other than the standalone applications and applets,
Java also allows the creation of distributed applications using the concept of RMI
(Remote Method Invocation).
This book, Advanced Java Programming, has been written in the self-
instructional mode or SIM format wherein each unit begins with an ‘Introduction’
to the topic, followed by an outline of the ‘Objectives’. The detailed content is
then presented in a simple and organized manner, interspersed with ‘Check Your
Progress’ questions to test the student’s understanding of the topics covered. A
‘Summary’ along with a list of ‘Key Words’ and a set of ‘Self Assessment Questions
and Exercises’ is provided at the end of each unit for effective recapitulation.

Self-Instructional
12 Material
Introduction to JDBC
BLOCK - I
INTRODUCTION

NOTES
UNIT 1 INTRODUCTION TO JDBC
Structure
1.0 Introduction
1.1 Objectives
1.2 JDBC: Overview
1.2.1 JDBC Drivers
1.2.2 Seven Steps to Create the JDBC Programs and Applications
1.3 JDBC Metadata API
1.4 A JDBC-Servlet Example
1.5 A JDBC-JSP Example
1.6 Answers to Check Your Progress Questions
1.7 Summary
1.8 Key Words
1.9 Self Assessment Questions and Exercises
1.10 Further Readings

1.0 INTRODUCTION

Nowadays you are using applications that are most preferably three–tier
applications, though n-tier architecture is the necessity nowadays. Database is an
essential part of this 3-tier architecture besides the presentation and business logics.
Differentiating the storage from the main application has various advantages over
traditional inbuilt database applications.
The web applications require database to store their data. Database is an
essential part of every good application be it a standalone application or a web
application. It is equally important for both. A good application is that which can
easily connect to database and retrieve the data in the format that user wants. In
this unit, you will learn about the database connectivity and Metadata function.

1.1 OBJECTIVES

After going through this unit, you will be able to:


 Understand database management system and its uses
 Discuss about Java Database Connectivity(JDBC) and its utility
 Explain the types of JDBC implementations
 Analyze the JDBC metadata API
Self-Instructional
Material 1
Introduction to JDBC
1.2 JDBC: OVERVIEW

A database is an organized collection of data and a schema that provides the data
NOTES structures to hold the data. A database is very essential, by the point of view of a
web application as it will store the data, the web application will deal with. There
are various types of databases that you can see and use for your web applications.
The most preferred one is the RDBMS (Relational Database Management System).
RDBMS supports organization of data in tuples (rows) or say in a table and
provides you the functionality to define the table characteristics independently of
the actual data you’re going to store into it.
A database management system (DBMS), such as Oracle (Oracle
Corporation, licensed), MySQL (Open Source) or PostgreSQL (Open Source),
is a software package that lets you CRUD activities on both- items of data and
elements of the schema. CRUD stands for Create, Retrieve, Update and Delete
Operations on the data.
So, dealing with database is not an easy task, you need to be able to
differentiate and understand the following three aspects about databases:
 The data it contains.
 The structure you impose on the data in order to CRUD it efficiently.
 The software that allows you to manipulate both the data itself and the
database structure (the DBMS).
You are working with databases; it means you are interacting with the
database management systems (DBMS) which can be one among the following
interactive modes:
(a) Command line interface (CLI),
(b) Using graphical user interfaces (GUIs)
(c) Programmatically through an API.
Most of the time, you use all the three methods, each for a different purpose
and need. The CLI is best enough for testing purposes and to start database with.
In contrast, the API is well suited in use in web application to interact with the
database to perform its tasks, and the GUI is used to validate the individual data
items or fix problems.
JDBC (Java Database Connectivity) is a Java technology that empowers
you to connect to any existing relational database management systems, execute
SQL commands, and process the results, all from within a Java program. JDBC is
an application programming interface between Java programs and database

Self-Instructional
2 Material
management systems –a call level interface like Oracle call Interface (OCI). Call Introduction to JDBC

level Interface means making function calls to access the features unlike SQL
statements which need to be translated by a pre compiler. JDBC APIs lets your
application to connect to any database systems to store, process and retrieve the
data using a Java class known as a JDBC Driver. And there are hundreds of such NOTES
drivers existing to connect to a number of databases that are widely used. The real
benefit that you will get using JDBC is , with just minute changes in your program
can make it compatible to work with a hell lot of database like JDBC queries that
work on an Oracle database require little or no changes to work with DB2, or
SQL Server, or any other database. JDBC also helps in quick and easy transition
from legacy systems to Web-enabled applications.
Remember, JDBC is often mistaken as an acronym of Java Database
Connectivity. It is one of the J2EE compliant technology used for connecting your
java program with databases.
In this chapter you will go through the database connectivity with your
application, whatever be it-a standalone core java application or a web application
developed using JSP and Servlets.
1.2.1 JDBC Drivers
The JDBC API lets you access databases from Java application programs. There
are basically four types of JDBC implementations (i.e., drivers) according to the
nature of connections you will wish to establish with the database(s).
1. Type1: JDBC-ODBC Bridge Driver
JDBC drivers of type 1 are actually JDBC-ODBC bridges, because they access
databases via an Open Database Connectivity (ODBC) driver. Using ODBC
requires configuring your systems data Source Name (DSN) that will represent
the target database.
When you will use MS-Access as database source, you will need to use
this driver.
2. Type 2: Native API, Partly Java Driver
JDBC drivers of type 2 use vendor-specific, native, client-side libraries. In this the
JDBC API calls are converted into the native vendor specific, C/C++ API calls
that are unique to the databases. In other words, they act as interface to non-Java
functions provided by the DBMS vendor, which in turn act as interfaces to the
databases. These drivers are more efficient compared to those of type 1, but you
can only use them locally and hence not applicable for web applications.

Self-Instructional
Material 3
Introduction to JDBC The OCI (Oracle call Interface) driver is an example of this type.

NOTES

Fig. 1.1 Implementation of JDBC Type 2 and JDBC Type 4 Drivers which are the Most
Popular of all the JDBC Drivers

3. Type 3: JDBC-Net Pure Java Driver


JDBC drivers of type 3 are Java drivers that, instead of communicating directly
with the databases, rely on a middleware package that sits on an application server.
This type practically represents the implementation of all the above explained driver
types. When you want your application to be compatible to more than one type of
database then this is the type of driver you need.
4. Type 4: Native Protocol, Pure Java Driver
JDBC drivers of type 4 are written entirely in Java and communicate directly with
the DBMS server. Most of the time, this is the driver you need. This supports both
standalone and web applications. Example is MySQL connector/J Driver.
1.2.2 Seven Steps to Create the JDBC Programs and Applications
These are seven standard steps for querying databases. They have been briefly
explained below:
1. Load the JDBC driver. To load a driver, you must specify the classname
of the database driver in the Class.forName() method. By doing so, you
automatically create a driver instance and register it with the JDBC driver
manager.The syntax can be any one of the following according to the
database you choose:
try {
//you need to use any one from the followings:

Self-Instructional
4 Material
Class.forName(“connect.microsoft.MicrosoftDriver”);//for Introduction to JDBC
Microsoft DB2
Class.forName(“oracle.jdbc.driver.OracleDriver”);//for
Oracle Database
Class.forName(“com.sybase.jdbc.SybDriver”);//for Sybase NOTES
} catch(ClassNotFoundException cnfe) {
System.err.println(“Error loading driver: “ + cnfe);
}
Note: This method takes a string representing a fully qualified classname
(i.e., one that includes package names) and loads the corresponding class.
This call could throw a ClassNotFoundException, so it should be inside a
try/catch block.
You can place your JDBC driver file (JAR file) in the WEB-INF/lib directory
for deployment of your web application. However, the administrator may
choose to move the JAR file to a common library directory on the server.
2. Define the connection URL: In JDBC, a connection URL specifies the
server host, port, and database name with which to establish a connection.
It specifies the location of the database.
String host = “databasehost.yourcompany.com”;
String dbName = “someName”;
int port = 8033;//it can be anything that your server
works on.
//for Oracle database
String oracleURL = “jdbc:oracle:thin:@” + host + “:” +
port + “:” + dbName;

//for Sybase database


String sybaseURL = “jdbc:sybase:Tds:” + host + “:” + port
+ “:” + “?SERVICENAME=” + dbName;
//for MS-Access database
String msAccessURL = “jdbc:odbc:” + dbName;\\dbname=DSN
name.
3. Establish the connection. With the connection URL, username, and
password, a network connection to the database can be established. Once
the connection is established, database queries can be performed until the
connection is closed. The syntax is :
String username = “Oracle1”;
String password = “Oracle123”;
Connection connection=DriverManager.getConnection(oracleURL,
username,password);

Self-Instructional
Material 5
Introduction to JDBC 4. Create a statement object. Creating a Statement object enables you to
send queries and commands to the database.
String query = “ SELECT col1, col2, col3 FROM tableName”;
NOTES ResultSet resultSet = statement.executeQuery(query);
5. Execute a query or update. Given a Statement object, you can send
SQL statements to the database by using the execute, executeQuery,
executeUpdate, or executeBatch methods.
The following list summarizes commonly used methods in the Statement
class.
i. executeQuery(): Executes an SQL query and returns the data in a
ResultSet. The ResultSet may be empty, but never null.
ii. executeUpdate(): Used to execute UPDATE, INSERT, or DELETE
commands. Returns the number of rows affected, which could be
zero. Also provides support for Data Definition Language (DDL)
commands, for example, CREATE TABLE, DROP TABLE, and
ALTER TABLE.
iii. executeBatch(): Executes a group of commands as a unit, returning
an array with the update counts for each command. Use addBatch to
add a command to the batch group.
Note that vendors are not required to implement this method in their driver
to be JDBC compliant.
6. Process the results. When a database query is executed, a ResultSet is
returned. The ResultSet represents a set of rows and columns that you can
process by calls to next and various getXxx() methods like getInt() or
getString() methods.
Here is an example that prints the values of the first two columns and the
first name and last name, for all rows of a ResultSet.
while (resultSet.next()) {
System.out.println(resultSet.getString(1) + “ “ +
resultSet.getString(2) + “ “ +
resultSet.getString(“firstname”) + “ “
resultSet.getString(“lastname”));
}
Note: It is advised to use the column name instead of the column index
when you access the columns of a ResultSet. Why? So that, restructuring
the table does not affect the ResultSet that is to be retrieved.
7. Close the connection. When you are finished performing queries and
processing results, you should close the connection, releasing resources to
the database.

Self-Instructional
6 Material
To close the connection explicitly, you have to do: Introduction to JDBC

connection.close ();
Closing the connection also closes the corresponding Statement and
ResultSet objects. NOTES
You should postpone closing the connection if you expect to perform
additional database operations, since the overhead of opening a connection is
usually large.
JDBC 2.0 has provided some more flexibility. The main is the use of Java
Naming and Directory Interface (JNDI).An API that helps an application to look
up a Data Source object by name from a naming service, rather than hard-coding
driver class name and database URL in the program, thereby providing the flexibility
to port the database.
JDBC 2.0 result sets have more capabilities. The result set derived can be
accessed in random order rather than sequentially from start to finish. They can be
updated and have the updates propagated back to the underlying table.
Now you will see the implementation of these steps in the servlet and JSP
programs.

1.3 JDBC METADATA API

The JDBC API consists of two important interfaces that help in retrieving the
metadata information, they are: 1. DatabaseMetaData and 2. ResultSetMetaData.
The java.sql package houses these interfaces, you have to import the java.sql
package to use these ones. DatabaseMetaData interface is meant for retrieving
database information like its capabilities and structure while the ResultSetMetaData
interface is considered if you want to retrieve the information about SQL queries
like some specific information about its size and types of column used,etc. Let’s
get them in details as these are the key constituents of the package.
DatabaseMetaData
DatabaseMetaData interface is used for retrieving database information like its
capabilities and structure and this information is required by the database vendor.
So, it is implemented by the database vendor and provided along with the native
JDBC driver. Native JDBC drivers are built on top of the database. By
implementing this interface, database vendors provide comprehensive information
about the database as a whole, such as table name, indexes, product name, version,
and so forth. There are a number of methods declared in this interface to retrieve
various metadata information associated with the database.

Self-Instructional
Material 7
Introduction to JDBC Example 1.1: To illustrate the concept of Metadata interface.
package org.mano.example;

import java.sql.Connection;
NOTES
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseMetaDataDemo {

private static final String URL =


“jdbc:mysql://localhost:3306/addressbook?
zeroDateTimeBehavior=convertToNull”;
private static final String USERNAME = “testuser”;
private static final String PASSWORD = “secret”;

public static void main(String[] args) {


Connection conn = null;
DatabaseMetaData dbmd = null;
try {
conn = DriverManager.getConnection(URL,
USERNAME,
PASSWORD);
dbmd = conn.getMetaData();
if (dbmd != null) {
System.out.println(“Database Version: “ +
dbmd.getDatabaseProductVersion());
System.out.println(“Driver Name: “ +
dbmd.getDriverName());
System.out.println(“Driver Version: “ +
dbmd.getDriverVersion());
System.out.println(“URL: “ +
dbmd.getURL());
System.out.println(“User Name: “ +
dbmd.getUserName());
System.out.println(
(dbmd.supportsANSI92FullSQL() ?
“ANSI92FullSQL supported.” :
“ANSI92FullSQL not supported.”));
System.out.println(
(dbmd.supportsTransactions() ?
Self-Instructional
8 Material
“Transaction supported.” : Introduction to JDBC
“Transaction not supported.”));
} else {
System.out.println(“Metadata not supported”);
NOTES
}
} catch (SQLException ex1) {
System.err.println(ex1);
} finally {
try {
conn.close();
} catch (SQLException ex2) {

}
}
}
}
ResultSetMetaData
This interface provides metadata information about the structure of
the ResultSet object, such as finding out number of columns, its name, type and
length, table names, whether a column is readable/writable, searchable, and so
on.
Example 1.2: To illustrate the use of ResultSet object.
package org.mano.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class ResultSetMetaDataDemo {

private static final String URL =


“jdbc:mysql://localhost:3306/addressbook?
zeroDateTimeBehavior=convertToNull”;
private static final String USERNAME = “testuser”;
private static final String PASSWORD = “secret”;
private static final String SQL =
“SELECT * FROM Addresses”;
Self-Instructional
Material 9
Introduction to JDBC
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
NOTES
ResultSet rs = null;
ResultSetMetaData rsmd = null;

try {
conn = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
rsmd = rs.getMetaData();

if (rsmd != null) {
int cols = rsmd.getColumnCount();
System.out.println(“Number of Columns: “ +
cols);
System.out.println(“Table Name: “ +
rsmd.getTableName(1));
System.out.println(“Catalog Name: “ +
rsmd.getCatalogName(1));
System.out.println
(“—————————————————————”);
for (int i = 1; i <= cols; i++) {
System.out.println(“Class Name: “ +
rsmd.getColumnClassName(i));
System.out.println(“Column Name: “ +
rsmd.getColumnName(i));
System.out.println(“Column Type Name: “ +
rsmd.getColumnTypeName(i));
System.out.println
(“———————————————————”);
}
} else {
System.out.println(“ResultSetMetadata not
supported”);
}

} catch (SQLException ex1) {


System.err.println(ex1);
Self-Instructional
10 Material
} finally { Introduction to JDBC
try {
stmt.close();
rs.close();
NOTES
conn.close();
} catch (SQLException ex2) {

}
}
}
}
ParameterMetaData
ParameterMetadata objects are used to retrieve information about the parameter
markers in a PreparedStatement object. The metadata information refers to the
types and properties of the parameter used, such as getting the fully qualified Java
class name, parameter count, its types, designated precision specified by the column
size, and the like.
Example 1.3: To illustate the use of ParameterMetaData objects.
package org.mano.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ParameterMetaDataDemo {

private static final String URL = “jdbc:mysql://


localhost:3306/
addressbook?zeroDateTimeBehavior=convertToNull”;
private static final String USERNAME = “testuser”;
private tatic final String PASSWORD = “secret”;
private static final String SQL = “SELECT id, firstName,
lastName
FROM Addresses WHERE id=? AND firstName LIKE ?”;

public static void main(String[] args) {

Connection conn = null;


Self-Instructional
Material 11
Introduction to JDBC PreparedStatement pstmt = null;
ParameterMetaData pmd = null;

try {
NOTES
conn = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
pstmt = conn.prepareStatement(SQL);
pmd = pstmt.getParameterMetaData();
if (pmd != null) {
System.out.println(“Parameter Count: “ +
pmd.getParameterCount());
} else {
System.out.println(“ParameterMetadata not
supported by the database”);
}

catch (SQLException ex1) {


System.err.println(ex1);
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException ex2) {

}
}
}
}
RowSetMetaData
The RowSetMetaData interface is a part of the javax.sql package and is a sub-
implementation of the ResultSetMetaData interface. An object of this class provides
information about columns in a RowSetobject. The RowSet interface provides
support for the JDBC API for JavaBeans component model. As a result, it has
properties and supports the technique of JavaBeans event notification.
RowSetMetadataprovides the information about the columns in a RowSet object
and can be used to find out about the number of columns contained in a rowset or
the type of data each column contains. It is crucial to understand the working
mechanism of the RowSet object to fully appreciate the use of RowSetMetaData.
Delineating the rowset mechanism is outside the scope of this article; however,
readers may refer the article “Working with the JDBC RowSet API” to get an
Self-Instructional
12 Material
idea of the Rowset API. However, this is not going to stop us from getting a glimpse Introduction to JDBC

of RowSetMetaData in action.
Example 1.4: Showing the use of RowSetMetaData interface.
package org.mano.example; NOTES

import java.sql.SQLException;

import javax.sql.RowSetMetaData;
import javax.sql.rowset.WebRowSet;

import com.sun.rowset.WebRowSetImpl;

public class RowSetMetaDataDemo {

private static final String URL = “jdbc:mysql://


localhost:3306/
addressbook?zeroDateTimeBehavior=convertToNull”;
private static final String USERNAME = “testuser”;
private static final String PASSWORD = “secret”;
private static final String SQL = “SELECT * FROM
Addresses”;

public static void main(String[] args) {


WebRowSet rowSet = null;
RowSetMetaData rsmd = null;

try {
Class.forName(“com.mysql.jdbc.Driver”);
rowSet = new WebRowSetImpl();
rowSet.setUrl(URL);
rowSet.setUsername(USERNAME);
rowSet.setPassword(PASSWORD);
rowSet.setCommand(SQL);
rowSet.execute();

rsmd = (RowSetMetaData) rowSet.getMetaData();


if (rsmd != null) {

int count = rsmd.getColumnCount();


for (int i = 1; i <= count; i++)

Self-Instructional
Material 13
Introduction to JDBC System.out.println(“Column Name: “ +
rsmd.getColumnName(i) +
“ Type: “ + rsmd.getColumnTypeName(i));
} else {
NOTES
System.out.println(“RowSetMetadata not
supported”);
}

} catch (ClassNotFoundException | SQLException ex1)


{
System.err.println(ex1);
} finally {
try {
rowSet.close();
} catch (SQLException ex2) {

}
}
}
}
JDBC Metadata APIs are indispensable for creating most commercial
database applications. They are particularly useful for creating customized database
solutions such as generating a GUI-based data browser application. For example,
one can create dynamic a GUI-based table structure according to the metadata
information retrieved from the database. Refer to the Java API documentation for
more information on the APIs and their functionality.

Check Your Progress


1. What is a database?
2. What do JDBC APIs help the application with?

1.4 A JDBC-SERVLET EXAMPLE

Example of Database Program using a Servlet and MS-Access


All the necessary steps have already been mentioned and you might have thoroughly
gone through those for better understanding. Here you will find a servlet which will
connect to the oracle database and display the database content in some table
form. You will find it easy to implement as all the required things have been explained
the following:
Self-Instructional
14 Material
1. Files Required Introduction to JDBC

1. index.html- the front controller of the application ,from here the table name
is taken from the user whose data he wants to view.
2. ServletJdbcOracleConnect.java – The business logic that will contain NOTES
the method of retrieving the data from the table and also display it in certain
form like a table.
3. web.xml- the deployment descriptor for the web application .
2. Prerequisites
(a) Set the classpath to servlet-api.jar so that the servlet can be compiled.
(b) Create the DSN named as “vph” and associate an MS-Access file with it
which will work as the repository here.
(c) Create the web application folder and use the directory structure to put the
files in appropriate folders.
Once you are set with all the above prerequisites, compile the servlet and
place the .class file in the classes folder in WEB-INF folder. Place all other files
properly in their respective folders. Finally deploy the application on the server
and run using the appropriate URL.
ServletJdbcOracleConnect.java
import java.io.*;
import java.sql. *;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletJdbcOracleConnect extends HttpServlet

{
p ro tect ed vo id d oPos t (H t t pS er v l et Re qu e st
req,HttpServletResponse res)throws ServletException,
IOException
{
PrintWriter pw=res.getWriter();
res.setContentType(“text/html”);
String tb=req.getParameter(“table”);
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Conne c tion con =D river M an ag er . g et Co nn e c tio n
(“jdbc:odbc:vph”,””,””);
Statement st=con.createStatement();

Self-Instructional
Material 15
Introduction to JDBC System.out.println(“connection established
successfully...!!”);
ResultSet rs=st.executeQuery(“Select * from “+tb);
pw.println(“<table border=1>”);
NOTES while(rs.next())
{
pw.println(“<tr><td>”+rs.getString(1)+”</
t d > < t d > ” + r s . g e t S t r i n g ( 2 ) + ” < /
td>”+”<td>”+rs.getString(3)+”</td></tr>”); }
pw.println(“</table>”);
pw.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
Example of Database Program using Servlet and Oracle Database
The basic steps have already been discussed while explaining about the Servlet
and MS Access database connectivity. You are advised to follow the initial steps
as they are except the making of the DSN. An additional step that you need to
follow here is:
1. Set the classpath of servlet-api.jar or else your servlet will not compile.
2. Just remember to set the classpath to ojdbc14.jar and ojdbc14_g.jar
file and also copy only ojdbc14.jar in the lib folder of Tomcat.
(a) The servlet will use ojdbc14.jar file which is in the classpath, for
compiling the application,
(b) ojdbc14.jar file in lib folder will be used at the time of running the
servlet application by the server.
index.html
<Html>
<head><title>Servlet-JDBC Example</title></head>
<body>
<form action=”JdbcShow” method=”post”>
Enter Table Name : <input type=”text” name=”table”>
<input type=”submit” value=”Display”>
</form>
</body>
</html>
Self-Instructional
16 Material
ServletJdbcOracleConnect.java Introduction to JDBC

import java.io.*;
import java.sql. *;
import javax.servlet.*; NOTES
import javax.servlet.http.*;
public class ServletJdbcOracleConnect extends HttpServlet

{
p ro tect ed vo id d oPos t (H t t pS er v l et Re qu e st
req,HttpServletResponse res)throws ServletException,
IOException
{
PrintWriter pw=res.getWriter();
res.setContentType(“text/html”);
String tb=req.getParameter(“table”);
try
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection con=DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:XE”,”system”,”admin”);
Statement st=con.createStatement();
System.out.println(“connection established
successfully...!!”);
ResultSet rs=st.executeQuery(“Select * from “+tb);
pw.println(“<table border=1>”);
while(rs.next())
{
pw.println(“<tr><td>”+rs.getString(1)+”</
t d > < t d > ” + r s . g e t S t r i n g ( 2 ) + ” < /
td>”+”<td>”+rs.getString(3)+”</td></tr>”); }
pw.println(“</table>”);
pw.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
web.xml
<web-app>
<servlet>
Self-Instructional
Material 17
Introduction to JDBC <servlet-name>ServletDBConnect</servlet-name>
<servlet-class> ServletJdbcOracleConnect </servlet-
class>
</servlet>
NOTES <servlet-mapping>
<servlet-name>ServletDBConnect</servlet-name>
<url-pattern>/JdbcShow</url-pattern>
</servlet-mapping>
</web-app>

1.5 A JDBC-JSP EXAMPLE

Example of Database Program using JSP and MS-Access


Here we will now discuss two examples
1. JdbcInsert.jsp for insert operation
2. JdbcUpdate.jsp for updating record in the database.
Here, you will use the testing method i.e. using the type 2 JDBC-ODBC
bridge drivers implementation for connecting the JSP program with MS-ACESS
using DSN name “vph”. And you should have an MS-Access file containing the
following information in table as following columns: userid, password, sname,
eid, addr. Insert some test data also so that you don’t get confused about not
getting the result from the database.
JdbcInsert.jsp
<%@page import=”java.sql.*” pageEncoding=”UTF-8"
contentType=”text/html”%>
<html> <head>
<title>JDBC connectivity with JSP</title> </
head>
<body>
<%
String usrid=request.getParameter(“userid”);
String pwd=request.getParameter(“password”);
String nam=request.getParameter(“sname”);
String eid=request.getParameter(“eid”);
String addres=request.getParameter(“addr”);
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Conne cti o n co n= Dr iv er Ma n ag er.g etC o nne ctio n
(“jdbc:odbc:vph”,””,””);
Self-Instructional
18 Material
/* Passing argument through the question mark */ Introduction to JDBC
PreparedStatement ps=con.prepareStatement(“insert into
login values(?,?,?,?,?)”) ;
ps.setString(1,usrid);
ps.setString(2,pwd); NOTES
ps.setString(3,nam);
ps.setString(4,addres);
ps.setString(5,eid);
int i=ps.executeUpdate(); /*Set the Update query
command */
if(i!=0)
{
response.sendRedirect(“index.jsp?msg=Thank You for
registering !”);
}
else
{
response.sendRedirect(“JdbcInsert.jsp?msg=Insertion
Failed!! “);
}
con.close();
}
catch(Exception ex)
{
out.println(ex);
}
%>
</body>
</html>
Code Explanation
The above code is used to insert record in to the database by accessing data from
the entry form. The PreparedStatement is used to pass the DML insert command
to store the record in the database. Now, you will set the string at the particular
database filed. This is the update program that is used to update existing records
in the database. Once the database entry is updated, you are redirected to the
index.jsp page, the front-controller page or else it is redirected to the JdbcInsert.jsp
page.
JdbcUpdate.jsp
<%@page contentType=”text/html”%>
<%@page pageEncoding=”UTF-8"%>
<%@ page import=”java.sql.*” %> Self-Instructional
Material 19
Introduction to JDBC <html>
<head>
<title>JSP Update Page</title>
</head>
NOTES
<body>
<%
String uid=(String)session.getAttribute(“userid”);
String p=request.getParameter(“password1”);
String n=request.getParameter(“name1”);
String e=request.getParameter(“eid”);
String a=request.getParameter(“address”);
try{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection
con=DriverManager.getConnection(“jdbc:odbc:vph”,””,””);
PreparedStatement ps=con.prepareStatement(“update
login set password1=?,name1=?,eid=?,address=? where
userid=?”);
ps.setString(1,p);
ps.setString(2,n);
ps.setString(3,e);
ps.setString(4,a);
ps.setString(5,uid);
int i=ps.executeUpdate();
if(i!=0)
{
response.sendRedirect(“index.jsp?msg=
Profile Updated Successfully!”);
}
else
{
response.sendRedirect(“pUpdate.jsp?msg=
ProfileUpdationFailed.PleaseTryagain!!!!”);
}
con.close();
}
catch(Exception ex){
out.println(ex);
}
%>
</body>
</html>
Self-Instructional
20 Material
Example of Database Program using JSP and Oracle Introduction to JDBC

Here we will now discuss two examples.


1. JdbcInsert.jsp for insert operation
2. JdbcUpdate.jsp for updating record in the database. NOTES

Here, you will use the testing method i.e. using the type 1 JDBC-ODBC
bridge drivers implementation for connecting the JSP program with MS-ACESS
using DSN name “vph”. And you should have an MS-Access file containing the
following information in table as following columns: userid, password, sname,
eid, addr. Insert some test data also so that you don’t get confused about not
getting the result from the database.
JdbcInsert.jsp
<%@page import=”java.sql.*” pageEncoding=”UTF-8"
contentType=”text/html”%>
<html> <head>
<title>JDBC connectivity with JSP</title> </
head>
<body>
<%
String usrid=request.getParameter(“userid”);
String pwd=request.getParameter(“password”);
String nam=request.getParameter(“sname”);
String eid=request.getParameter(“eid”);
String addres=request.getParameter(“addr”);
try
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connectioncon=DriverManager.getConnection(“jdbc:
oracle:thin:@localhost:1521:XE”,”system”,”admin”
);
/* Passing argument through the question mark */
PreparedStatement ps=con.prepareStatement(“insert into
login values(?,?,?,?,?)”) ;
ps.setString(1,usrid);
ps.setString(2,pwd);
ps.setString(3,nam);
ps.setString(4,addres);
ps.setString(5,eid);
int i=ps.executeUpdate(); /*Set the Update query
command */
if(i!=0)
Self-Instructional
Material 21
Introduction to JDBC {
response.sendRedirect(“index.jsp?msg=Thank You for
registering !”);
}
NOTES else
{
response.sendRedirect(“JdbcInsert.jsp?msg=Insertion
Failed!! “);
}
con.close();
}
catch(Exception ex)
{
out.println(ex);
}
%>
</body>
</html>
Code Explanation
The above code is used to insert record in to the database by accessing data from
the entry form. You should notice the changes made in the Class.forName() method
and the Connection class here.They have now the drivers specific to Oracle databse.
The PreparedStatement is used to pass the DML insert command to store the
record in the database. Now, you will set the string at the particular database filed.
This is the update program that is used to update existing records in the database.
Once the database entry is updated, you are redirected to the index.jsp page, the
front-controller page or else it is redirected to the JdbcInsert.jsp page.
JdbcUpdate.jsp
<%@page contentType=”text/html”%>
<%@page pageEncoding=”UTF-8"%>
<%@ page import=”java.sql.*” %>
<html>
<head>
<title>JSP Update Page</title>
</head>
<body>
<%
String uid=(String)session.getAttribute(“userid”);
String p=request.getParameter(“password1”);

Self-Instructional
22 Material
String n=request.getParameter(“name1”); Introduction to JDBC
String e=request.getParameter(“eid”);
String a=request.getParameter(“address”);
try{
NOTES
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection con=DriverManager. getConnection
(“jdbc:oracle:thin:@localhost:1521:XE”, ”system”,”admin”
);
PreparedStatement ps=con.prepareStatement(“update
login set password1=?,name1=?,eid=?,address=? where
userid=?”);
ps.setString(1,p);
ps.setString(2,n);
ps.setString(3,e);
ps.setString(4,a);
ps.setString(5,uid);
int i=ps.executeUpdate();
if(i!=0)
{
response.sendRedirect(“index.jsp?msg=
Profile Updated Successfully!”);
}
else
{
response.sendRedirect(“pUpdate.jsp?msg=
ProfileUpdationFailed.PleaseTryagain!!!!”);
}
con.close();
}
catch(Exception ex){
out.println(ex);
}
%>
</body>
</html>

Check Your Progress


3. What is the PreparedStatement used for?
4. What are JDBC Metadata APIs used for?

Self-Instructional
Material 23
Introduction to JDBC
1.6 ANSWERS TO CHECK YOUR PROGRESS
QUESTIONS

NOTES 1. A database is an organized collection of data and a schema that provides


the data structures to hold the data.
2. JDBC APIs lets your application to connect to any database systems to
store, process and retrieve the data using a Java class known as a JDBC
Driver.
3. The PreparedStatement is used to pass the DML insert command to store
the record in the database.
4. JDBC Metadata APIs are indispensable for creating most commercial
database applications.

1.7 SUMMARY

 A database is an organized collection of data and a schema that provides


the data structures to hold the data.
 A database is very essential, by the point of view of a web application as it
will store the data, the web application will deal with.
 There are various types of databases that you can see and use for your web
applications.
 A database management system (DBMS), such as Oracle (Oracle
Corporation, licensed), MySQL (Open Source) or PostgreSQL (Open
Source), is a software package that lets you CRUD activities on both-
items of data and elements of the schema.
 Most of the time, you use all the three methods, each for a different purpose
and need. The CLI is best enough for testing purposes and to start database
with.
 JDBC (Java Database Connectivity) is a Java technology that empowers
you to connect to any existing relational database management systems,
execute SQL commands, and process the results, all from within a Java
program.
 JDBC APIs lets your application to connect to any database systems to
store, process and retrieve the data using a Java class known as a JDBC
Driver.
 The real benefit that you will get using JDBC is , with just minute changes in
your program can make it compatible to work with a hell lot of database
like JDBC queries that work on an Oracle database require little or no
changes to work with DB2, or SQL Server, or any other database.
Self-Instructional
24 Material
 The JDBC API lets you access databases from Java application programs. Introduction to JDBC

JDBC drivers of type 1 are actually JDBC-ODBC bridges, because they


access databases via an Open Database Connectivity (ODBC) driver.
 JDBC drivers of type 2 use vendor-specific, native, client-side libraries. In
NOTES
this the JDBC API calls are converted into the native vendor specific, C/
C++ API calls that are unique to the databases. In other words, they act as
interface to non-Java functions provided by the DBMS vendor, which in
turn act as interfaces to the databases.
 JDBC drivers of type 3 are Java drivers that, instead of communicating
directly with the databases, rely on a middleware package that sits on an
application server.
 JDBC drivers of type 4 are written entirely in Java and communicate directly
with the DBMS server.
 To load a driver, you must specify the classname of the database driver in
the Class.forName() method.
 With the connection URL, username, and password, a network connection
to the database can be established.
 The JDBC API consists of two important interfaces that help in retrieving
the metadata information, they are 1. DatabaseMetaData and
2. ResultSetMetaData.
 DatabaseMetaData interface is used for retrieving database information like
its capabilities and structure and this information is required by the database
vendor.
 ParameterMetadata objects are used to retrieve information about the
parameter markers in a PreparedStatement object.
 The RowSetMetaData interface is a part of the javax.sql package and is a
sub-implementation of the ResultSetMetaData interface.
 JDBC Metadata APIs are indispensable for creating most commercial
database applications.
 All the necessary steps have already been mentioned and you might have
thoroughly gone through those for better understanding.
 The PreparedStatement is used to pass the DML insert command to store
the record in the database.

1.8 KEY WORDS

 executeQuery(): It executes an SQL query and returns the data in a


ResultSet. The ResultSet may be empty, but never null.
 executeUpdate(): It is used to execute UPDATE, INSERT, or DELETE
commands. Returns the number of rows affected, which could be zero.
Self-Instructional
Material 25
Introduction to JDBC Also provides support for Data Definition Language (DDL) commands,
for example, CREATE TABLE, DROP TABLE, and ALTER TABLE.
 executeBatch(): It executes a group of commands as a unit, returning an
array with the update counts for each command. Use addBatch to add a
NOTES
command to the batch group.

1.9 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short-Answer Questions
1. What is database management system and what is it used for?
2. Discuss about Java Database Connectivity and its utility.
3. Discuss the types of JDBC implementations.
4. What do you mean by JDBC metadata API?
Long-Answer Questions
1. “JDBC (Java Database Connectivity) is a Java technology that empowers
you to connect to any existing relational database management systems,
execute SQL commands, and process the results, all from within a Java
program.” Explain in detail.
2. Explain in detail about JDBC drivers and its types.
3. How are of JDBC Type 2 and JDBC Type 4 drivers implemented? Also
tell which are the most popular of all the JDBC Drivers? Support your
answer with an illustration from the text.

1.10 FURTHER READINGS

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
26 Material
SQL Exception

UNIT 2 SQL EXCEPTION AND and Warning

WARNING
NOTES
Structure
2.0 Introduction
2.1 Objectives
2.2 SQL Exception and SQL Warning Concepts
2.2.1 Exception Retrieval
2.2.2 Introduction to SQL Warning
2.2.3 Special SQL Exceptions
2.3 Answers to Check Your Progress Questions
2.4 Summary
2.5 Key Words
2.6 Self Assessment Questions and Exercises
2.7 Further Readings

2.0 INTRODUCTION

In this unit, you will learn about the exceptions and warning in SQL. An exception
is an error condition that occurs during a program execution. SQL supports
programmers to catch such conditions using exception block in the program. It
also helps take an appropriate action against the error condition. Exceptions are
raised by the database server automatically whenever there is any internal database
error, but exceptions can be raised explicitly by the programmer too.

2.1 OBJECTIVES

After going through this unit, you will be able to:


 Know and Understand about the basics of SQL exception
 Understand how to retrieve exceptions
 Understand some specially categorized SQL exceptions

2.2 SQL EXCEPTION AND SQL WARNING


CONCEPTS

If JDBC finds it unable to be interactive with a data source, it responds back by


generating an error. And hence throws an instance of SQL exception unlike a normal
exception object. The SQL exception instance consists of the some information

Self-Instructional
Material 27
SQL Exception that can be used for considering and isolating the root cause of the error occurrence.
and Warning
The information isolated is:
 An error description: The error description is contained within the
String object that is retrieved by calling SQLException.getMessage()
NOTES
method.
 A SQLState code: A SQLState code is a String object that consists of
total 5 alphanumeric characters. It is recovered by calling the method
SQLException.getSQLState()..
 An error code: An error code is an integer value used in the identification
of the error that actually initiated the SQLException instance to be thrown.
Retrieval of the error can be done by just calling the method
SQLException.getErrorCode().
 A cause: Sometimes you might be interested in finding the causal relation
consisting one or more Throwable objects probably that might have caused
the SQLException instance to be thrown. SO, to navigate this chain of
causes, getCause() method is to be used recursively until you get a null
value.GetCause() method belong to the SQLException class.
 A reference to any chained exceptions: Retrieval of the chained
exceptions can be done by calling the SQLException.getNextException()
method on the exception that was thrown.
2.2.1 Exception Retrieval
Use the method printSQLException() to display the error information .The
information that gets displayed consists of the followings - SQLState, error code,
error description, and the cause if there exists any and any other exception that is
cause a result, in the chain.
public static void printSQLException(SQLException ex) {

for (Throwable e : ex) {


if (e instanceof SQLException) {
if (ignoreSQLException(
((SQLException)e).
getSQLState()) == false) {

e.printStackTrace(System.err);
System.err.println(“SQLState: “ +
((SQLException)e).getSQLState());

System.err.println(“Error Code: “ +
((SQLException)e).getErrorCode());
System.err.println(“Message: “ + e.getMessage());
Self-Instructional
28 Material
SQL Exception
and Warning
Throwable t = ex.getCause();
while(t != null) {
System.out.println(“Cause: “ + t);
NOTES
t = t.getCause();
}
}
}
}
}
For example, if you call the method CoffeesTable.dropTable with Java DB
as your DBMS, the table COFFEES does not exist, and you remove the call
to JDBCTutorialUtilities.ignoreSQLException, the output will be similar to the
following:
SQLState: 42Y55
Error Code: 30000
Message: ‘DROP TABLE’ cannot be performed on
‘TESTDB.COFFEES’ because it does not exist.
Instead of outputting SQLException information, you could instead first
retrieve the SQLState then process the SQLException accordingly. For example,
the method JDBCTutorialUtilities.ignoreSQLException returns true if
the SQLState is equal to code 42Y55 (and you are using Java DB as your DBMS),
which causes JDBCTutorialUtilities.printSQLException to ignore
the SQLException:
public static boolean ignoreSQLException(String sqlState)
{
if (sqlState == null) {
System.out.println(“The SQL state is not defined!”);
return false;
}

// X0Y32: Jar file already exists in schema


if (sqlState.equalsIgnoreCase(“X0Y32”))
return true;

// 42Y55: Table already exists in schema


if (sqlState.equalsIgnoreCase(“42Y55”))
return true;
return false;
}
Self-Instructional
Material 29
SQL Exception 2.2.2 Introduction to SQL Warning
and Warning
Warnings can be used to just alert and inform the user without halting the execution
of the application when something intended has not happened. While Exceptions
NOTES just halt the execution of the application warnings don’t. While dealing with
database, you may fall prey to some uncontrolled access conditions, for that you
can use the SQLWarning objects. SQLWarning class inherits the SQLException
class.
When a warning is generated its object consists of the following: objects of
interfaces like Connection interface, a Statement interface and/or
a ResultSet interface object. If you wish to see the warning that was first reported,
then just invoke a getWarnings() method. If getWarnings() returns a warning, then
you must call the getNextWarning() method to get any other additional warnings,
if there is any. The following methods illustrate how to get complete information
about any warnings reported on Statement or ResultSet objects:
public static void getWarningsFromResultSet(ResultSet rs)
throws SQLException {
JDBCTutorialUtilities.printWarnings(rs.getWarnings());
}

public static void getWarningsFromStatement(Statement


stmt)
throws SQLException {
JDBCTutorialUtilities.printWarnings(stmt.getWarnings());
}

public static void printWarnings(SQLWarning warning)


throws SQLException {

if (warning != null) {
System.out.println(“\n—Warning—\n”);

while (warning != null) {


System.out.println(“Message: “ + warning.getMessage());
System.out.println(“SQLState: “ + warning.getSQLState());
System.out.print(“Vendor error code: “);
System.out.println(warning.getErrorCode());
System.out.println(“”);
warning = warning.getNextWarning();
}
}

Self-Instructional
30 Material
One of the most common of all the warnings you might encounter is the SQL Exception
and Warning
DataTruncation warning, which inherits the SQLWarning class. What is more
common in all the DataTruncation objects is that they have a SQLState of 01004,
which is for depicting the problem regarding reading or writing data in
database. Using the DataTruncation methods you can easily find out in which NOTES
column or parameter data got truncated, state of the transaction whether on a
read or write operation, total number of bytes transferred, etc.
2.2.3 Special SQL Exceptions
While dealing with JDBC operations, sometimes you may fall upon the subclass
of SQLException that might be corresponding to a common SQLState or some
common error state which is not associated with any specific SQLState class
value. These are special SQLExceptions and can be the sub class of any one
amongst the followings classes: SQLNonTransientException class,
SQLTransientException class, or SQLRecoverableException class. Understanding
of these may enable you to code more portable error-handling codes for your
applications.
Some more Subclasses of SQL Exception
Apart from the ones mentioned above, there a few more special ones, some
subclasses of SQLException that can also be seen thrown in the application:
 BatchUpdateException is thrown when there occurs any error during a
batch update operation providing the exception information as provided
by SQLException, and also total number of the update counts for all
statements that were successfully executed before the error occurred during
the update.
 When one or more client information properties could not be set on
Connection, then an exception is thrown- SQLClientInfoException .
SQLClientInfoException consists of a list of client information properties
and some basic exception information provided by SQLException .

Check Your Progress


1. What are SQLWarning objects used for?
2. What does the warning object consist of?

2.3 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. SQLWarning objects are used to take care of all the database access
warnings to be displayed.
Self-Instructional
Material 31
SQL Exception 2. When a warning is generated its object consists of the following: objects of
and Warning
interfaces like Connection interface, a Statement interface and/or
a ResultSet interface object.

NOTES
2.4 SUMMARY

 Whenever JDBC is unable to interact with a data source, it results in an


error and hence throws an instance of SQL Exception as opposed
to Exception.
 The String object is retrieved that contains this detailed description.
 This String object consists of five alphanumeric characters and is retrieved
by calling the method SQLException.getSQLState.
 This is an integer value that basically helps in the identification of the error
that initiated the SQLException instance to be thrown.
 There might exist a causal relation consisting one or more Throwable objects
that caused the SQLException instance to be thrown.
 If there is an occurrence of more than one error, then the exceptions are
referenced through this chain.
 Instead of outputting SQLException information, you could instead first
retrieve the SQLState then process the SQLException accordingly.
 When you want to just alert the user about that something did not happen
as planned without stopping the execution of the application, then you simply
use warnings.
 SQLWarning objects are used to take care of all the database access
warnings to be displayed and it is a subclass of SQLException.
 If getWarnings() returns a warning, then need to call the getNextWarning()
method to get any further additional warnings.
 DataTruncation warning,is one the common warnings implemented, it is a
subclass of SQLWarning.
 The JDBC driver might throw a subclass of SQLException corresponding
to a common SQLState or some common error state that is not anywhere
associated with a specific SQLState class value. This enables you to write
more portable error-handling code.
 If an error occurs during a batch update operation then
BatchUpdateException is thrown which provides the information about the
exception provided by SQLException, and total number of the update
counts for all statements that were executed before the error occurred.
 SQLClientInfoException is thrown when one or more client information
properties could not be set on a Connection.
Self-Instructional
32 Material
SQL Exception
2.5 KEY WORDS and Warning

 Error Description: The String object is retrieved that contains this detailed
description. This is done by calling the method SQLException.getMessage(). NOTES
 SQLState Code: It is a String object that consists of five alphanumeric
characters and is retrieved by calling the method
SQLException.getSQLState.
 Error Code: This is an integer value that basically helps in the identification
of the error that initiated the SQLException instance to be thrown.

2.6 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short-Answer Questions
1. What do you understand by SQL exception?
2. Write a short note to analyze the SQL warning.
3. Discuss some specially categorized SQL exceptions.
Long-Answer Questions
1. “Whenever JDBC is unable to interact with a data source, it results in an
error and hence throws an instance of SQL Exception as opposed to
Exception.” Discuss.
2. What are SQL Warnings? When are they used? Explain in detail.
3. “The JDBC driver might throw a subclass of SQLException corresponding
to a common SQLState or some common error state that is not anywhere
associated with a specific SQLState class value.” Discuss.

2.7 FURTHER READINGS

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
Material 33
JDBC Classes and
Statements
UNIT 3 JDBC CLASSES AND
STATEMENTS
NOTES
Structure
3.0 Introduction
3.1 Objectives
3.2 The java.sql Package
3.2.1 The DriverManager Class
3.2.2 The Connection Interface
3.2.3 The Statement Interface
3.2.4 The ResultSet Interface
3.2.5 The PreparedStatement Interface
3.2.6 The ResultSetMetaData Interface
3.2.7 The CallableStatement Interface
3.2.8 The SQLException Class
3.3 Answers to Check Your Progress Questions
3.4 Summary
3.5 Key Words
3.6 Self Assessment Questions and Exercises
3.7 Further Readings

3.0 INTRODUCTION

The JDBC interface is contained in the java.sql and javax.sql packages. You must
import these packages in your programs if you want to use database to store its
data. It consists mainly of interfaces rather than concrete classes as each vendor’s
implementation is different rather say specific to their particular database protocol.
In this unit, you will study about JDBC classes, statements and interfaces.

3.1 OBJECTIVES

After going through this unit, you will be able to:


 Discuss the methods of the DriverManager Class and Connection
interface
 Discuss about the statement and ResultSet interface
 Understand PreparedStatement interface
 Understand callableStatement interface
 Explain the various methods of SQLException class

Self-Instructional
34 Material
JDBC Classes and
3.2 THE JAVA.SQL PACKAGE Statements

To work with the database, Java provides java.sql package. It contains


various classes and interfaces that can be used for establishing connection with NOTES
database and retrieve data from it.
It provides API for processing data stored in database. This section discusses
one of the important class DriverManager and some of the important interfaces
included in this package.
3.2.1 The DriverManager Class
The DriverManager class is responsible for loading the driver specific classes.
The drivers are registered with the DriverManager class either when an
instance of driver is created using registerDriver(Driver driver)
method of the DriverManager class or DriverManager class is initialized.
The static method forName() of the Class class can be used by
DriverManager class to locate and load the drivers listed in system variable
jdbc.drivers is as follows:
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”)
Here, the driver class specified in the string parameter is loaded dynamically
at the run time.
Some of the methods of the DriverManager are as follows:
 Connection getConnection(String url): This method
attempts to establish a connection to a given database URL—does not
require password.
 Connection getConnection(String url, String
user, String password): This method attempts to establish
a connection to a given database URL.
 Driver getDriver(String URL): It locates the driver that
identifies the given URL.
 void registerDriver(Driver driver): This method
is used to register a driver specified by driver with the
DriverManager.
 void deregisterDriver(Driver driver): This method
removes the driver specified by d r i v e r from the
DriverManager’s list.
 void setLogintimeout(int seconds): It sets the
maximum time a driver should wait while attempting to connect to the
database.

Self-Instructional
Material 35
JDBC Classes and  void setLogWriter(PrintWriter out): It sets
Statements
PrintWriter object that is used by all the drivers and
DriverManager.
 Boolean jdbcCompliant(): It returns True or False depending
NOTES
on whether this driver is a genuine JDBC CompliantTM driver.
 DriverPropertyInfo[] getPropertyInfo(String
url, Properties Info): It provides the information about
the possible properties for the current driver.
 int getMajorVersion(): It returns the major driver’s version
number.
 int getMinorVersion(): It returns the minor driver’s version
number.
3.2.2 The Connection Interface
The Connection interface helps to establish a connection with the required
database. Other than establishing connection, it provides lot of functionality including
transaction management, maintaining database sessions and creating SQL
statements. This interface does not provide its object with garbage collection rather
all the objects have to be closed explicitly or should themselves be garbage collected
and once the connection is closed no other request can be made for the database.
A Connection’s database is able to provide information about its tables, its SQL
grammar, the capabilities of this connection, stored procedures, and so on.
Some of the commonly used methods of connection interface are as follows:
 void close(): This method closes database connection associated
with Connection’s object and releases JDBC resources.
For example, consider this statement.
con.close();
where,
con is an instance of connection interface.
 Statement createStatement(): This method creates a
Statement object which is used to send SQL statement to the
database. It is usually used when SQL statement without parameters is
to be executed.
 void clearWarnings(): This method clears all the warnings
reported for the connection object.
 CallableStatement prepareCall(String sql):
This method creates an instance of CallableStatement which
is used to handle database stored procedures.

Self-Instructional
36 Material
 void commit(): It completes and makes all the changes made JDBC Classes and
Statements
since last commit or rollback permanent in database and releases all the
database lock held by the current connection.
 PreparedStatement prepareStatement(String
NOTES
sql): This method creates PreparedStatement object which
is used to create SQL statement specified in string sql. It is usually
used when parameterized SQL statement is to be executed.
 DatabaseMetaData getMetaData(): It retrieves the meta
data related to the current connection’s database.
 boolean isClosed(): It checks whether the connection is
closed.
 boolean getAutoCommit(): It retrieves the current auto
commit mode for the current connection object.
 void rollback(): It rollbacks all the changes made since last
commit or rollback.
 SQLWarning getWarning(): It returns the first warning
reported by the calls made on current connection’s object.
3.2.3 The Statement Interface
The Statement interface provides methods that are used to execute static
SQL statements. Using the object of this interface, one can assemble multiple
SQL statements into batch and can be submitted to the database for batch
processing. The SQL statements are queries, insertions, updates and deletions
etc.
Some of the methods of the Statement interface are as follows:
 void close(): This method closes database connections associated
with Statement’s object and releases JDBC resources.
 boolean execute(String sql): This method is used to
execute an SQL statement that might produce multiple result sets or
multiple counts. It returns true if multiple result sets are produced and
returns false if multiple counts are generated.
 int executeUpdate(String sql): This method is used
to execute an SQL statement that gives information about number of
affected rows. For example, if we execute the statements like INSERT,
DELETE, the result will only be a number of rows affected.
 ResultSet executeQuery(String sql): This method
executes a query and returns a ResultSet object. A result set is just
like a table containing the resultant data.

Self-Instructional
Material 37
JDBC Classes and  ResultSet getResultSet(): This method returns the first
Statements
result set or multiple count generated on the execution of
execute(String sql) method. If there is no result set, it returns
null value.
NOTES
 int getUpdateCount(): After the execution of the
execute(String sql) method updates counts may be
generated. This method returns the first update count and clears it. More
update counts can be retrieved by getMoreResults(). Note
that this method returns value -1 if there is no update count or when
only result sets are generated on execution of execute(String
sql) method.
 boolean getMoreResults(): This method is used to retrieve
the next result set in multiple result set or to the next count in multiple
update count generated on execution of execute(String
sql)method. It returns a true value if multiple sets are available and
returns a false value if multiple update counts are available.
 void addBatch(String sql): This method is used to add
an SQL statement to the current set of statements.
 void cancel(): This method is used to cancel the current
Statement’s object if the driver and the DBMS supports aborting
an SQL statement.
 void clearBatch(): This method is used to clear all the
statements present in the set of SQL statements held by the
Statement’s object.
 void setFetchSize(int rows): This method is used to
inform the JDBC driver about the maximum number of rows that should
be fetched at once from the database when large number of rows are
required.
 void setFetchDirection(int direction): This
method is to inform the JDBC driver about the direction in which the
rows has to be processed.
 int getFetchDirection(): This method returns the direction
for fetching and processing the rows from the database.
 int getFetchSize(): This method returns the default fetch
size of rows for result sets.
 int getMaxFieldSize(): This method returns the maximum
number of bytes allowed for the particular column value.
 int getMaxRows(): This method returns the maximum number
of rows that a ResultSet object can hold.

Self-Instructional
38 Material
 int getQueryTimeout(): This method returns the number of JDBC Classes and
Statements
seconds a driver should wait for the execution of the Statement’s
object.
 int getresultSetType(): This method returns the type for
NOTES
the result set generated by the Statement’s object.
 void setEscapeProcessing(boolean enable): This
method sets the escape processing on or off.
 void setCursorName(String name): This method defines
the name for the cursor that will be used for the execution of statements
of the Statement’s object.
 void setQueryTimeout(int second): This method is
used to set the time for which JDBC driver has to wait for the execution
of the Statement’s object. The time is specified in seconds.
3.2.4 The ResultSet Interface
The execution of SQL statement results in table which consists of rows and columns
containing the resultant data. The data can be retrieved from the table by using
methods of the ResultSet interface. The ResultSet object is automatically
closed when its corresponding Statement object is closed. It maintains a
cursor that points to the current row and can used to access any row. Initially, the
cursor points to the first row. There are several methods that can be used to move
the cursor to the desired row. Some methods of the ResultSet interface are
as follows:
 boolean first(): This method is used to move the ResultSet
cursor to the first row in the data.
 boolean next(): This method is used to move the ResultSet
cursor to the next row of the data. Initially, the ResultSet cursor is
pointed before the first row. It returns the false value if there are no more
rows in the ResultSet object.
 boolean absolute(int row): This method moves the
ResultSet cursor to the given row specified as an argument of the
method.
 void deleteRow(): This method deletes the current row from the
data.
 int getType(): This method returns the type of the current
ResultSet object.
 String getString(int index): This method returns the string
value that is stored in the column indicated by the column number, index.
For example, if the value of index is 2 then it will return the value stored in
second column number.
Self-Instructional
Material 39
JDBC Classes and  String getString(String column): This method returns
Statements
the string value that is stored in the column indicated by the column name
column.
 float getFloat(String column): This method returns the
NOTES
value of the specified column in the current row as a float.
 boolean last(): This method moves the cursor to the last row in
the data.
 boolean isLast(): This method tells whether the cursor is on the
last row of the data.
 Time getTime(int columnIndex): This method returns the
value of the specified column in the current row as java.sql.Time
object.
 void updateDate(int columnIndex,Date x): This
method updates the specified column with the java.sql.Date value
passed as an argument.
 boolean wasNull(): This method returns whether the last column
read had a value of SQL null.
 void refreshRow(): This method refreshes the current row with
the latest values from the database.
 void insertRow(): This method inserts the values of the insert row
into the Resultset object and into the database.
 int getRow(): This method returns the current row number of the
ResultSet object.
 boolean isAfterLast(): This method informs whether the cursor
is after the last row in the data.
 boolean isBeforeFirst(): This method informs whether the
cursor is before the first row in the data.
 Array getArray(String column_name): This method returns
the value of the specified column of the current row in the data as an Array
object.
 byte getByte(String column_name): This method returns
the value of the specified column of the current row in the data as a byte.
 Date getDate(String column_name): This method returns
the value of the specified column in the current row as java.sql.Date
object.
 URL getURL(String column_name): This method returns the
value of the specified column in the current row as java.net.URL
object.

Self-Instructional
40 Material
 void deleteRow(): This method deletes the current row from JDBC Classes and
Statements
ResultSet object and also from the corresponding database. When
the cursor is on the insert row, this method cannot be called.
 Date getDate(int column_index, Calendar cal):
NOTES
This method returns the value of the specified column on the current row of
in the data as java.sql.Date object.
 Time getTime(int column_index, Calendar cal):
This method returns the value of the specified column in the current row as
java.sql.Time object.
 Timestamp getTimestamp(int column_index,
Calendar cal): This method returns the value of the specified column
in the current row as java.sql.Timestamp object.
Example 3.1: A program to establish connection and retrieve data from Student
database
import java.sql.*;
public class SimpleJDBCProgram
{
public static void main(String args[])
{
try
{
//loading the driver class

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//defines the datasource for the driver
String url = “jdbc:odbc:ITLESL”;

//creating the connection through


//DriverManager
Connection
con = DriverManager.getConnection (“url”, “login”,
“password”);
//creating the statement object
Statement st = con.createStatement();

//executing the query through


//Resultset object
ResultSet
rs = st.executeQuery(“Select Roll, Marks, Grade FROM
Student”);
//output the resultset data
Self-Instructional
Material 41
JDBC Classes and while (rs.next())
Statements
{
//retrieve columns
int roll = rs.getInt(“Roll”);
NOTES
int marks = rs.getInt(“Marks”);
String grade = rs.getString(“Grade”);
//display values
System.out.println(“Roll No :”+ roll);
System.out.println(“Marks :”+ marks);
System.out.println(“Grade :”+ grade);
}
//cleaning up the environment
rs.close();
st.close();
con.close();
}
catch(Exception e)
{
System.out.println(“Error “+e);
}
}
}
In this program, following steps are followed to access the data from the
database.
1. Appropriate drivers for the database are loaded by using
Class.forName().
2. The getConnection() method of DriverManager class of
JDBC is used to create the Connection object. An application
may have more than one connection objects to connect with one or
more databases.
3. The first parameter URL(“jdbc:odbc:ITLESL”) identifies the
database. This URL has three parts: protocol, subprotocol and DSN
name. To connect to the database username and password are also
required which are specified by the other two parameters of
getConnection()method, login and password.
4. The statement Statement st = con.createStatement()
is used to create Statement object, st for querying the database.
It is created by calling the createStatement() method using
the Connection object, con.

Self-Instructional
42 Material
5. In this example, st.executeQuery is used to execute the JDBC Classes and
Statements
SELECT statement of SQL. The try{..} catch {..} is
used to catch any exceptions that may arise as a result of executing this
query statement. The result of this query may consist of set of tuples,
which is assigned to rs object of type ResultSet. Initially, it places NOTES
the cursor at the beginning of the first tuple. The statement rs.next()
moves the cursor to the next tuple.
6. The next() method is used to fetch one tuple at a time from the result
set rs. The statement int roll = rs.getInt(“Roll”);
is used to access data from the database and
System.out.println(“Roll No :”+ roll); is used
to display data.
7. The connection must be closed after it is no more required at the end of
the procedure. The statement rs.close(), st.close(),
con.close() closes all the open connections.
3.2.5 The PreparedStatement Interface
PreparedStatement interface extends the Statement interface so it
has access to all the methods of Statement interface. It is used to execute
precompiled parameterised SQL statements. This helps statements to execute
much faster thus increases the efficiency of the program. It allows you to specify
SQL query, in which unknown values are replaced by ‘?’. The user provides the
unknown values later at the run-time. The setString() and setInt()
methods can be used to specify the values for the parameters. To understand the
concept of prepared statement, consider the following statements.
PreparedStatement ps = con.prepareStatement(“INSERT INTO
Student
VALUES(?,?,?)”);
ps.setString(1, “A010”); //assigns value to first
//attribute
ps.setInt(2, 90); //assigns value to second
//attribute
ps.setString(3, “A”); //assigns value to third
//attribute
ps.executeUpdate();
The values can be assigned to the corresponding attributes through variable
name also instead of using literal values representing index value. Like,
setString() and setInt() methods, there are various methods for setting
value of other data type. Some of these are setBoolean(), setFloat(),
s e t B y t e ( ) , s e t D a t e ( ) , etc. The method v o i d
clearParameters() can be used to clear all the values held currently in
the parameters.
Self-Instructional
Material 43
JDBC Classes and Note: The methods e x e c u t e ( ) , e x e c u t e Q u e r y ( ) and
Statements
e x e c u t e Up d a t e ( ) have same functionality as the methods of
Statement interface, but with a difference that here no parameters are
passed.
NOTES
Example 3.2: A program to demonstrate implementation of
PreparedStatement interface
import java.io.*;
import java.sql.*;
public class ExamplePreparedStatement
{
public static void main(String args[])
{
Connection con=null;
int i = 0;
try
{
Class.
forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con=
DriverManager.getConnection(“jdbc:odbc:Emp”);
Statement st = con.createStatement();
PreparedStatement ps =
con.prepareStatement(“
INSERT INTO Employee VALUES(?,?,?,?,?)”);
ps.setInt(1,8);
ps.setString(2,”Meenu”);
ps.setString(3,”IT”);
ps.setString(4,”SE”);
ps.setInt(5,30000);
i = ps.executeUpdate();
System.out.println(“
Number of rows effected:” +i);
ResultSet rs = st.executeQuery(“
select * from Employee”);
System.out.print(“Eno ”);
System.out.print(“Name ”);
System.out.print(“Depatment ”);
System.out.print(“Designation ”);
System.out.println(“Salary ”);
System.out.println(“
Self-Instructional
44 Material
——————————————————————-”); JDBC Classes and
Statements
while(rs.next())
{
System.out.print(rs.getString(“ENumber”));
NOTES
System.out.print(“ ”);
System.out.print(rs.getString(“EName”));
System.out.print(“ ”);
System.out.
print(rs.getString(“Department”));
System.out.print(“ ”);
System.out.
print(rs.getString(“Designation”));
System.out.print(“ ”);
System.out.
println(rs.getString(“Salary”));
}
rs.close();
System.in.read();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
The output of the program is
Number of rows effected: 1
————————Employee Details—————————————
Eno Name Department Designation Salary
—————————————————————————————
1 Prem IT PL 30000
2 Samee IT SSE 29500
3 Preeti IT TL 29500
4 Mili IT SE 28000
5 Niti Math TL 28000
6 Surabhi IT SE 25000
7 Milendu IT SE 25000
8 Meenu IT SE 30000

Self-Instructional
Material 45
JDBC Classes and 3.2.6 The ResultSetMetaData Interface
Statements
The ResultSetMetaData interface provides methods that allow you to
get metadata for the resultset, that is, the number, types and properties of the
NOTES columns in a ResultSet object. This information is used to collect the data
with same semantics but stored in different databases in different formats.
To get this information of columns in the ResultSet object using methods
of the ResultSetMetaData interface, it is required to invoke the
getMetaData() method of the ResultSet object that returns a reference
to an object of type ResultSetMetaData.
Some of the methods of ResultSetMetaData interface are as
follows:
 int getColumnCount(): This method returns the number of
columns in the resultset.
 String getColumnName(int index): This method returns
the name of column specified by index value index in the resultset.
 int getColumnType(int index): This method returns
the type of column specified by index value index in the resultset.
Example 3.3: A program to demonstrate implementation of
ResultSetMetaData and ResultSet interface
import java.sql.*;
class ExampleResultSetMetaData
{
public static void main(String args[])
{
Connection con;
Statement stmt;
ResultSet rs;
try
{
Class.forName(“
sun.jdbc.odbc.JdbcOdbcDriver”);
con =
DriverManager.getConnection(“jdbc:odbc:Emp”);
stmt = con.createStatement();
rs = stmt.
executeQuery(“Select * from Employee WHERE
Department=’Math’”);
ResultSetMetaData rsmd = rs.getMetaData();
int col = rsmd.getColumnCount();

Self-Instructional
46 Material
//returns number of columns JDBC Classes and
Statements
int row = 1;
while(rs.next())
{
NOTES
System.out.println(“Row “ + row + “: “);
for(int i = 1; i <= col; i++)
{
System.out.print(“ Column “ + i + “: “);
System.out.println(rs.getString(i));
}
System.out.println(“ “);
row++;
}
stmt.close();
con.close();
}
catch(Exception e)
{
System.err.print(“ClassNotFoundException: “);
System.err.println(e.getMessage());
}
}
}
The output of the program is
Row 1:
Column 1: 5
Column 2: Niti
Column 3: Math
Column 4: TL
Column 5: 28000
3.2.7 The CallableStatement Interface
The CallableStatement interface which is derived from the
PreparedStatement interface is used to execute remote SQL stored
procedures on the database. It can return one ResultSet or multiple
ResultSet objects.
Stored Procedures
Stored procedure is stored in the database and is used by the applications to
access the database. It is usually used to put together the commonly used operations
that are to be performed on the database. The stored procedure can be called by
Self-Instructional
Material 47
JDBC Classes and using JDBC CallableStatement interface. For example, consider this
Statements
procedure without parameters.
CREATE PROCEDURE Employee_Details
AS
NOTES
BEGIN —Start of a procedure
SELECT ENumber, EName, Designation, Salary FROM Employee;
END —End of a procedure
Stored procedures can be called with the parameters and these parameters
are of two types namely, IN and OUT. IN parameters are used to pass data to the
stored procedure and OUT parameters hold the values returned by the stored
procedure. The OUT parameter can be registered by using following method of
CallableStatement object:
registerOutParameter(2, Types.Integer)
In this statement, the first parameter indicates the index position of the OUT
parameter and second parameter indicates its type.
Consider the following stored procedure with one IN and one OUT
parameter.
CREATE PROCEDURE Emp_Details
@EmpName Char(30),
@EmpSalary Int Out
AS
BEGIN
SELECT EmpSalary = Salary FROM Employee WHERE EName =
EmpName;
END
Invoking Stored Procedure Using CallableStatement Interface
JDBC allows calling stored procedure using CallableStatement interface.
The statement for calling the stored procedure can be parameterized or non-
parameterized.
The syntax for the calling stored procedure without parameter is as follows:
“{call procedure_name}”
The syntax for the calling stored procedure with parameters is as follows:
“{call procedure_name(?,?,…,?)}”
This interface inherits some method from other interfaces such as
PreparedStatement interface and Statement interface.
Some of the methods of CallableStatement interface are as
follows:
 String getString(int parameter_index): This
method returns the value of the specified JDBC CHAR, VARCHAR, or
Self-Instructional LONGVARCHAR parameter as a String in Java.
48 Material
 int getInt(int parameter_index): This method returns JDBC Classes and
Statements
the value of the specified JDBC INTEGER parameter as an int in
Java.
 int getFloat(int parameter_index): This method
NOTES
returns the value of the specified JDBC FLOAT parameter as a float
in Java.
 int getDate(int parameter_index): This method returns
the value of the specified JDBC D A T E parameter as a
java.sql.Date object.
 int getTime(int parameter_index): This method returns
the value of the specified JDBC T I M E parameter as a
java.sql.Time object.
 void registerOutParameter(int
parameter_Index, int sqlType): This method is used
to register the specified OUT parameter to the JDBC type sqlType.
 void setString(int parameter_index, String
x): This method sets the string value of the specified column.
 void setTime(String parameter, Time t): This
method sets the specified parameter with the value of
java.sql.Time.
 void setTimestamp(String parameter, Timestamp
ts): This method sets the specified parameter with the value of
java.sql.Timestamp.
 void setNull(String parameter, int type):
This method sets the value of the specified parameter to SQL null.
 void wasNull(): This method checks whether the last OUT
parameter returned was SQL null.
 void setDate(String parameter, Date x): This
method sets the specified parameter with the value of
java.sql.Date.
 void setBoolean(String parmeter, boolean b):
This method sets the value of the specified parameter with the given
boolean value.
 void setByte(String parameter, byte b): This
method sets the value of the specified parameter with the given byte
value.
 void setObject(String parameter, Object obj):
This method sets the value of the specified parameter with the given
object.

Self-Instructional
Material 49
JDBC Classes and Example 3.4: A program to demonstrate the calling of a stored procedure without
Statements
parameters
import java.io.*;
import java.sql.*;
NOTES
public class ExampleProcedure1
{
public static void main(String[] args)
{
Connection con=null;
try
{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//loads driver
con=Driver
Manager.getConnection(“jdbc:odbc:Emp”);
//establishes connection
CallableStatement cst=null;
//creates CallableStatement object
cst=con.prepareCall(“{call Employee_Details}”);
//procedure is invoked
ResultSet rs=cst.executeQuery();
//executes the procedure call and
//creates ResultSet object
System.out.println(“ENumber “);
System.out.print(“EName “);
System.out.print(“Designation “);
System.out.print(“Salary”);
//displays data till there are no more rows
while(rs.next())
{
System.out.println(rs.getString(1));
System.out.print(“ “);
System.out.print(rs.getString(2));
System.out.print(“ “);
System.out.print(rs.getString(3));
System.out.print(“ “);
System.out.print(rs.getString(4));
}
//closes the connection

Self-Instructional
50 Material
rs.close(); JDBC Classes and
Statements
cst.close();
con.close();
}
NOTES
catch(Exception e)
{
System.out.println(“Exception occured”);
}
}
}
The output of the program is
ENumber EName Designation Salary
1 Prem PL 30000
2 Samee SSE 29500
3 Preeti TL 29500
4 Mili SE 28000
5 Niti TL 28000
6 Surabhi SE 25000
7 Milendu SE 25000
Example 3.5: A program to demonstrate the calling of a stored procedure with
parameter
import java.io.*;
import java.sql.*;
public class ExampleProcedure
{
public static void main(String[] args)
{
Connection con=null;
try
{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//loads driver
con=
DriverManager.getConnection(“jdbc:odbc:Emp”);
//establishes connection
CallableStatement cst=null;
//creates CallableStatement object
cst=con.prepareCall(“{call Emp_Details(?,?)}”);
//procedure is invoked
cst.setString(1, “Shannaya”) Self-Instructional
Material 51
JDBC Classes and //sets the value of IN parameter
Statements
cst.registerOutParameter(2, Types.INTEGER);
//registers the OUT parameter
cst.executeQuery();
NOTES
//executes the procedure call
int sal = cst.getInt(2);
//get the value of OUT parameter
System.out.println(“
Salary of the Employee is: “+sal+” pm”);
//closes the connection
cst.close();
con.close();
}
catch(Exception e)
{
System.out.println(“Exception occured”);
}
}
}
3.2.8 The SQLException Class
While accessing the database, the developer may encounter various types of errors.
If any JDBC object encounters an error, it throws the SQLException. The
SQLException class extends the java.lang.Exception class. Some
of the methods of the SQLException class are as follows:
 SQLException getNextException(): This method is used
to obtain the next exception object in the chain of errors (if any exists).
 String getSQLState(): This method provides the information
about the state of SQL, which helps in taking appropriate decisions.
 int getErrorCode(): This method provides information about
the vendor specific errors whose meaning is defined by the driver vendor
only.
 void setNextException(): This method is used to add an
SQLException object at the end of chain of errors.
Example 3.6: A program to demonstrate how exceptions related to JDBC are
handled
import java.io.*;
import java.sql.*;
public class FinalExceptionExample
{
Self-Instructional
52 Material
public static void main(String args[]) JDBC Classes and
Statements
{
Connection con=null;
try
NOTES
{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con=Driver
Manager.getConnection(“jdbc:odbc:Emp”);
Statement st = con.createStatement();
ResultSet rs =
st.executeQuery(“select * from EmployeeDB”);
System.out.print(“Employee Number ”);
System.out.print(“Employee Name ”);
System.out.print(“Department ”);
System.out.print(“Designation ”);
System.out.println(“Salary ”);
System.out.println(“
——————————— ——————————-”);
while(rs.next())
{
System.out.print(rs.getString(“ENumber”));
System.out.print(“ ”);
System.out.print(rs.getString(“EName”));
System.out.print(“ ”);
System.out.
print(rs.getString(“Department”));
System.out.print(“ ”);
System.out.
print(rs.getString(“Designation”));
System.out.print(“ ”);

System.out.println(rs.getString(“Salary”));
}
rs.close();
}
catch(SQLException e)
{
while(e != null)
{

Self-Instructional
Material 53
JDBC Classes and System.out.println(“\nSQL Exception:”);
Statements
System.out.println(e.getMessage());
System.out.
println(“SQL State: ” + e.getSQLState());
NOTES
System.out.
println(“Error Code: ” + e.getErrorCode());
e = e.getNextException();
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe.getMessage());
}
}
}
The output of the program is
SQL Exception:
[Microsoft][SQL Server Native Client 10.0][SQL
Server]Invalid object name ‘EmployeeDB’.
SQL State: S0002
Error Code: 208
Note that if Class.forName() syntax is used for registering the driver,
you may encounter the ClassNotFoundException. This type of exception
is encountered if the class loader is unable to find the specified database driver.

Check Your Progress


1. What is the responsibility of DriverManager class?
2. What is the use of statement interface?
3. Define PreparedStatement interface.

3.3 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. The DriverManager class is responsible for loading the driver specific


classes.
2. The Statement interface provides methods that are used to execute
static SQL statements. Using the object of this interface, one can assemble
multiple SQL statements into batch and can be submitted to the database
for batch processing.
Self-Instructional
54 Material
3. PreparedStatement interface extends the Statement interface JDBC Classes and
Statements
so it has access to all the methods of Statement interface. It is used to
execute precompiled parameterised SQL statements.

NOTES
3.4 SUMMARY

 Java provides java.sql package which contains various classes and


interfaces that can be used for establishing connection with database and
retrieve data from it.
 The DriverManager class is responsible for loading the driver specific
classes. The drivers are registered with the DriverManager class
either when an instance of driver is created using
regist erDriver(D river driv er) method of the
DriverManager class or DriverManager class is initialized.
 The Connection interface helps to establish a connection with the
required database. Other than establishing connection, it provides lot of
functionality including transaction management, maintaining database sessions
and creating SQL statements.
 The Statement interface provides methods that are used to execute
static SQL statements. Using the object of this interface, one can assemble
multiple SQL statements into batch and can be submitted to the database
for batch processing.
 The data can be retrieved from the table by using methods of the
ResultSet interface. The ResultSet object is automatically closed
when its corresponding Statement object is closed.
 PreparedStatement interface extends the Statement interface
so it has access to all the methods of Statement interface. It is used to
execute precompiled parameterised SQL statements.
 The ResultSetMetaData interface provides methods that allow
you to get metadata for the resultset, that is, the number, types and properties
of the columns in a ResultSet object.
 The CallableStatement interface which is derived from the
PreparedStatement interface is used to execute remote SQL stored
procedures on the database.
 If any JDBC object encounters an error, it throws the SQLException.

3.5 KEY WORDS

 DriverManager: It is an interface that registers JDBC drivers and supplies


connections that can handle specific JDBC URLs.
Self-Instructional
Material 55
JDBC Classes and  ResultSetMetaData: It is an interface that describes the columns of a
Statements
ResultSet. This can be obtained by calling the result set’s getMetaData()
method.

NOTES
3.6 SELF ASSESSMENT QUESTIONS AND
EXERCISES

Short-Answer Questions
1. Write a note on DriverManager class.
2. Discuss the methods of connection class.
3. List the various methods in statement interface.
Long-Answer Questions
1. What are the different methods of DriverManager class? Explain.
2. What is a connection interface? Also, discuss list the various methods
of connection interface.
3. Explain the various methods of statement interface.
4. What is ResultSet interface? Explain its methods.
5. Write a note on:
(i) ResultSetMetaData interface
(ii) CallableStatement interface
(iii) SQLException class

3.7 FURTHER READINGS

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
56 Material
InetAddress, TCP/IP
BLOCK - II Client and Server Sockets
INETADDRESS

NOTES
UNIT 4 INETADDRESS, TCP/IP
CLIENT AND SERVER
SOCKETS
Structure
4.0 Introduction
4.1 Objectives
4.2 The InetAddress Class
4.3 Getter Methods
4.4 Inet4Address and Inet6Address
4.5 Using IP Addresses and InetAddress
4.6 Networking Protocols
4.7 Ports and Sockets
4.7.1 Using TCP/IP Sockets
4.8 Answers to Check Your Progress Questions
4.9 Summary
4.10 Key Words
4.11 Self Assessment Questions and Exercises
4.12 Further Readings

4.0 INTRODUCTION

In this unit, you will learn about the Transmission Control Protocol and Internet
Address Protocol to transfer information between the client and the server over
the network. You will also learn about ports, which allow a user to request a Web
page from the server and socket that helps in maintaining the uninterrupted
connection between the two. In addition, you also learn how to use TCP/IP sockets
in a Java program to establish a connection between the client and the server.

4.1 OBJECTIVES

After going through this unit, you will be able to:


 Discuss the InetAddress class
 Explain networking classes and interfaces
 TCP/IP sockets to transmit data using the TCP protocol
 Use UDP sockets to transmit data using the UDP protocol
Self-Instructional
Material 57
InetAddress, TCP/IP
Client and Server Sockets 4.2 THE INETADDRESS CLASS

The java.net.InetAddress class represents an IP address and does


NOTES not discriminate between the two classes of protocols, IPv4 and IPv6. Though ,
there are subclasses Inet4Address and Inet6Address that represent IPv4 and
IPv6 addresses, respectively, you need not worry about them while writing network
applications as Java takes care of that by hiding all the details. Hence, for either of
the two (IPv4 and IPv6), using InetAddress is enough. It includes both a hostname
and an IP address and hence it is used by most of the other networking classes,
including Socket, ServerSocket, URL, DatagramSocket,
DatagramPacket, and more.
Creating New InetAddress Objects
The InetAddress class does not have any public constructors. Rather,
InetAddress has static factory methods that connect to a DNS server to
resolve a hostname. And the most common one is
InetAddress.getByName().
For example, this is how you look up www.alagappauniversity.com:
InetAddress address = InetAddress.getByName(“www.alagappauniversity.com
“);
This method first of all sets a private String field in the InetAddress
class and also establishes a connection to the local DNS server to look up the
name and the numeric address. (If you’ve looked up this host previously, the
information may be cached locally, in which case a network connection is not
required.) If the DNS server can’t find the address, this method throws an
UnknownHostException, a subclass of IOException.
The example given below shows a complete program that creates an
InetAddress object for www.alagappauniversity.com.
Example 4.1: A program that prints the address of www.alagappauniversity.com.

Self-Instructional
58 Material
Output: InetAddress, TCP/IP
Client and Server Sockets

NOTES

Furthermore, you can also perform a reverse lookup by IP address.


For example, if you wish to know the hostname for the address
208.201.239.100, pass the dotted quad address to
InetAddress.getByName():
InetAddress address =
InetAddress.getByName(“208.201.239.100”);
System.out.println(address.getHostName());
If the address you look up does not have a hostname, getHostName()
simply returns the dotted quad address you supplied.
www. actually has two addresses. Which one getHostName() returns
is indeterminate. If, for some reason, you need all the addresses of a host, call
getAllByName() instead, which returns an array:
try {
InetAddress[] addresses =
InetAddress.getAllByName(“www.”);
for (InetAddress address : addresses) {
System.out.println(address);
}
} catch (UnknownHostException ex) {
System.out.println(“Could not find www.”);
}
Finally, the getLocalHost() method returns an InetAddress
object for the host on which your code is running:
InetAddress me = InetAddress.getLocalHost();
This method tries to connect to DNS to get a real hostname and IP address
such as “gupta.publishing.help.com” and “192.168.43.239”; but if that fails it may
return the loopback address instead. This is the hostname “localhost” and the
dotted quad address “127.0.0.1”.
Self-Instructional
Material 59
InetAddress, TCP/IP Example 4.2: To prints the address of the machine it is running on.
Client and Server Sockets
import java.net.*;

public class MyAddress {


NOTES

public static void main (String[] args) {


try {
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
} catch (UnknownHostException ex) {
System.out.println(“Could not find this computer’s
address.”);
}
}
}
Output:

Whether you see a fully qualified name like alagappauniversity.indiuniv.edu


or a partial name like alagappa depends on what the local DNS server returns
for hosts in the local domain. If you’re not connected to the Internet, and the
system does not have a fixed IP address or domain name, you’ll probably see
localhost as the domain name and 127.0.0.1 as the IP address.
If you know a numeric address, you can create an InetAddress object
from that address without talking to DNS using
InetAddress.getByAddress(). This method can create addresses
for hosts that do not exist or cannot be resolved:
public static InetAddress getByAddress(byte[] addr) throws
UnknownHostException
public static InetAddress getByAddress(String hostname,
byte[] addr)
throws UnknownHostException
Self-Instructional
60 Material
The first InetAddress.getByAddress() factory method creates InetAddress, TCP/IP
Client and Server Sockets
an InetAddress object with an IP address and no hostname. The second
InetAddress.getByAddress() method creates an InetAddress
object with an IP address and a hostname. For example, this code fragment makes
an InetAddress for 107.23.216.196: NOTES
byte[] address = {107, 23, (byte) 216, (byte) 196};
InetAddress lessWrong = InetAddress.getByAddress(address);
InetAddress lessWrongWithname = InetAddress.getByAddress(
“lesswrong.com”, address);
Note that it had to cast the two large values to bytes.
Unlike the other factory methods, these two methods make no guarantees
that such a host exists or that the hostname is correctly mapped to the IP address.
They throw an UnknownHostException only if a byte array of an illegal
size (neither 4 nor 16 bytes long) is passed as the address argument. This
could be useful if a domain name server is not available or might have inaccurate
information. For example, none of the computers, printers, or routers in my
basement area network are registered with any DNS server. Because I can never
remember which addresses I’ve assigned to which systems, I wrote a simple
program that attempts to connect to all 254 possible local addresses in turn to see
which ones are active. (This only took me about 10 times as long as writing down
all the addresses on a piece of paper.)

4.3 GETTER METHODS

The InetAddress class contains four getter methods that return the hostname
as a string and the IP address as both a string and a byte array:
public String getHostName()
public String getCanonicalHostName()
public byte[] getAddress()
public String getHostAddress()
There are no corresponding setHostName() and setAddress()
methods, which means that packages outside of java.net can’t change an
InetAddress object’s fields behind its back. This makes InetAddress
immutable and thus thread safe.
The getHostName() method returns a String that contains the
name of the host with the IP address represented by this InetAddress object.
If the machine in question doesn’t have a hostname or if the security manager
prevents the name from being determined, a dotted quad format of the numeric IP
address is returned. For example:
InetAddress machine = InetAddress.getLocalHost();
String localhost = machine.getHostName();
Self-Instructional
Material 61
InetAddress, TCP/IP The getCanonicalHostName() method is similar, but it’s a bit
Client and Server Sockets
more aggressive about contacting DNS. getHostName() will only call DNS
if it doesn’t think it already knows the hostname.
getCanonicalHostName() calls DNS if it can, and may replace the
NOTES existing cached hostname. For example:
InetAddress machine = InetAddress.getLocalHost();
String localhost = machine.getCanonicalHostName();
The getCanonicalHostName() method is particularly useful when
you’re starting with a dotted quad IP address rather than the hostname. The
example given below converts the dotted quad address 208.201.239.37 into a
hostname by using InetAddress.getByName() and then applying
getCanonicalHostName() on the resulting object.
Example 4.3: To find the hostname using the given address.
import java.net.*;

public class ReverseTest {

public static void main (String[] args) throws


UnknownHostException {
InetAddress ia =
InetAddress.getByName(“208.201.239.100”);
System.out.println(ia.getCanonicalHostName());
}
}
Here’s the result:
% java ReverseTest
The getHostAddress() method returns a string containing the dotted
quad format of the IP address. Example 4.4 uses this method to print the IP
address of the local machine in the customary format.
Example 4.4: To find the IP address of the local machine.
import java.net.*;

public class MyAddress {

public static void main(String[] args) {


try {
InetAddress me = InetAddress.getLocalHost();
String dottedQuad = me.getHostAddress();
System.out.println(“My address is “ +
dottedQuad);

Self-Instructional
62 Material
} catch (UnknownHostException ex) { InetAddress, TCP/IP
Client and Server Sockets
System.out.println(“I’m sorry. I don’t know my
own address.”);
}
} NOTES
}
Result:
% java MyAddress
My address is 152.2.22.14.
Of course, the exact output depends on where the program is run.
If you want to know the IP address of a machine (and you rarely do), then
use the getAddress() method, which returns an IP address as an array of
bytes in network byte order. The most significant byte (i.e., the first byte in the
address’s dotted quad form) is the first byte in the array, or element zero. To be
ready for IPv6 addresses, try not to assume anything about the length of this array.
If you need to know the length of the array, use the array’s length field:
InetAddress me = InetAddress.getLocalHost();
byte[] address = me.getAddress();
The bytes returned are unsigned, which poses a problem. Unlike C, Java
doesn’t have an unsigned byte primitive data type. Bytes with values higher than
127 are treated as negative numbers. Therefore, if you want to do anything with
the bytes returned by getAddress(), you need to promote the bytes to
ints and make appropriate adjustments. Here’s one way to do it:
int unsignedByte = signedByte < 0 ? signedByte + 256 :
signedByte;
Here, signedByte may be either positive or negative. The conditional
operator ? tests whether signedByte is negative. If it is, 256 is added to
signedByte to make it positive. Otherwise, it’s left alone. signedByte is
automatically promoted to an int before the addition is performed, so wraparound
is not a problem.
One reason to look at the raw bytes of an IP address is to determine the
type of the address. Test the number of bytes in the array returned by
getAddress() to determine whether you’re dealing with an IPv4 or IPv6
address.
Example 4.5: To determine whether an IP address is of v4 or v6.
import java.net.*;

public class AddressTests {

public static int getVersion(InetAddress ia) {


byte[] address = ia.getAddress();
Self-Instructional
Material 63
InetAddress, TCP/IP if (address.length == 4) return 4;
Client and Server Sockets
else if (address.length == 16) return 6;
else return -1;
}
NOTES
}
Address Types
Some IP addresses and some patterns of addresses have special meanings. For
instance, we have already mentioned that 127.0.0.1 is the local loopback address.
IPv4 addresses in the range 224.0.0.0 to 239.255.255.255 are multicast addresses
that send to several subscribed hosts at once. Java includes 10 methods for testing
whether an InetAddress object meets any of these criteria:
(i) public boolean isAnyLocalAddress()
(ii) public boolean isLoopbackAddress()
(iii) public boolean isLinkLocalAddress()
(iv) public boolean isSiteLocalAddress()
(v) public boolean isMulticastAddress()
(vi) public boolean isMCGlobal()
(vii) public boolean isMCNodeLocal()
(viii) public boolean isMCLinkLocal()
(ix) public boolean isMCSiteLocal()
(x) public boolean isMCOrgLocal()
The isAnyLocalAddress() method returns true if the address is a
wildcard address, false otherwise. A wildcard address matches any address of
the local system. This is important if the system has multiple network interfaces, as
might be the case on a system with multiple Ethernet cards or an Ethernet card and
an 802.11 WiFi interface. In IPv4, the wildcard address is 0.0.0.0. In IPv6, this
address is 0:0:0:0:0:0:0:0 (a.k.a. ::).
The isLoopbackAddress() method returns true if the address is
the loopback address, false otherwise. The loopback address connects to the
same computer directly in the IP layer without using any physical hardware. Thus,
connecting to the loopback address enables tests to bypass potentially buggy or
non-existent Ethernet, PPP, and other drivers, helping to isolate problems.
Connecting to the loopback address is not the same as connecting to the system’s
normal IP address from the same system. In IPv4, this address is 127.0.0.1. In
IPv6, this address is 0:0:0:0:0:0:0:1 (a.k.a. ::1).
The isLinkLocalAddress() method returns true if the address is
an IPv6 link-local address, false otherwise. This is an address used to help IPv6
networks self-configure, much like DHCP on IPv4 networks but without necessarily
using a server. Routers do not forward packets addressed to a link-local address
Self-Instructional
64 Material
beyond the local subnet. All link-local addresses begin with the eight bytes InetAddress, TCP/IP
Client and Server Sockets
FE80:0000:0000:0000. The next eight bytes are filled with a local address, often
copied from the Ethernet MAC address assigned by the Ethernet card manufacturer.
The isSiteLocalAddress() method returns true if the address is
NOTES
an IPv6 site-local address, false otherwise. Site-local addresses are similar to
link-local addresses except that they may be forwarded by routers within a site or
campus but should not be forwarded beyond that site. Site-local addresses begin
with the eight bytes FEC0:0000:0000:0000. The next eight bytes are filled with a
local address, often copied from the Ethernet MAC address assigned by the
Ethernet card manufacturer.
The isMulticastAddress() method returns true if the address is
a multicast address, false otherwise. Multicasting broadcasts content to all
subscribed computers rather than to one particular computer. In IPv4, multicast
addresses all fall in the range 224.0.0.0 to 239.255.255.255. In IPv6, they all
begin with byte FF.
The isMCGlobal() method returns true if the address is a global
multicast address, false otherwise. A global multicast address may have subscribers
around the world. All multicast addresses begin with FF. In IPv6, global multicast
addresses begin with FF0E or FF1E depending on whether the multicast address
is a well-known permanently assigned address or a transient address. In IPv4, all
multicast addresses have global scope, at least as far as this method is concerned.
IPv4 uses time-to-live (TTL) values to control scope rather than addressing.
The isMCOrgLocal() method returns true if the address is an
organization-wide multicast address, false otherwise. An organization-wide
multicast address may have subscribers within all the sites of a company or
organization, but not outside that organization. Organization multicast addresses
begin with FF08 or FF18, depending on whether the multicast address is a well
known permanently assigned address or a transient address.
The isMCSiteLocal() method returns true if the address is a site-
wide multicast address, false otherwise. Packets addressed to a site-wide address
will only be transmitted within their local site. Site-wide multicast addresses begin
with FF05 or FF15, depending on whether the multicast address is a well-known
permanently assigned address or a transient address.
The isMCLinkLocal() method returns true if the address is a subnet-
wide multicast address, false otherwise. Packets addressed to a link-local address
will only be transmitted within their own subnet. Link-local multicast addresses
begin with FF02 or FF12, depending on whether the multicast address is a well-
known permanently assigned address or a transient address.
The isMCNodeLocal() method returns true if the address is an
interface-local multicast address, false otherwise. Packets addressed to an
interface-local address are not sent beyond the network interface from which they
originate, not even to a different network interface on the same node. This is
Self-Instructional
Material 65
InetAddress, TCP/IP primarily useful for network debugging and testing. Interface-local multicast
Client and Server Sockets
addresses begin with the two bytes FF01 or FF11, depending on whether the
multicast address is a well-known permanently assigned address or a transient
address.
NOTES
The method name is out of sync with current terminology. Earlier drafts of
the IPv6 protocol called this type of address “node-local,” hence the name
“isMCNodeLocal.” The IPNG working group actually changed the name before
this method was added to the JDK, but Sun didn’t get the memo in time.
Example 4.6: To test the nature of an IP address entered from the command line
using these 10 methods.
import java.net.*;

public class IPCharacteristics {

public static void main(String[] args) {

try {
InetAddress address =
InetAddress.getByName(args[0]);

if (address.isAnyLocalAddress()) {
System.out.println(address + “ is a wildcard
address.”);
}
if (address.isLoopbackAddress()) {
System.out.println(address + “ is loopback
address.”);
}

if (address.isLinkLocalAddress()) {
System.out.println(address + “ is a link-local
address.”);
} else if (address.isSiteLocalAddress()) {
System.out.println(address + “ is a site-local
address.”);
} else {
System.out.println(address + “ is a global
address.”);
}

if (address.isMulticastAddress()) {
if (address.isMCGlobal()) {
Self-Instructional
66 Material
System.out.println(address + “ is a global InetAddress, TCP/IP
multicast address.”); Client and Server Sockets

} else if (address.isMCOrgLocal()) {
System.out.println(address
+ “ is an organization wide multicast NOTES
address.”);
} else if (address.isMCSiteLocal()) {
System.out.println(address + “ is a site wide
multicast
address.”);
} else if (address.isMCLinkLocal()) {
System.out.println(address + “ is a subnet
wide multicast
address.”);
} else if (address.isMCNodeLocal()) {
System.out.println(address
+ “ is an interface-local multicast
address.”);
} else {
System.out.println(address + “ is an unknown
multicast
address type.”);
}
} else {
System.out.println(address + “ is a unicast
address.”);
}
} catch (UnknownHostException ex) {
System.err.println(“Could not resolve “ +
args[0]);
}
}
}
Here’s the output from an IPv4 and IPv6 address:
$ java IPCharacteristics 127.0.0.1
/127.0.0.1 is loopback address.
/127.0.0.1 is a global address.
/127.0.0.1 is a unicast address.
$ java IPCharacteristics 192.168.254.32
/192.168.254.32 is a site-local address.
/192.168.254.32 is a unicast address.
$ java IPCharacteristics www.
Self-Instructional
Material 67
InetAddress, TCP/IP www./208.201.239.37 is a global address.
Client and Server Sockets
www./208.201.239.37 is a unicast address.
$ java IPCharacteristics 224.0.2.1
/224.0.2.1 is a global address.
NOTES
/224.0.2.1 is a global multicast address.
$ java IPCharacteristics FF01:0:0:0:0:0:0:1
/ff01:0:0:0:0:0:0:1 is a global address.
/ff01:0:0:0:0:0:0:1 is an interface-local multicast
address.
$ java IPCharacteristics FF05:0:0:0:0:0:0:101
/ff05:0:0:0:0:0:0:101 is a global address.
/ff05:0:0:0:0:0:0:101 is a site wide multicast address.
$ java IPCharacteristics 0::1
/0:0:0:0:0:0:0:1 is loopback address.
/0:0:0:0:0:0:0:1 is a global address.
/0:0:0:0:0:0:0:1 is a unicast address.
Testing Reachability
The InetAddress class has two isReachable() methods that test whether
a particular node is reachable from the current host (i.e., whether a network
connection can be made). Connections can be blocked for many reasons, including
firewalls, proxy servers, misbehaving routers, and broken cables, or simply because
the remote host is not turned on when you try to connect.
public boolean isReachable(int timeout) throws
IOException
public boolean isReachable(NetworkInterface interface,
int ttl, int timeout)
throws IOException
These methods attempt to use traceroute (more specifically, ICMP echo
requests) to find out if the specified address is reachable. If the host responds
within timeout milliseconds, the methods return true; otherwise, they return
false. An IOException will be thrown if there’s a network error. The second
variant also lets you specify the local network interface the connection is made
from and the “time-to-live” (the maximum number of network hops the connection
will attempt before being discarded).
Object Methods
Like every other class, java.net.InetAddress inherits from
java.lang.Object. Thus, it has access to all the methods of that class. It
overrides three methods to provide more specialized behavior:
public boolean equals(Object o)
public int hashCode()
Self-Instructional public String toString()
68 Material
An object is equal to an InetAddress object only if it is itself an instance InetAddress, TCP/IP
Client and Server Sockets
of the InetAddress class and it has the same IP address. It does not need to
have the same hostname. Thus, an InetAddress object for www.ibiblio.org
is equal to an InetAddress object for www.cafeaulait.org because both
names refer to the same IP address. The example below creates InetAddress NOTES
objects for www.ibiblio.org and helios.ibiblio.org and then tells you whether
they’re the same machine.
Example4.7 To check whether www.ibiblio.org and helios.ibiblio.org are same?
import java.net.*;

public class IBiblioAliases {

public static void main (String args[]) {


try {
InetAddress ibiblio =
InetAddress.getByName(“www.ibiblio.org”);
InetAddress helios =
InetAddress.getByName(“helios.ibiblio.org”);
if (ibiblio.equals(helios)) {
System.out.println
(“www.ibiblio.org is the same as
helios.ibiblio.org”);
} else {
System.out.println
(“www.ibiblio.org is not the same as
helios.ibiblio.org”);
}
} catch (UnknownHostException ex) {
System.out.println(“Host lookup failed.”);
}
}
}
Result:
% java IBiblioAliases
www.ibiblio.org is the same as helios.ibiblio.org
The hashCode() method is consistent with the equals() method.
The int that hashCode() returns is calculated solely from the IP address. It
does not take the hostname into account. If two InetAddress objects have
the same address, then they have the same hash code, even if their hostnames are
different.
Like all good classes, j a v a . n e t . I n e t A d d r e s s has a
toString() method that returns a short text representation of the object. Self-Instructional
Material 69
InetAddress, TCP/IP Example 4.1 and 4.2 implicitly called this method when passing InetAddress
Client and Server Sockets
objects to System.out.println(). As you saw, the string produced by
toString() has the form:
hostname/dotted quad address
NOTES
Not all InetAddress objects have hostnames. If one doesn’t, the dotted
quad address is substituted in Java 1.3 and earlier. In Java 1.4 and later, the
hostname is set to the empty string.

4.4 INET4ADDRESS AND INET6ADDRESS

Java uses two classes, Inet4Address and Inet6Address, in order to


distinguish IPv4 addresses from IPv6 addresses:
(i) public final class Inet4Address extends
InetAddress
(ii) public final class Inet6Address extends
InetAddress
Most of the time, you really shouldn’t be concerned with whether an address
is an IPv4 or IPv6 address. In the application layer where Java programs reside,
you simply don’t need to know this (and even if you do need to know, it’s quicker
to check the size of the byte array returned by getAddress() than to use
instanceof to test which subclass you have). Inet4Address overrides
several of the methods in InetAddress but doesn’t change their behavior in
any public way. Inet6Address is similar, but it does add one new method
not present in the superclass, isIPv4CompatibleAddress():
public boolean isIPv4CompatibleAddress()
This method returns true if and only if the address is essentially an IPv4
address stuffed into an IPv6 container—which means only the last four bytes are
nonzero. That is, the address has the form 0:0:0:0:0:0:0:xxxx. If this is the case,
you can pull off the last four bytes from the array returned by getBytes() and
use this data to create an Inet4Address instead. However, you rarely need
to do this.

Check Your Progress


1. What will getHostName () method returns?
2. What will isAnyLocalAddress () method returns?

4.5 USING IP ADDRESSES AND INETADDRESS

Internet address, also known as the Internet Protocol (IP) address, is a unique
Self-Instructional
address assigned to each computer. The Internet address consists of a 32-bit
70 Material
number that is divided into 4 fields of 8-bits each, separated by periods. An example InetAddress, TCP/IP
Client and Server Sockets
of an IP address is 192.168.0.134. You can connect to the Internet directly
or using an Internet Service Provider (ISP). When you are directly connecting to
the Internet, services are provided at a permanent IP address. However, when the
connection is made using an ISP, a temporary IP address is assigned for each NOTES
session.
It is difficult to remember different IP addresses while connecting to the
Internet. You can use Domain Naming Service (DNS) for addressing this problem
that are also known as URLs. DNS maps an IP address to a string of characters.
For example, www.demo.com is the DNS name for the IP address,
128.227.182.12.
Various Java classes enable you to implement networking in Java.
InetAddress is a class present in the java.net package that can
encapsulate the IP address of your computer to prevent the misuse of your computer
resources. You use InetAddress in your class by creating an object using
factory methods. The classes, for which the constructors are not available, you
use static methods, also known as factory methods that return an object of the
class. The InetAddress class uses two such methods, static InetAddress
getLocalHost() and static InetAddress getByName (String
hostname). The first method returns an InetAddress object representing
the local host and the second method returns an InetAddress for the host
passed as a parameter for the method. The following program code shows how to
create the InetAddress object:
Creating the InetAddress object
import java.net.*;
public class InternetAddress
{
public static void main(String args[])
{
try
{
InetAddress localaddr =
InetAddress.getLocalHost();

System.out.println (“Local IP Address : “ +


localaddr );
System.out.println (“Local Hostname : “ +
localaddr.getHostName());
}
catch (UnknownHostException e)
{
System.err.println (“Can’t detect localhost :
Self-Instructional
Material 71
InetAddress, TCP/IP “ + e);
Client and Server Sockets
}
}
/** Converts a byte_array of octets into a string
NOTES */
public static String byteToStr( byte[] byte_arr )
{
StringBuffer internal_buffer = new
StringBuffer();
// Keeps looping and adding octets to the IP
Address
for (int index = 0; index < byte_arr.length -1;
index++)
{
internal_buffer.append (
String.valueOf(byte_arr[index]) + “.”);
}
// Adds the final octet
internal_buffer.append ( String.valueOf
(byte_arr.length) );
return internal_buffer.toString();
}
}
The above code shows the IP address and host name of the computer on
which the program is running. Figure 7.3 shows the output generated by the
InetAddress class.

Fig. 7.3 Output of the InetAddress Class

4.6 NETWORKING PROTOCOLS

A networking protocol is a set of standard rules that provides the standard for
information exchange over the network. You create network programs in Java by
creating sockets that use networking protocols, such as TCP/IP and UDP. Various
other networking protocols, such as HTTP, FTP and Simple Mail Transfer Protocol
(SMTP) are used in connecting to the Internet.
Web browsers and Web servers use HTTP to communicate with each other.
HTTP is a TCP/IP application layer protocol that enables you to establish
connectivity between the client and server for developing Web-based applications.
The HTTP protocol is based on the request/response model. When you select a
Web page, the Web browser establishes connection with the TCP/IP port and
Self-Instructional
72 Material
transmits an HTTP header requesting the selected Web page. The Web server InetAddress, TCP/IP
Client and Server Sockets
provides a response to the Web browser including that HTTP header along with
the requested data.
The HTTP protocol functions in a manner that is similar to that of the Gopher
NOTES
protocol. Earlier, the use of Gopher was limited to the retrieval of textual information
only. The Gopher protocol is now modified to handle text as well as graphics.
The TCP/IP protocol consists of a set of rules for exchanging information
between applications, across networks. TCP is a connection-oriented, faithful
service that transmits information in the form of packets. The TCP/IP protocol
sends the packets to their intended destinations and the recipient sends an
acknowledgement to the sender on receiving the packets. The sender retransmits
the data, if the acknowledgement is not received.
UDP works as a datagram service between the clients and server. Datagram
is a unit of information that consists of a frame and the frame in turn consists of a
set of bits. UDP provides fast and connectionless transportation of packets. The
UDP protocol is not a reliable protocol, as it does not guarantee the delivery of
packets. The data sent through the UDP protocol contains the recipient’s address
and transfers the data without establishing a connection between the sender and
the recipient.
The Internet Inter-Object Request Broker (ORB) Protocol (IIOP) facilitates
communication between different objects located on a network. It enables the
different network objects to invoke one another using Common ORB Architecture
(CORBA). CORBA enables you to automate many network programming
processes, such as object registration, location and activation. CORBA is an
emerging infrastructure that is provided by the Object Management Group (OMG).
CORBA provides strategy of writing client and server programs in C, C++, Java
or any other language.
IIOP is used in the client/server architecture that synchronizes the languages
of client and server objects for communication between them. IIOP specified the
meaning of clients and servers used for information exchange. It is also used for
clients and servers development using different application programming languages
to interact with one another.

4.7 PORTS AND SOCKETS

A port is a numeric address that requests for a Web page using different protocols.
A 16-bit number, ranging from 0 to 65535, represents ports. Each protocol is
assigned a specific port number through which a client makes a request. Various
protocols, with their port numbers, are:
 Transmission Control Protocol/ Internet Protocol (TCP/IP): Consists
of TCP and UDP protocol that are used to exchange the data over a network.
The TCP/IP protocol reserves the port number 1024.
Self-Instructional
Material 73
InetAddress, TCP/IP  File Transfer Protocol (FTP): Enables the transfer of files efficiently and
Client and Server Sockets
reliably between computers. FTP reserves the port number 21.
 Telnet: Provides an interactive, text-based communication between a client
and server. The telnet protocol reserves the port number 23.
NOTES
 Finger: Enables the file transfer for clients using the FTP protocol. The
finger protocol reserves the port number 79.
 Hyper Text Transfer Protocol (HTTP): Enables the interaction of clients
with the Internet. The HTTP protocol reserves the port number 80.
Ports are categorized as either well known or ephemeral. The well-known
port, also known as privileged port, is created on the server side. The port number
of a well-known port is less than 1024. The ephemeral port, also known as transient
or temporary port, is created on the client side when a client wants to connect to
a server. The ephemeral port is chosen at random and is destroyed when the client
application terminates. The port number of the ephemeral port is greater than
1023. Java uses mainly TCP and UDP protocols for making connection requests.
Figure 4.1 shows how the data is passed to an application across the
network.

Fig. 4.1 Data Passing Over a Network

A socket establishes an uninterrupted network connection between a client


and a server using the port number. The server computer has a host name and a
port number that the client computer uses to make a connection request. The
server accepts the connection request by creating a new socket that the server
uses for communication with the client. The server has a separate local port for
communication with individual clients. The client and server communicate with
each other using a socket connection.

Self-Instructional
74 Material
Figure 4.2 shows how the connection is established between client and InetAddress, TCP/IP
Client and Server Sockets
server.

NOTES

Fig. 4.2 The Connection Establishment

You create network programs in Java using the java.net package. The
java.net package provides the Socket class that creates a client socket
and the ServerSocket class that enables servers to listen for client requests
and accept their connections. The code for implementing socket connection is:
Implementing Socket Connection
Socket mySocketConnection;
try
{
mySocketConnection = new Socket(“www.banner.com” ,
1201);
}
catch(IOException e)
{
System.out.println(“Exception is:” +e);
}
The above code creates the socket object, mySocketConnection,
at port number 1201. The code displays an error message, if it is unable to create
a socket object.
4.7.1 Using TCP/IP Sockets
TCP/IP sockets transfer the data over the network using the TCP/IP. TCP sockets
establish the connection between the host computers first and then start sending
the data. This connection is terminated automatically, when the data has been sent
to the specified host. Java provides two types of TCP/IP sockets, client and socket.
The client socket is used to connect the client to the server. The client socket
is created when you create an object of the Socket class. The Socket class

Self-Instructional
Material 75
InetAddress, TCP/IP is a member of the java.net package. The Socket class provides two
Client and Server Sockets
constructors for creating the client socket. The two constructors are:
 Socket(String HostName, int PortNumber): Creates
a client socket that connects the local host to the named host of the
NOTES
specified port number. This type of constructor throws two Java
exceptions, such as U n K n o w n H o s t E x c e p t i o n and
IOException.
 Socket(InetAddress IPAdress, int
PortNumber): Creates a client socket using the existing host, which
has a specified IP address and port number. IP address is the object of
the InetAddress class that represents the IP address of the existing
host and PortNumber represents its port number. This type of
constructor throws a Java exception, such as IOException.
The server socket is used for creating a server application, which enables a
server to communicate with the client. The server socket is created using the
ServerSocket class. The ServerSocket class is a member of the
java.net package. The ServerSocket class provides three constructors
for creating the server sockets. The three constructors are:
 ServerSocket(int PortNumber): Creates a server socket
for the specified port number that has a fixed queue length of 50. The
queue length determines how many client connections the system can
accept at a time.
 ServerSocket(int PortNumber, int MAXQueue):
Creates a server socket for the specified port number with the specified
queue length. The MAXQueue parameter represents the maximum queue
length as integer type.
 ServerSocket(int PortNumber, int MAXQueue,
InetAddress LocalAddress): Creates a server socket for
the specified port number and the specified local host address.
LocalAddress represents the object of the InetAddress class
that specifies the IP address of that local host.
You can examine the status and the input/output stream associated with the
socket using the socket methods.

Self-Instructional
76 Material
Table 4.1 describes the various socket methods. InetAddress, TCP/IP
Client and Server Sockets
Table 4.1 Socket Methods

Methods Description
getInetAddress() Returns the IP address of the host computer. NOTES
getPort() Returns the port number of the host computer.
getLocalPort() Returns the port number of the local host.
getInputStream() Returns the input stream that is associated
with the socket.
getOutputStream() Returns the output stream that is associated
with the socket.
close() Closes the socket connection.

Creating a Server Program


The server program creates a server socket that can communicate with the client
socket using TCP/IP. The TCPServer class creates a server socket by using
an object of the ServerSocket class. The following program code shows
how to use the ServerSocket class to create a server socket:
Creating a Server Socket
import java.net.*;
import java.lang.*;
import java.io.*;
public class TCPServer
{
public static final int PORT = 1050;
public static void main( String args[])
{
ServerSocket server_socket = null;
Socket socket = null;
System.out.println(“ Server is waiting.... “);
try
{
server_socket = new ServerSocket(PORT);
System.out.println(“TCPServer has been
started :”+ server_socket);
try
{
// Creates a socket connection using
TCP/IP

Self-Instructional
Material 77
InetAddress, TCP/IP socket = server_socket.accept();
Client and Server Sockets
System.out.println(“TCPClient has been
connected :”+ socket);
// Receives the message from the
NOTES TCPclient system
DataInputStream dstream = new
DataInputStream(socket.getInputStream());
// Sends the message to the TCPclient
system
PrintStream pstream = new PrintStream
(socket.getOutputStream());
pstream.println(“Hello! TCPServer
here.”);
pstream.close();
socket.close(); // Terminate the
connection
}
catch(SocketException se)
{
System.out.println(“Error in server
socket “+ se.getMessage());
}
catch(Exception e)
{
System.out.println(“Error in server
starting”+ e.getMessage()) ;
}

System.out.println(“ Connection from : “ +


socket.getInetAddress());
}
catch(Exception e)
{
System.out.println(“Error in TCPServer “+
e.getMessage()) ;
}
} // End main()method
} // End of TCPServer class
The above code shows how to create a server socket at port number 1050.
The ServerSocket(PORT) creates a server socket of specified port number
and the socket() method creates a client socket. The server socket can
communicate with the socket using the methods, getInputStream() and
getOutputStream().
Self-Instructional
78 Material
Creating a Client Program InetAddress, TCP/IP
Client and Server Sockets
The client program creates a client socket that can communicate with the server
socket using TCP/IP. The TCPClient class creates a client socket using an
object of the Socket class. The following program code shows how to use the NOTES
Socket class to create the client socket:
Creating the Client Socket
import java.lang.*;
import java.io.*;
import java.net.*;
import java.net.InetAddress;
class TCPClient
{
public static void main(String args[])
{
Socket socket = null;
DataInputStream dstream = null;
PrintStream pstream = null;
System.out.println(“ Client is connecting to
TCPServer....”);
try
{
InetAddress ipadss
=InetAddress.getByName(“java.sun.com”);
socket = new Socket(ipadss,1050);
pstream = new
PrintStream(socket.getOutputStream());
pstream.println(“ Hi! TCPClient here.”);
DataInputStream istream = new
DataInputStream(socket.getInputStream());
System.out.println(istream.readLine());
}
catch(SocketException se)
{
System.out.println(“Error in sockets “ +
se);
}
catch(IOException ioe)
{
System.out.println(“Input/Output Errors “ +
ioe);

Self-Instructional
Material 79
InetAddress, TCP/IP }
Client and Server Sockets
finally
{
try
NOTES
{
socket.close(); // Closes the socket
}
catch(IOException ioe)
{
System.out.println(“ Socket closing
Errors:” + ioe.getMessage());
}
} // End finally block
} // End the main() method
} // End the TCPClient class
The above code shows how to create a client socket that can communicate
with the server of port number 1050. The client socket communicates with the
server using the methods, g e t I n p u t S t r e a m ( ) and
getOutputstream(). You can run the client and server program after
successfully compiling both the program.
Figure 4.3 shows the output.

Fig. 4.3 Running TCPServer

Figure 4.4 shows the output of the client and server program.

Fig. 4.4 Running TCPClient

Check Your Progress


3. What is internet address?
4. What is the use of client socket?

Self-Instructional
80 Material
InetAddress, TCP/IP
4.8 ANSWERS TO CHECK YOUR PROGRESS Client and Server Sockets

QUESTIONS

1. The getHostName () methods returns a string that contains the name NOTES
of the host with the IP address represented by the InetAddress object.
2. The isAnyLocalAddress() method returns true if the address is a
wildcard address, false otherwise.
3. Internet address, also known as Internet protocol (IP) address, is a unique
address assigned to each computer.
4. The client socket is used to connect the client to the server.

4.9 SUMMARY

 The InetAddress class does not have any public constructors. Rather,
InetAddress has static factory methods that connect to a DNS server to
resolve a hostname.
 The InetAddress class contains four getter methods that return the hostname
as a string and the IP address as both a string and a byte array.
 IPv4 addresses in the range 224.0.0.0 to 239.255.255.255 are multicast
addresses that send to several subscribed hosts at once.
 The InetAddress class has two isReachable() methods that test whether a
particular node is reachable from the current host.
 Internet address, also known as Internet protocol (IP) address, is a unique
address assigned to each computer.
 It is difficult to remember different IP addresses while connecting to the
Internet. You can use Domain Naming Service (DNS) for addressing this
problem that are also known as URLs.
 A networking protocol is a set of standard rules that provides the standard
for information exchange over the network.
 A port is a numeric address that requests for a Web page using different
protocols.
 TCP/IP sockets transfer the data over the network using the TCP/IP. TCP
sockets establish the connection between the host computers first and then
start sending the data.
 The server program creates a server socket that can communicate with the
client socket using TCP/IP. The TCPServer class creates a server socket
by using an object of the ServerSocket class.
 The client program creates a client socket that can communicate with the
server socket using TCP/IP. The TCPClient class creates a client socket
Self-Instructional
using an object of the Socket class. Material 81
InetAddress, TCP/IP
Client and Server Sockets 4.10 KEY WORDS

 Uniform Resource Locator (URL): It represents the address of a Web


NOTES page that enables you to find a resource on the Internet.
 Internet Protocol (IP): It is also known as Internet address, is a unique
address assigned to each computer.
 Networking Protocol: It is a set of standard rules that provides the standard
information for exchange over the network.
 Transmission Control Protocol and Internet Protocol (TCP/IP): It is
a set of rules for exchanging information between applications, across
networks.

4.11 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short-Answer Questions
1. Write a note on InetAddress.
2. What are the features of Networking?
3. What are client and server sockets?
4. What are the different types of gether methods?
Long-Answer Questions
1. Why do you need sockets in networking?
2. Explain the different types of addresses.
3. Write Java programs to create a chat application using the TCP/IP server
socket. In this application, a client can communicate with the server or
server can communicate with the client.
4. Write a code to implement socket connection.
5. What are the various methods of TCP/IP socket?

4.12 FURTHER READINGS

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
82 Material
URL Connection and

UNIT 5 URL CONNECTION AND Datagrams

DATAGRAMS
NOTES
Structure
5.0 Introduction
5.1 Objectives
5.2 URL and URL Connection Classes
5.3 Using UDP Sockets
5.3.1 Creating a Server Program
5.3.2 Creating a Client Program
5.4 Answers to Check Your Progress Questions
5.5 Summary
5.6 Key Words
5.7 Self Assessment Questions and Exercises
5.8 Further Readings

5.0 INTRODUCTION

URL Connection is an abstract class that represents an active connection to a


resource specified by a URL. The URL Connection class has two different purposes.
First, it provides more control over the interaction with a server (especially an
HTTP server) than the URL class. Java DatagramSocket class also represents a
connection-less socket for sending and receiving datagram packets. The Java
DatagramPacket is a message that can be sent or received. If you send multiple
packets, it may arrive in any order. Additionally, packet delivery is not guaranteed.
This unit will explain about URL Connections and Datagram.

5.1 OBJECTIVES

After going through this unit, you will be able to:


 Understand URL and its class
 Discuss DatagramSockets and their use
 Explain the functionality of URL Connection Class
 Analyse the commonly used methods of URL class
 Use UDP sockets to transmit data using the UDP protocol

Self-Instructional
Material 83
URL Connection and
Datagrams 5.2 URL AND URL CONNECTION CLASSES

Uniform Resource Locator (URL) represents the address of a Web page, which
NOTES enables you to find a resource on the Internet. You can access a specific Website
by typing its URL in the address bar of the Web browser. A URL is represented as
a string that explains the resource you are using on the Internet. For example,
www.google.com is a search engine, which you simply type in the address
bar for accessing information about any topic. The components of a URL are:
(i) Filename: Specifies the name of the file you are accessing.
(ii) Directory Name: Specifies the location of the file.
(iii) Host Name: Specifies the Internet host contacted for retrieving requested
documents.
(iv) Access Method: Specifies the protocol used for accessing the documents,
such as HTTP and FTP.
An example of a URL is http://www.utoronto.com/
webdocs/HTMLdocs/ New.html. In this URL, http is the protocol
used and locations are separated by forward slashes and colon (:). Protocol
identifiers can be FTP, Gopher, File and News that specify the address of the
resource on the Internet.
The java.net package provides the URL class that enables you to
create an instance of URL. The URL object refers to the address of the Internet
resource you want to access. The code to implement a URL in a class is:
URL myURL = new URL(“http://www.banner.com/”);
The above code shows the creation of URL object, myURL, for fetching
the Internet resource, www.banner.com.
You need to use various methods using which you can extract the protocol,
host name, port number and file name from the URL object. Table 5.1 lists the
various methods of the URL class.
Table 5.1 Various Methods of URL Class

Methods Description
getFile() Retrieves the name of file.
GetHost() Retrieves the host name included in URL string.
getPort() Retrieves the port number of the destination computer that
is connected with the URL.
getProtocol() Retrieves the protocol of the URL that is used as an
identifier.
getContent() Retrieves the content of the URL.
getRef() Retrieves the reference of the URL.

You can implement the URL in your defined class and use various methods.
The following program code shows how to implement URL:
Self-Instructional
84 Material
Implementing URL URL Connection and
Datagrams
import java.net.*;
import java.io.*;
public class newURL NOTES
{
public static void main(String args[])throws Exception
{
URL myURL = new URL(“http://www.utoronto.com/webdocs/
HTMLdocs/New.html”);
System.out.println(“Protocol used: “ +
myURL.getProtocol());
System.out.println(“Host name: “ + myURL.getHost());
System.out.println(“Port number: “ + myURL.getPort());
System.out.println(“File name: “ + myURL.getFile());
}
}
The above code shows retrieving the protocol, host name, port number and
the file name of the given URL. Figure 5.1 shows the output generated by the new
URL class.

Fig. 5.1 Output of the newURL.java Class

An object of the URLConnection class enables you to perform general


communication, such as reading, writing and querying from the URL. You create
an object of the URLConnection class using the openConnection()
method available in the java.net package. URLConnection is a super
class that represents the communication link between the URL and the application
executing on the network. The code to create an object of the URLConnection
class is:
URLConnection UrlCon= UrlCon.openConnection();
The above code shows the openConnection () method that creates
an instance of URL connection, initializes the link between the Java program and
the URL and returns an object of the URLConnection class.
You can use several methods of the URLConnection class to retrieve
the information. Table 5.2 describes the various methods of the URLConnection
class.

Self-Instructional
Material 85
URL Connection and Table 5.2 Various Methods of the URLConnection Class
Datagrams
Methods Description
getContentEncoding() Retrieves the data encoding that is used for data
transfer.
NOTES getContentLength() Retrieves the length of a URL string in bytes.
getContentType() Retrieves the content type of a URL, such as
MIME type data.
getExpiration() Retrieves the time of expiration of a URL.
getLastModified() Retrieves the last modified data of a URL.

You implement the URLConnection class in your defined class and


use its various methods. The following program code shows how to implement
the URLConnection class:
Implementing the URLConnection Class
import java.net.*;
import java.io.*;
public class URLTest
{
public static void main(String args[]) throws Exception
{
URL myURL= new URL(“http://192.168.0.207:8000/”);

URLConnection Ucon=myURL.openConnection();
BufferedReader br = new BufferedReader(new
InputStreamReader(Ucon.getInputStream()));
String istream;
while ((istream = br.readLine()) != null)
System.out.println(istream);
br.close();//stream close
//Declaration of Content type variable
String CntType=Ucon.getContentType();
System.out.println(“Format of the page content
is:” +CntType);
long EXP=Ucon.getExpiration();
System.out.println(“URL Expiration is:”+EXP);
//for storing length of content type
int Clen=Ucon.getContentLength();
System.out.println(“Length of page is:”+Clen);
//Declaration input stream type variable
}
}

Self-Instructional
86 Material
The above code shows the contents of page mentioned in the URL. The URL Connection and
Datagrams
code also shows the days of expiration of URL and the length of page. Figure 5.2
shows the output generated by implementing the URLTest.java class.

NOTES

Fig. 5.2 Output of the URLTest.java Class

5.3 USING UDP SOCKETS

UDP sockets exchange data over the network by using the User Datagram Protocol
(UDP). UDP is a connectionless protocol that can send data in the form of data
bundles called as datagram that consists of the destination address. UDP is a less
reliable protocol than TCP/IP because it cannot create a connection between the
host computers. UDP sockets are used for sending data without establishing a
connection between the host computers. Java provides two classes for creating a
UDP socket, DatagramPacket and DatagramSocket.
The DatagramPacket class creates the datagram packet that stores
information in the form of an array. The datagram packets can be transmitted over
the network using the UDP. Java provides two constructors for the
DatagramPacket class. The two constructors are:
(i) DatagramPacket(byte data[], int size): Creates
datagram packets of specified size. The parameter, data[]
represents an array that stores the information. The parameter, size,
indicates the maximum size of packet that can be transmitted over the
network.
(ii) DatagramPacket(byte data[], int size,
InetAddress IPAddress, int port): Creates the
datagram packets of specified size, IP address and port number. The
parameter, IPAddress, represents the IP address of the target
host and parameter port represents the port number of the target host.
The DatagramSocket class creates a socket that controls the
transmission of datagram packets across the network. The object of the
DatagramSocket class always throws an exception, SocketException
at the time of datagram packet transmission over the network. Java provides two
types of DatagramSocket constructors for creating the socket. The two
constructors are:
(i) DatagramSocket(): Creates a default socket that transmits a
datagram packet across the network.
(ii) DatagramSocket(int port): Creates a socket that can
transmit a datagram packet to the host of specified port number across
the network. Self-Instructional
Material 87
URL Connection and You can send or receive the datagram across the network using the datagram
Datagrams
methods. There are several methods for accessing the state of the datagram packet.
Table 5.3 describes the various socket methods.
Table 5.3 Datagram Methods
NOTES
Method Descriptions
send(DatagramPacket dp) Sends the datagram packet to the specified host.
Receive(DatagramPacket Retrieves the datagram packet from the
dp) specified host.
getLength() Returns the length of the datagram packet.
getAddress() Returns the IP address of local host.
getPort() Returns the port number of the specified host.
close() Closes the socket connection.

5.3.1 Creating a Server Program


A server program creates the datagram packets and server socket, which enable
the server to transmit the datagram packet over the network using UDP. The
UDPServer class creates the datagram and server socket. The following program
code shows how to create a server socket using the DatagramSocket class:
Creating a Server Socket
import java.net.*;
import java.io.*;
public class UDPServer
{
static final int SPORT = 1050;
static final int SIZE = 1024;
public static void main(String args[]) throws
SocketException
{
DatagramPacket dpacket;
DatagramSocket dsocket;
byte[] data;
int CPORT;
InetAddress adss;
String str;
dsocket = new DatagramSocket(SPORT);
for(;;)
{
data = new byte[SIZE];
dpacket = new DatagramPacket(data, SIZE);
System.out.println(“UDPServer is waiting to
receive the data packets”);
Self-Instructional
88 Material
try URL Connection and
Datagrams
{
dsocket.receive(dpacket);
}
NOTES
catch(IOException ie)
{
System.out.println(“Input/Output
Error:” + ie.getMessage());
System.exit(0);
}
adss = dpacket.getAddress();
CPORT = dpacket.getPort();
str = new
String(data,0,0,dpacket.getLength());
System.out.println(“Message :”+
str.trim());
System.out.println(“From :”+adss);
dpacket = new DatagramPacket(data,SIZE,
adss,CPORT);
try
{
dsocket.send(dpacket);
}
catch(IOException ioe)
{
System.out.println(“Input/Output Error
“+ ioe.getMessage());
System.exit(0);
}
} // End for loop
} // End the main() method
} // End the UDPServer class
The above code shows how to create a server socket and datagram packet.
The DatagramSocket(PORT) creates a server socket at port number 1050
and the DatagramPacket() method creates the datagram packets of size
1024. The local host can communicate with the target host using the methods,
getInputStream() and getOutputStream() and the data is
transferred over the network using the methods, send() and receive().
5.3.2 Creating a Client Program
A client program creates a client socket that can communicate with the server
socket by using UDP. The UDPClient class creates a client socket using the
Self-Instructional
Material 89
URL Connection and object of the DatagramSocket class. The following program code shows
Datagrams
how to create a client socket using the Socket class:
Creating a Client Socket
NOTES import java.net.*;
import java.io.*;
public class UDPClient
{
static final int SPORT = 1050;
static final int SIZE = 1024;
public static void main(String args[]) throws
UnknownHostException, SocketException
{
DatagramSocket dsocket;
DatagramPacket dpacket;
InetAddress adss;
String msgSend;
String msgRecieve;
byte[] data;
if(args.length != 2)
{

System.out.println(“UDP Error : Java


UDPClient <Server-name> <message>”);
System.exit(0);
}
// Retrieves the IP address of the UDPServer
adss = InetAddress.getByName(args[0]);
dsocket = new DatagramSocket();
data = new byte[SIZE];
msgSend = new String(args[1]);
msgSend.getBytes(0,msgSend.length(),data,0);
dpacket = new DatagramPacket(data, data.length,
adss, 1050);
System.out.println(“ UDPClient is trying to
send the data packet.... “);
try
{
dsocket.send(dpacket);
}
catch(IOException ie)
{
Self-Instructional
90 Material
System.out.println(“Input/Output Error “ + URL Connection and
ie.getMessage()); Datagrams

System.exit(0);
}
dpacket = new DatagramPacket(data, NOTES
data.length);
try
{
dsocket.receive(dpacket);
}
catch(IOException ioe)
{
System.out.println(“Input/Output Error “+
ioe.getMessage() );
System.exit(0);
}
msgRecieve = new String (dpacket.getData(),0);
System.out.println(“Message Returned : “+
msgRecieve.trim());
} // End the main() method
} // End the UDPClient class
The above code shows how to create a client socket and datagram packets
that can be transmitted to the server of port number 1050. The datagram packet
is transmitted using the send() method and received using the receive()
method.
You can run the client and server program after successfully compiling both
the programs. The server program runs on the server computer and the client
program runs on the client computer.
Figure 5.3 shows the output of the program that uses the UDP server.

Fig. 5.3 Running the UDPServer

Figure 5.4 shows the output of the program that uses the UDP client.

Fig. 5.4 Running the UDPClient

Self-Instructional
Material 91
URL Connection and This UDPServer class waits for receiving the datagram packets from
Datagrams
the UDPclient class after starting the server. The UDPClient class sends
the datagram packet, when you pass the IP address and message packet as
parameter. The server receives that datagram packet and again waits for the next
NOTES datagram packet if next datagram packets are not available.

Check Your Progress


1. Define URL.
2. What is datagram?
3. What is the significance of URLConnection class?

5.4 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. URL is an acronym for Uniform Resource Locator. URL is a string of text


that identifies all the resources on Internet, telling us the address of the
resource, how to communicate with it and retrieve something from it.
2. A datagram is nothing but an encapsulated data packed in a unit that is
meant for transferring from one node.
3. URLConnection class is a general purpose class that is used for accessing
the attributes of any remote resources.

5.5 SUMMARY

 Uniform Resource Locator (URL) represents the address of a Web page,


which enables you to find a resource on the Internet. You can access a
specific Web site by typing its URL in the address bar of the Web browser.
 An object of the URLConnection class enables you to perform general
communication such as reading, writing and querying from the URL. You
create an object of the U R L C o n n ec ti on class using the
openConnection() method available in the java.net package.
 UDP sockets exchange data over the network by using the User Datagram
Protocol (UDP). UDP is a connectionless protocol that can send data in
the form of data bundles called as datagram that consists of the destination
address.
 The DatagramPacket class creates the datagram packet that stores
information in the form of an array.
 The DatagramSocket class creates a socket that controls the
transmission of datagram packets across the network.
Self-Instructional
92 Material
URL Connection and
5.6 KEY WORDS Datagrams

 URLConnection Class: It is a general purpose class that is used for


accessing the attributes of any remote resources. NOTES
 DatagramSocket: These are used to send and receive datagram packets
over the web.

5.7 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short-Answer Questions
1. What are DatagramSockets?
2. Write a note on URL and its class
3. Discuss DatagramSockets and their use.
4. Discuss the functionality of URL Connection Class.
Long-Answer Questions
1. Analyse the commonly used methods of URL class.
2. Differentiate between DatagramPacket and DatagramSocket.
3. How do you Display the source code of a webpage by URLConnecton
class? Support your answer with the help of an example.

5.8 FURTHER READINGS

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
Material 93
Client and Server
Applications Using RMI
UNIT 6 CLIENT AND SERVER
APPLICATIONS USING RMI
NOTES
Structure
6.0 Introduction
6.1 Objectives
6.2 N-Tier Architecture
6.3 Overview of RMI
6.4 Distributed Object Technologies
6.5 Locating and Loading Remote Classes
6.6 Locating Remote Objects
6.7 Enabling Remote Method Class
6.8 Creating a Client Class
6.9 Transferring Non Remote Objects
6.10 Handling Exceptions
6.11 Executing RMI
6.12 Implementing Callbacks
6.13 Distributing the RMI Application
6.14 Using Applets with RMI
6.14.1 Defining Server Class
6.14.2 Defining Remote Interfaces
6.14.3 Defining Client Class
6.14.4 Creating the HTML File
6.14.5 Executing the RMI with Applet
6.15 RMI Architecture
6.15.1 Application Layer
6.15.2 Proxy Layer
6.15.3 Transport Layer
6.16 Socket versus RMI Programming
6.17 Answers to Check Your Progress Questions
6.18 Summary
6.19 Key Words
6.20 Self Assessment Questions and Exercises
6.21 Further Readings

6.0 INTRODUCTION

This unit introduces the concept of distributed architecture using N-Tier and
distributed object technologies. In this unit, you will learn how to locate and load
Java classes on a remote machine. After loading the remote classes, you need to
create and locate objects of the remote machines. You will learn how to enable the
remote method class to listen to a client request.

Self-Instructional
94 Material
You can implement callbacks from a server to the client to send error Client and Server
Applications Using RMI
messages and acknowledgements. You can also distribute the application over the
network to implement RMI on distributed systems. RMI can be integrated with
applets to enhance user interactivity. This unit also describes various layers in the
RMI architecture such as application layer, proxy layer, remote reference layer NOTES
and transport layer. In addition, you will learn the differences between socket
programming and RMI programming.

6.1 OBJECTIVES

After going through this unit, you will be able to:


 Understand the use of distributed object technologies to access a Java
program in a distributed environment
 Use applets with RMI to enhance interactivity with the user
 Create a client class to execute RMI
 Locate and load remote classes to invoke methods on remote JVM
 Use N-Tier Architecture to determine the distributed environment
 Execute the Remote Method Invocation

6.2 N-TIER ARCHITECTURE

The N-tier architecture allows a programmer to represent the concept of client-


server architecture using various tiers such as presentation logic and business logic.
In the N-tier architecture, a user is presented with GUI at the front tier and data
present in the database at the back tier. The presentation and business logic required
to process the data is presented at middle tiers of the N-tier architecture. Various
tiers in the N-tier architecture represent partition between the operation and
interaction required at various levels.
Figure 6.1 shows the N-tier architecture.
1-tier 2-tier n-tier

Request Request Request


Reply Reply Other Tier

Web Client
Web Business Database
Server Logic Server
(Presentation) Server

Fig. 6.1 The N-Tier Architecture

Self-Instructional
Material 95
Client and Server The above figure shows the Web server at the first tier of the client server
Applications Using RMI
architecture. The second tier consists of the business logic server and the N-tier
consists of the database server that sends response to all the queries sent by the
clients.
NOTES
6.3 OVERVIEW OF RMI

Distributed applications contain objects that are distributed over a network. The
objects communicate with each other using a standard protocol such as TCP/IP.
The client object sends a request in the form of a message to the object present on
the server. The server reads the client request to collect the information about
fulfilling the request such as the name of the method called by the client and the
parameters required by the method. The answer to the request is returned to the
client.
In a client/server architecture, the request of the client object and the response
from the server object are converted to an intermediate format such as name/
value pairs. The intermediate format used to represent the messages is dependent
on the technology used to create the client and server objects. Hence, it becomes
important to know the technology used to create client and server objects. For
example, the intermediate format to send messages between two objects such as
a client and a server, written in Java, is different from the format used in case if
either client or server object is written in C++. If the client object is created in
Java, then either the server object can be created in Java or it can be created using
other technology such as C++. If the server objects are not created in Java, the
communication between the client and the server is difficult as both the client and
the server objects use different technology. In this case, Common Object Request
Broker Architecture (CORBA) is used. CORBA like RMI makes possible the
communication between the client and the server objects written in different
technologies. CORBA specifies the mechanisms to transfer data. However,
CORBA is difficult to implement and is slow in performance too.
In the second case, if both client and server objects are written in Java, then
you do not need to consider the complexities while implementing CORBA. Sun
Microsystems has developed RMI, specifically designed to be used when both
the client and server objects are written in Java. RMI like CORBA enables transfer
of data between the client and the server objects. As compared to CORBA, RMI
is easier to perceive and use.
In RMI, the Java object that calls a method remotely is called the client
object. The remote Java object whose method is invoked is called the server
object. In RMI however, the client/server terminology applies to only single method
call. The server object for an earlier call can become the client in the next call if it
calls a method remotely on a Java object present on a different computer.

Self-Instructional
96 Material
Client and Server
6.4 DISTRIBUTED OBJECT TECHNOLOGIES Applications Using RMI

In Remote Method Invocation (RMI), if you have the rights to access a Java
object present on a different computer over a network, then you can call the NOTES
methods defined in it. The accessible Java object is called a distributed object.
Therefore using RMI, you can distribute the objects over a network that can
communicate with each other. RMI is identical to Remote Procedure Call (RPC)
used in C/C++ to call methods remotely over a network.
You need to pass parameters over the network to call the method of a
remote object. The process of passing the parameters to the remote object is
called parameter passing. When the client object is calling a method of the server
object, this call is similar to the normal method call of Java programming language.
Therefore, the remote method call may need to transfer parameters to the server
object also. The parameters to be passed are stored in a proxy object called a
stub. It contains all the parameters required for the method call. The stub object is
stored on the client machine.
The process of encoding the parameters to be stored in the stub object is
called parameter marshalling. The purpose of parameter marshalling is to convert
the parameters into an appropriate format so that they can be transported from
one Java Virtual Machine (JVM) to another. A stub object contains all the marshalled
parameters, a message describing the method to be called and a remote object
identifier to identify the remote object whose method needs to be called.
The stub passes the information it contains to the server automatically. At
the server, a receiver object, called as skeleton, receives all the information contained
in the stub. The receiver object performs the following actions to fulfill the client
request:
1. Retrieves all the parameters from the stub object.
2. Locates the object that is called.
3. Calls the method of the object.
4. Collects the result after executing the method.
5. Sends the result back to the client.
The client stub object then receives the result of the execution of the remote
method sent back by the server.
Whenever an application loads new data from another location over a
network, security becomes important to protect the application from viruses. As a
result, you need to use a security manager, which is a security mechanism, in the
client that manages all the security issues.

Self-Instructional
Material 97
Client and Server
Applications Using RMI 6.5 LOCATING AND LOADING REMOTE
CLASSES

NOTES Locating and loading remote classes include creating and checking the RMI
application. You need to check the RMI application on both the client and server
computers by placing the required files of the application, which contains the client
classes, server classes and required interfaces at both client and server location.
An RMI application contains more than one file, which is required by the client
objects or the server objects. The client object needs the files to know about the
methods present in the server class. The server object needs the files to get
information about the client itself. In addition, the client uses a special lookup
mechanism to locate the objects on the server.
interface Customer extends Remote{
public String[] customerDetails() throws
RemoteException;
}
You can create an RMI application either on a single computer or on a set
of computers connected through a network. However, the network services such
as TCP/IP protocol should be available to test a RMI application on a single
computer after creating it. The client calls the method that is present on the server
so it should have the required information about the methods present in the server
class. To inform the client about the required information, you need to create an
interface that is shared between the client and the server. The interface contains
the signatures of those methods that the client can access of the remote server.
The code to create an interface that represents a remote object is:
In the above code, the interface, Customer, is defined for remote objects.
The Customer interface extends the Remote interface. All the interfaces for remote
objects must extend the Remote interface that is defined in the java.rmi
package. All the methods of this interface must throw RemoteException
because the remote method calls are very sensitive to network errors and there is
great possibility for the failure of the network call. In case of failure, the remote
method will throw RemoteException. The Customer interface must be
available to client as well as to server, as both of them share the interface.
On the server machine, there must be a class available that contains the
methods defined in the remote interface. If there is no such class, you need to
create it by extending the UnicastRemoteObject class. The class that
extends the UnicastRemote Object class acts as the server for remote
interface. The UnicastRemoteObject class provides the functionality to
make an object remotely accessible. The following program code shows how to
extend the UnicastRemoteObject class:

Self-Instructional
98 Material
Creating a Server Class for Remote Client Client and Server
Applications Using RMI
public class CustomerImpl extends UnicastRemoteObject
implements Customer{
public CustomerImpl() throws RemoteException{
//The constructor is also throwing
NOTES
// RemoteException
}
public String[] customerDetails(){

}
}
The above code shows the CustomerImpl class that extends the
UnicastRemote Object class and implements the Customer remote
interface created earlier. The constructor of this class is also throwing the
RemoteException. As this class implements the Customer remote interface,
it also defines the customerDetails() method of the Customer remote
interface.
Every server class needs to extend the RemoteServer class of the
java.rmi.server package, but this class does not define any method, as
it is an abstract class. However, the UnicastRemoteObject class extends
the RemoteServer class and defines all its methods. This is why the
CustomerImpl class created earlier extends the
UnicastRemoteObject class.
Figure 6.2 shows the inheritance hierarchy in UnicastRemoteObject
class.

Fig. 6.2 Inheritance Hierarchy for the UnicastRemoteObject Class

Self-Instructional
Material 99
Client and Server This figure shows the RemoteObject class that extends the Object
Applications Using RMI
class and implements the Remote interface. The RemoteServer class extends
the RemoteObject class. The RemoteServer class is an abstract class
as it contains only method signatures. The UnicastRemoteObject class
NOTES extends the RemoteServer class and defines all the methods of the
RemoteServer class.
The server class that you define extends the UnicastRemoteObject
class. The client can access the server class using the TCP/IP protocol.
The client class uses a stub that implements the remote interface to access
the server object. The code to access the server object:
Customer c = …;
String[] s = c.customerDetails();
for( int i=0; i<str.length(); i++)
System.out.println( s[i] );
In the above code, a reference to the stub object of Customer interface is
created that is used to access the method of the server. When the client invokes
the Customer interface method using the stub object reference, a request is sent to
the server object through the network. On the server, the skeleton object receives
the request and invokes the required method by parsing the request message. The
result of the execution of the method is returned to the client.
Table 6.1 describes the naming conventions that you can use while creating
an RMI application.
Table 6.1 Naming Conventions

Naming Convention RMI Class


No suffix Represents the name of the remote interface.

Impl suffix Represents the server class that implements the remote
interface.
Server suffix Represents the class that creates the server objects.

Client suffix Represents the client program that accesses the remote
methods.
_Stub suffix Represents the name of the stub class.
_Skel suffix Represents the name of the skeleton class.

You need to create a stub class for the CustomerImpl class because
this class implements the Remote interface. You need to create a stub class for
those classes that implement the Remote interface. The rmic tool is used to create

Self-Instructional
100 Material
the stub classes automatically. The code to create the stub class for the Client and Server
Applications Using RMI
CustomerImpl class using the rmic tool is:
rmic CustomerImpl
The above code creates two classes, a stub class and a skeleton class. NOTES
However, before using the rmic tool to create the stub class, you need to compile
the Java source files such as CustomerImpl class using the javac utility.

6.6 LOCATING REMOTE OBJECTS

The client uses a stub object to access the remote object that exists on the server,
but how can the client get the stub object. The stub object must be registered
somewhere by the server to enable the client to access it. The simple method for
the client to access a stub object is to call a remote method of another server
object that returns the stub object. The RMI library contains the utility,
rmiregistry, to register the stub objects, which is also called the bootstrap
registry service. The server registers objects at the bootstrap registry service and
the client uses this bootstrap registry service to get the stub objects. You can
register a server object to bootstrap registry service by passing the bootstrap
registry service a name, which is used by the client to access the stub object using
the lookup mechanism and a reference to the object that needs to be registered.
The code to register a CustomerImpl object is:
CustomerImpl ci = new CustomerImpl(“first”);
Naming.bind(“Customer1”, ci);
In the above code, the reference, ci, to the CustomerImpl class is
passed to the bootstrap registry service. The bind() static method of the
Naming class is used to register the object. Customer1 represents the name
for the registered object. Try to specify unique names that are not used earlier to
register some other remote objects. The client gets a stub object by specifying the
server and object name. The following code shows how to get a stub object:
Customer c = (Customer)Naming.lookup(“rmi://ServerName/
Customer1”);
In the above code, the ServerName represents the name of the server.
If you are testing the application locally, then you have to use localhost instead of
ServerName in the lookup() method. The string, localhost refers
to the local computer if the server object is running on the same machine where the
client is running. Customer1 represents the name used by the server to register
the remote object. The lookup() static method of the Naming class is used to
locate the remote object. The parameter of the lookup() method represents
a RMI URL that starts with rmi://, followed by the server name, an optional
port number, a slash and then a name of the remote object as shown in the above
code. The default port number is 1099.

Self-Instructional
Material 101
Client and Server
Applications Using RMI 6.7 ENABLING REMOTE METHOD CLASS

You can create a RMI server by extending the UnicastRemoteObject


NOTES class. The code to show a remote interface, Customer, which will be used later to
create a stub object, is:
import java.rmi.*;
public interface Customer extends Remote{ String
getFullName() throws RemoteException;
}
In the above code, the interface contains the signature of one method,
getFull Name(). As Customer is a remote interface, the method needs to
throw a Remote Exception. The following program code shows the
CustomerImpl class that implements this remote interface:
import java.rmi.*;
import java.rmi.server.*; public class CustomerImpl
extends UnicastRemoteObject
Implementing the Customer Interface

implements Customer{
public CustomerImpl(String firstName, String
middleName, String lastName) throws RemoteException{
this.firstName = firstName; this.middleName =
middleName; this.lastName = lastName;
}
public String getFullName() throws RemoteException{
if(middleName == “”)
return “The fullname is : “ + firstName+ “ “+ lastName;
else
return “The fullname is : “ + firstName+ “ “+
middleName+ “ “+ lastName;
}
private String firstName, middleName, lastName;
}
The above code shows the CustomerImpl class that is a server class
as it extends the UnicastRemoteObject class. This class defines the
getFullName() method of the Customer remote interface. The
getFullName() method of the CustomerImpl class returns the full
name of the customer as a String object. The following program code shows the
CustomerServer class that will bind the CustomerImpl objects to
the bootstrap registry service:

Self-Instructional
102 Material
Registering CustomerImpl Objects Client and Server
Applications Using RMI
import java.rmi.*;
import java.rmi.server.*; import sun.applet.*;
public class CustomerServer{
NOTES
public static void main(String arg[]){ try{
System.out.println(“Implementing server”);
CustomerImpl c1 = new CustomerImpl(“Lalit”, “”,
“Kapoor”);
CustomerImpl c2 = new CustomerImpl(“Sumit”, “Kr.”,
“Sharma”);
System.out.println(“Binding remote server objects to
Bootstrap Registry Service”);
Naming.rebind(“Lalit”, c1); Naming.rebind(“Sumit”, c2);
System.out.println(“Binding complete,
Server is ready”);
}catch(Exception e){ System.out.println(“Error : “+e);
}
}
}
In the above code, the Naming.rebind() method is used to register
objects, Lalit and Sumit, to the bootstrap registry service. After creating the classes
required to start the server, you need to compile all the classes. Save all Customer,
CustomerImpl and CustomerServer files in a single directory and
compile all the files. After compiling the files, you need to create the stub class. To
create the stub class, use the rmic tool, as shown in the following code:
rmic CustomerImpl
The above code will create stub and skeleton classes automatically. After
they are created, use the rmiregistry tool to invoke the bootstrap registry
service. The following code shows how to start the bootstrap registry service in
Windows from the DOS prompt:
start rmiregistry
In the above code, the start command of the Windows operating system is
used to start the bootstrap registry service in a new window. The following code
shows how to start the bootstrap registry service in Unix:
rmiregistry &
After starting the rmiregistry, you can start the server. The code to start the server
is:
java CustomerServer
The above code starts the server represented by CustomerServer. A
separate thread starts that runs indefinitely when the objects of a class that extends
the UnicastRemoteObject class is created. The main() method of the
CustomerServer class runs indefinitely. Therefore, the CustomerServer
class runs indefinitely to allow the clients to send request to it. Self-Instructional
Material 103
Client and Server
Applications Using RMI
Check Your Progress
1. What does the N-tier architecture allow a programmer to do?
NOTES 2. What do distributed applications contain?

6.8 CREATING A CLIENT CLASS

The client needs to capture a stub object to send requests to the object present on
the server. The lookup() method of the Naming class is used to get the stub
of the remote object. The client to call the methods defined in the server object
then uses the stub object. The reference to the stub object is of remote interface
type defined for the server. Therefore, the client can access the method signature
defined in the remote interface. The following program code shows the
CustomerClient class that retrieves the stub to the registered objects:
Creating the CustomerClient Class
import java.rmi.*;
import java.rmi.server.*; public class CustomerClient{
public static void main(String arg[]){
System.setSecurityManager( new
RMISecurityManager());H
String url = “rmi://localhost/”; try{
Customer c1 = (Customer)Naming.lookup(url+”Lalit”);
Customer c2 = (Customer)Naming.lookup(url+”Sumit”);
System.out.println(c1.getFullName());
System.out.println(c2.getFullName());
}catch(Exception e){ System.out.println(“Error : “+ e);
}
System.exit(0);
}
}
The above code shows the CustomerClient class. The first statement
in the m a i n ( ) method is used to create an object of the
SecurityManager() class that will handle all the security issues for the
client The SecurityManager object is important because the RMI clients
can load the stub classes from other locations such as RMI servers. The Security
Manager restricts the client from violating any permission granted to the server.
For example, the client cannot access files at the server computer that the server
object can access. The client cannot manipulate files from the server’s file system
because of the S e c u r i t y M a n a g e r object. After creating the
SecurityManager object, the getFullName() method of both the
Self-Instructional
104 Material
stub objects are executed. The exit() method is used to terminate the client Client and Server
Applications Using RMI
program.
To enable the client to connect to the server object, you need to supply the
policy file. The policy file enables the client to get any network connection. The
NOTES
code to give the network permission to the client between port numbers 1024 to
65535 is:

grant{
permission java.net.SocketPermission “*:1024-65535”,
“connect”;
};
The above code gives SocketPermission to the client. Save this
file in the C:/Windows folder as java.policy.
Save the CustomerClient class in the folder where the server classes
are stored. Then move to that folder, compile the client class and execute it. The
output when the CustomerClient class executes is:
The fullname is: Lalit Kapoor
The fullname is Sumit Kr. Sharma. The above code shows the output
of the CustomerClient class. The client calls the getFullName()
method of the server class that returns a String object representing the full name of
the registered Customer objects.

6.9 TRANSFERRING NON REMOTE OBJECTS

You can pass and retrieve any object through a remote call including those that
implement the Remote interface. For example, in the CustomerClient class,
the getFullName() method returns a String object that does not implement
the Remote interface. This is because the client gets a copy of the String object.
A nonremote object is an object of that class that does not implement the
Remote interface. Whenever a nonremote object needs to be passed from one
JVM to another, the JVM creates a copy of the object and sends it over the
network. The RMI mechanism uses the serialization mechanism to send objects
across the network. The RMI mechanism creates multiple copies of nonremote
objects if they implement the Serializable interface.
Note: The remote objects are passed as stubs across the network, but the nonremote
objects are copied using the Serialization mechanism.
In case of passing remote object, only the methods defined in the remote
interface can be accessed through the stub. The client cannot access any method
of the class that is not defined in the remote interface. The stubs are generated only
for the classes that implement the Remote interface. If the subclass does not
implement the Remote interface but the superclass does, then only the methods of
the superclass are accessible to the client. Self-Instructional
Material 105
Client and Server
Applications Using RMI 6.10 HANDLING EXCEPTIONS

In any distributed application, catching exception is a difficult and mandatory


NOTES process because an exception can occur at the client object or the server object
or an exception can be raised because of a network error. To enable the client to
handle every possible exception during a remote method call, it should catch every
exception thrown by the server. The client can catch either generic Java exceptions
defined in the java.lang package or specific RMI exceptions defined in the
java.rmi package.
The Remote Exception class is the parent class of all the RMI specific
exception classes. The other exception classes include
AlreadyBoundException and NotBoundException to catch
the exceptions thrown by the bootstrap registry service. In addition, the invocation
to RMI object methods throws four types of exceptions:
 UnknownHostException
 StubNotFoundException
 NoSuchObjectException
 RMISecurityException
The following program code shows how to catch RMI exceptions: Catching
RMI Exceptions
package java.rmi;
public class CustomerClient{ public Client(){
//Capture the remote object form registry try{
Remote remoteObject = Naming.lookup(“SERVER”);
}catch (java.rmi.NotBoundException exc){
System.out.println(“Error in lookup()”+
exc.toString());
}
// getting the specific one ServerInterface Server;
if(remoteObject instanceof Server)
Server = (ServerInterface) remoteObject;
// Invoking the object try
{
System.out.println(“Total is:”+ Server.getTotal());
}catch (java.rmi.RemoteException exc){
System.out.println(“Errorininvocation”+
exc.toString());
}
}
}

Self-Instructional
106 Material
The above code shows the Client class. The Naming.lookup() Client and Server
Applications Using RMI
method throws NotBoundException so it is caught using the try catch
block. Similarly, the remote method invocation to the getTotal() method of
the Server class throws a RemoteException, so it is also encapsulated
inside the try catch block. NOTES

6.11 EXECUTING RMI

All the files in the Customer application created earlier are stored locally in a
folder to find any error in the RMI application. You should always test your
application locally before deploying it on the network. You need to save the files at
both the client and the server computer of the RMI application to make it a
distributed application.
Before saving the files at the client and server computer, create two folders,
client and server, on the local computer. The client folder will store all the files
required by the client object and the server folder would store all the files related
to server object.
For example, in the Customer application created earlier, the following files
will be stored in the server folder:
 CustomerServer.class: This file represents the class used to
create server objects.
 CustomerImpl.class: This file represents the server class used
to implement remote interface.
 Customer.class: This file represents the name of the remote
interface.
 CustomerImpl_Stub.class: This file represents the name of
the Stub class.
The CustomerImpl.class file is used to define methods that are
required to access the methods define in the remote interface. The methods defined
in the remote interface are implemented by extending the
UnicastRemoteObject. The UnicastRemoteObject provides
functionality to make the objects available from the remote machines.
The client needs to define an interface that contains the signatures of the
methods of the server class available to the client to be accessed. This interface
gives access to the client to access the methods defined in the server. The interface
enables the client to use the remote object’s method as if it is a local method.
After saving the above files in the server folder, you need to store files in the
client folder. Store the following files in the client folder:
 CustomerClient.java: This file represents the client programs
that accesses the remote methods.
Self-Instructional
Material 107
Client and Server  CustomerClient.class: This file represents the client program
Applications Using RMI
that accesses the remote method.
 Customer.class: This file represents the name of the remote
interface.
NOTES
Move the client folder to the client computer. Create a policy file on the
client computer to enable the client to make network connections. You need to
change the RMI URL in the CustomerClient.java file to enable the
client to access the server.
Open the CustomerClient.java file and change the RMI URL
by specifying the name or the IP address of the server in place of localhost. The
new URL will enable the client to access the server. The code to represent the
RMI URL to access the server with IP address 192.168.0.124 is:
String url = “rmi://192.168.0.124/”;
After changing the URL, compile the source file again and run the client
program. The client will receive a reference to the stub object of the registered
server object using the bootstrap registry service. The Naming.lookup()
method will look for the registered objects and will return a stub object for it. The
client will use that stub to execute the remote server object methods.

6.12 IMPLEMENTING CALLBACKS

The server itself can make a remote call back to the client such as sending a
warning for an error, a progress feedback or sending a message from one client to
another. To enable the server to call the methods of a client, the client also needs
to work like an RMI server. However, the client class cannot extend the
UnicastRemoteObject class of the java.rmi.server package
because only the server class extends the UnicastRemteObject class.
To enable the server to connect to the client, the client must make itself available
to receive the calls from the server. The exportObject() method of the
UnicastRemoteObject class makes the client available to receive the
incoming calls from the server. The syntax to use the exportObject method
is:
public static RemoteStub exportObject(Remote obj) throws
RemoteException
In the above syntax, the exportObject() method takes a Remote
object as parameter and returns a RemoteStub object. The remote object,
obj passed as parameter becomes available to receive calls from the server.
The exportObject() method is a static method.

Self-Instructional
108 Material
Client and Server
6.13 DISTRIBUTING THE RMI APPLICATION Applications Using RMI

To execute the RMI application over the network, you need to place the required
class files at the locations that can be accessed by the server and the clients. The NOTES
files that are required by the server are:
 Remote interfaces definitions
 Stubs classes
 Skeletons classes
 All other server classes
The following class files should be available for the client:
 Stubs classes
 Remote interface definitions
 Server classes of objects used required by the client (such as return
values)
 All other client classes
In addition to the above requirements, you also need to make a change in
the Client class code. In the Client.java class, you need to change the
rmi string from rmi://localhost/server to rmi://
ServerName/server. Here, ServerName represents the name of the
server where the bootstrap registry service is running. For example,
192.168.0.124 represents a name of the server, so a valid rmi string is
rmi://192.168.0.124/server. You can also specify a port number
that the server is using to fulfill the client request after the server name. The code to
show the rmi string that contains the default port number, 1099, with the server
name is:
rmi://192.168.0.124:1099/server
The port number is optional to be specified in the rmi string. The default
port number, 1099, is used when no port number is specified.

6.14 USING APPLETS WITH RMI

You can also create applets to represents the RMI clients. All the required files for
the applet must be stored in the same host that contains the Web page. The applet
can make network connections to only that host, which contains the applet.
Therefore, you need to store all the server objects on the same host that contains
the Web page. The server must contain Web pages, stub classes, server objects,
applet file and the RMI registry.

Self-Instructional
Material 109
Client and Server 6.14.1 Defining Server Class
Applications Using RMI
The Server Class extends the UnicastRemoteObject class of the rmi
package. The Server class is initially compiled with javac to create .class
NOTES files. Then the server .class is compiled using the rmic compiler to
generate the stub and skeleton class files. The Server.class defines the
basic functioning of the method on the remote machine and throws runtime
exception.
import java.rmi.registry.LocateRegistry; import
java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject; public
class Server implements RemoteInterface
{
public String getMessage()
{
return “Using RMI with applet”;
}

public static void main(String args[])


{
try
{
Registry registry =
LocateRegistry.getRegistry(RemoteInterface.REGISTRY_PORT);
RemoteInterface remoteReference = (RemoteInterface)
UnicastRemoteObject.exportObject(new Server());
registry.rebind(RemoteInterface.REGISTRY_NAME,
remoteReference);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
6.14.2 Defining Remote Interfaces
Remote Interfaces must be defined as public so that the client program can access
the interface on the remote machine. The getMessage in the Remote Interface
throws a Remote Exception that is handled using the RemoteException
class of the rmi package.
import java.rmi.Remote;
import java.rmi.RemoteException;
Self-Instructional
110 Material
public interface RemoteInterface extends Remote Client and Server
Applications Using RMI
{
String REGISTRY_NAME = “RMI_Example”; int REGISTRY_PORT
= 3273;
String getMessage() throws RemoteException; NOTES
}
6.14.3 Defining Client Class
The registry is a remote objects that maps the String names passed to it to the
remote objects. The applets search the RMI registry at the same host, using the
getCodeBase() and getHost() methods. The code to access the
RMI registry is:
LocateRegistry.getRegistry(getCodeBase().getHost(),
RemoteInterface.REGISTRY_PORT);
RemoteInterface remoteReference = (RemoteInterface)
registry.lookup(RemoteInterface.REGISTRY_NAME);
In the above code, the gethost() method locates the host of the
applet and returns it as a String object, url. The String object, url, is used in
the formation of rmi URL. The following program code shows the
ClientApplet.java file that represents the Client class created earlier
converted to an applet:
Showing the Content of the ClientApplet.java File
import java.rmi.registry.LocateRegistry; import
java.rmi.registry.Registry;
import java.awt.*; import java.applet.*;
import java.rmi.server.UnicastRemoteObject; public
class ClientApplet extends Applet
{
public void init()
{
try
{
Registry registry =

LocateRegistry.getRegistry(getCodeBase().getHost(),
RemoteInterface.REGISTRY_PORT);
RemoteInterface remoteReference = (RemoteInterface)
registry.lookup(RemoteInterface.REGISTRY_NAME);
add(new Label(remoteReference.getMessage()));
}
catch (Exception e)
{
Self-Instructional
Material 111
Client and Server throw new RuntimeException(e);
Applications Using RMI
}
}
}
NOTES
In the above code, the registry.lookup method obtains an object
handle and listens to the default port. The Naming.lookup method must be
type cast to the Remote Interface.
Save the file in the folder where the Client file is stored and compile the file.
After compiling the file, create the stub and skeleton files for the ClientApplet
class.
6.14.4 Creating the HTML File
To pass the name of the client from the server to the applet, you need to pass the
client name as the parameter to the applet. To pass the parameter to the applet,
you need to create the Applet.html file. The following program code shows
the content of the Applet.html file:
Showing the ClientApplet.html File
<?xml version=”1.0" encoding=”UTF-8"?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//
EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”
xml:lang=”en” lang=”en”>
<head>
<title>’Using RMI with Applet’</title>
</head>
<body>
<h1>”Simple example of using RMI with Applet”</h1>
<p>
This example simply demonstrates the use of applets in
Remote Method Invocation.
</p>
<p>
<!—[if !IE]>—>
<object classid=”java:ClientApplet.class”
type=”application/x-java-applet” height=”250"
width=”250" >

Self-Instructional
112 Material
<!—<![endif]—> Client and Server
Applications Using RMI
<object classid=”clsid:8AD9C840-044E-11D1-B3E9-
00805F499D93"
height=”50" width=”150" >
<param name=”code” value=”ClientApplet” /> NOTES
</object>
<!—[if !IE]>—>
</object>
<!—<![endif]—>
</p>
</body>
</html>
The name of the client is passed in the <param> tag, which the client
retrieves using the getParameter() method. The name of the client is
accessed using it.
6.14.5 Executing the RMI with Applet
1. Compile the java source files Server.java, ClientApplet.java
and RemoteInterface.java to generate the Sever.class,
ClientApplet.class and RemoteInterface.class files.
2. Compile the Server.class file with the rmic compiler using the
following command at the prompt:
rmic –v1.2 Server
3. Start the rmi registry on port 3273 using the following command:
start rmi registry 3273
4. Start the server using the following command:
start java server
This will start the program on the server side.
Figure 6.3 shows the command line to execute the RMI.

Fig. 6.3 Executing RMI

Self-Instructional
Material 113
Client and Server 5. Open web browser such as Internet Explorer and view the
Applications Using RMI
applet.html file. Figure 6.4 shows the output

NOTES

Fig. 6.4 Using RMI with applet

6.15 RMI ARCHITECTURE

During the Remote Method Invocation (RMI) call, the client requests a service
from a server and the server processes the request. RMI classes extend an interface
that helps in implementing the remote service based on the concept of classes.
The RMI architecture defines the implementation of object class on a remote
JVM that is based on various abstract layers such as:
 Application layer
 Proxy layer
 Remote reference layer
 Transport layer
All the above layers are independent of each other and you can amend
these layers according to your requirement. RMI is initiated when a method is
called at the client end, which requires a service. The request for service passes
through these abstract layers and then reaches the server side. Figure 6.5 shows
the RMI architecture.

Self-Instructional
114 Material
Client and Server
Applications Using RMI

NOTES

Fig. 6.5 The RMI architecture

6.15.1 Application Layer


Application layer is used to define Java programs written on the client side and the
server side to call a remote method. At the client side, the application layer includes
the Java code, which defines the service that can be obtained from the server. At
the server side, the application layer defines the implementation of the class that
processes the service.
6.15.2 Proxy Layer
This is the first layer of the RMI architecture and acts as an interface between the
application layer and other RMI layers. The method calls initiated at the client end
to process the service are intercepted by the proxy layer. The proxy layer performs
the mapping of interface variables initialised by the client application program with
the variables at the reference layer.
Remote Reference Layer
This layer acts as an interface between the proxy layer and the transport layer. The
proxy layer receives request for service from the client proxy layer and manages
the semantics of the call to be send to the server using the transport layer. The
proxy layer manages the semantics of the request based on remote reference
protocols. Similarly, the proxy layer manages the semantics of the service processed
by the server, prior to a delivery of the response to the client side.

Self-Instructional
Material 115
Client and Server 6.15.3 Transport Layer
Applications Using RMI
The transport layer performs the tasks of managing the connection between the
client and the remote server machines. The transport layer receives request from
NOTES the remote reference layer at the client side and transmits the request to the remote
reference layer at the server side. In addition to establishing the connection between
the client and server machine, the transport layer needs to manage and monitor
the connection between the two. Transport layers manage the connection between
the client and server, which are based on various transport protocols such as
TCP/IP protocol.

6.16 SOCKET VERSUS RMI PROGRAMMING

Table 6.2 lists the difference between the socket programming and RMI
programming.
Table 6.2 Socket programming and RMI programming

Socket Programming RMI programming


Socket programming provides RMI programming provides mechanism
communication mechanism between the to invoke method from a JVM that is
client and the server. executed on a remote JVM.
Socket programming is categorized as Java programs that provide the
connection oriented socket transport layer to establish and maintain
programming and connection less connection between the client and the
socket programming based on the server invoke RMI programming.
transport protocols such as TCP/IP and
UDP used in programming.
The main method on the server class The method calls from various clients
object opens a port to establish the initiate the connection between the
connection. client and the server.
It does not require rmiregistry on the It requires rmiregistry on the system to
system to execute. execute.
Socket programming can be RMI invokes the method call on the
accomplished in two modes, client remote JVM.
mode and the server mode.
Socket programming cannot RMI programming can load new
dynamically load new classes. classes dynamically.
Socket programming does not allow RMI can be used to share resources and
sharing of resources and distributing distributed load among various
loads across processors. processors.

Self-Instructional
116 Material
Client and Server
Applications Using RMI
Check Your Progress
3. What happens in case of a passing remote object?
4. Which class is the parent class of all the RMI specific exception classes? NOTES

6.17 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. The N-tier architecture allows a programmer to represent the concept of


client-server architecture using various tiers such as presentation logic and
business logic.
2. Distributed applications contain objects that are distributed over a network.
3. In case of passing remote object, only the methods defined in the remote
interface can be accessed through the stub.
4. The Remote Exception class is the parent class of all the RMI specific
exception classes

6.18 SUMMARY

 The N-tier architecture allows a programmer to represent the concept of


client-server architecture using various tiers such as presentation logic and
business logic.
 Distributed applications contain objects that are distributed over a network.
The objects communicate with each other using a standard protocol such
as TCP/IP.
 In a client/server architecture, the request of the client object and the response
from the server object are converted to an intermediate format such as
name/value pairs.
 In Remote Method Invocation (RMI), if you have the rights to access a
Java object present on a different computer over a network, then you can
call the methods defined in it.
 The process of encoding the parameters to be stored in the stub object is
called parameter marshalling.
 You can create a RMI server by extending the
UnicastRemoteObject class.

Self-Instructional
Material 117
Client and Server  The client needs to capture a stub object to send requests to the object
Applications Using RMI
present on the server.
 You can pass and retrieve any object through a remote call including those
that implement the Remote interface.
NOTES
 In case of passing remote object, only the methods defined in the remote
interface can be accessed through the stub.
 In any distributed application, catching exception is a difficult and mandatory
process because an exception can occur at the client object or the server
object or an exception can be raised because of a network error.
 The Remote Exception class is the parent class of all the RMI specific
exception classes.
 All the files in the Customer application created earlier are stored locally in
a folder to find any error in the RMI application.
 Before saving the files at the client and server computer, create two folders,
client and server, on the local computer.
 The client needs to define an interface that contains the signatures of the
methods of the server class available to the client to be accessed.
 The server itself can make a remote call back to the client such as sending
a warning for an error, a progress feedback or sending a message from one
client to another.
 To execute the RMI application over the network, you need to place the
required class files at the locations that can be accessed by the server and
the clients.
 The Server Class extends the UnicastRemoteObject class of the
rmi package. The Server class is initially compiled with javac to
create .class files.
 The registry is a remote objects that maps the String names passed to it to
the remote objects.
 To pass the name of the client from the server to the applet, you need to
pass the client name as the parameter to the applet.
 During the Remote Method Invocation (RMI) call, the client requests a
service from a server and the server processes the request.
 Application layer is used to define Java programs written on the client side
and the server side to call a remote method.
 The transport layer performs the tasks of managing the connection between
the client and the remote server machines.

Self-Instructional
118 Material
Client and Server
6.19 KEY WORDS Applications Using RMI

 CustomerServer.class: This file represents the class used to create


server objects. NOTES
 Remote Interfaces: It can be defined as public so that the client program
can access the interface on the remote machine.
 Application Layer: This layer is used to define Java programs written on
the client side and the server side to call a remote method.
 Proxy Layer: It is the first layer of the RMI architecture and acts as an
interface between the application layer and other RMI layers.

6.20 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short-Answer Questions
1. Name the four types of Exception thrown by RMI object methods.
2. List the files that are required by the server.
3. Write down the Abstract layers of RMI architecture.
4. What is the major difference between Socket programming and RMI
programming?
5. Name the tool to create the skeleton classes automatically.
Long-Answer Questions
1. What is RMI?
2. How are parameters passed from the client to the server?
3. Which class is extended to create an RMI server?
4. Which tool is used to create the stub and skeleton classes automatically?
5. Where and how the server registers the objects?
6. What is the Callback mechanism?
7. Write a program to implement RMI where the remote method is used to
display the sum of two numbers passed as command line arguments during
execution of the program at the client side.
8. Write a program to display Hello World message while implementing RMI
using applets.

Self-Instructional
Material 119
Client and Server
Applications Using RMI 6.21 FURTHER READINGS

Naughton, Patrick and Herbert Schildt, The Complete Reference Java 2, Third
NOTES Edition.
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
120 Material
BDK and JAR Files
BLOCK - III
BDK AND DESIGN PATTERNS

NOTES
UNIT 7 BDK AND JAR FILES
Structure
7.0 Introduction
7.1 Objectives
7.2 Java Beans
7.3 Java Archive File (JAR)
7.4 Introspection
7.5 Answers to Check Your Progress Questions
7.6 Summary
7.7 Key Words
7.8 Self Assessment Questions and Exercises
7.9 Further Readings

7.0 INTRODUCTION

A Java Bean is a specially constructed java class written in the Java and coded
according to the JavaBeans API specifications. A bean encapsulates many objects
into one object, so we can access this object from multiple places. Moreover, it
provides the easy maintenance. JavaBeans can also be referred to as Java classes
which adhere to an extremely simple coding convention. In this unit, you will learn
about Bean development, JAR and introspection in detail.

7.1 OBJECTIVES

After going through this unit, you will be able to:


 Understand Java Beans and its use
 Discuss the benefits of using Java Beans
 Analyse the Composition of a Java Bean
 Explain the power and capabilities of Java Bean

7.2 JAVA BEANS

The Java Beans architecture is based on a component model enabling the


developers to create small software units that they call components. These smaller
components can be assembled and integrated to form large components like

Self-Instructional
Material 121
BDK and JAR Files applets, applications etc. These core components have the characteristics of
reusability and are self-contained and are known as beans.
The official definition of a bean, as given in the Java Beans specification, is:
“A bean is a reusable software component based on Sun’s JavaBeans specification
NOTES
that can be manipulated visually in a builder tool.”
These software components or beans are developed, but run and reused
everywhere as per the requirements .There are various softwares like NetBeans
,JBuilder , BDK , etc. which can help you out to unleash the power of beans –
reusability. The JavaBeans component architecture is backed upon by the set of
APIs called the JavaBeans API specification that deals with the internal
sophistication of this model.
Java Beans are dynamic components and also very crucial implementations
to be dealt with. Dynamic in the sense that you can easily change their nature and
customize them as per your need .For this the design mode of a builder tool can
be used for visual manipulation. Simply, choose a bean from the toolbox, drag and
drop it into a form, restructure its appearance and behaviour, define its interaction
with other beans, and combine it with other beans into an applet, application, or a
new bean.
Some Bean Facts
1. A Java Bean is a reusable and self-contained software component that
inherits the basic implementations from sun’s java bean specification.
2. A Java Bean is a not only reusable but also customizable and can be easily
manipulated visually in a builder tool.
3. The Builder tool is an application development tool which helps you to
build new beans or reuse the pre-existing ones to develop an application
visually.
4. Java Beans help to create simple components first which can be then
reutilised to produce comparatively some more complex components or
applications using the builder tools like NetBeans etc.
5. These builder tools are moreover like IDEs that determine a bean’s features
like its properties, methods, and events .The process of discovering these
facts about the beans is called introspection. There are two ways for Beans
support introspection:
(i) Just adhere to some specific rules, known as design patterns, when
naming bean features. The Introspector class checks the beans for
these design patterns explore out all the bean features.
(ii) And the other method is to explicitly provide all the basic information
like property, method, and event information with a related bean
information class. A bean information class implements the Bean

Self-Instructional
122 Material
Info interface. A BeanInfoclass explicitly lists those bean features that BDK and JAR Files

are to be exposed to application builder tools.


6. The appearance and behaviour of a bean determines its properties .These
properties can be manipulated and changed later during the design using
NOTES
some builder tools. Builder tools introspect on a bean to discover its
properties and expose those properties for manipulation and further changes.
7. Beans show various properties which can be customized at design time
either by using property editor tools like NetBeans, etc. or by using more
advanced bean customizers.
8. Events are the mechanism of communication between two or more beans.
Beans follow the event delegation model where there is a listener and the
source for every event. It requires a bean builder tool to act as interface and
create appropriate registration of the source (event generator), the listener
(event delegator) and the event handler so that the event gets properly
managed.
9. The literary meaning of “Persistence” is long lasting. So, this enables the
beans to save and restore their state later when needed. After bean
manipulation, beans properties get changed from the initial ones, so this
need to be saved. Why? So, that if there is any error or the bean component
is not performing as desired then it could be reverted back to its initial state.
Java Object Serialization is used to support persistence in java beans.
10. A bean’s methods are similar to the Java methods, and can be called from
other beans or a scripting environment as required. By default all public
methods are exported.
11. On the basis of functionality and purpose, all the beans vary in nature from
each other. Some of the bean implementations you might have probably
met while programming are:
(a) GUI (graphical user interface)
(b) Non-visual beans, such as a spelling checker
(c) Animation applet
(d) Spreadsheet application
Benefits of using Java Beans
As discussed beans are reusable, self-contained software components. So, there
are a lot of benefits that a programmer can utilize to create a good software. Some
of the benefits have been discussed below:
 The java beans are java components hence have the “Write once and run
anywhere” property.
 Beans are platform independent and hence can work in different local
platforms.
Self-Instructional
Material 123
BDK and JAR Files  Beans follow the message passing concept and therefore can easily capture
the events sent by other objects and vice versa thereby enabling effective
object communication.
 The application developer can add, manipulate and configure the properties,
NOTES
events and methods of the bean with the help of bean auxiliary software
during design time without creating any havoc at runtime.
 The beans are persistent in nature and hence their configuration settings can
be saved in persistent storage and restored later during any contingency or
failure.
Power and capabilities of Java Bean
A Bean can be too simple or too complex, whatever be the design and/or
configurations, but both are equally powerful in implementations. A bean can be
designed to cater the need of performing a simple function, like developing a spell
checking component to be used in a document, or for performing a complex
function, such as forecasting some performance metrics in business models. A
Bean may be visible to an end user.
Builder tool
Builder tools are the softwares that helps a developer to examine a Java Bean by
a process known as Introspection and exposes the features of the Java Bean so
that it can be visually manipulated. Apart from this, it also maintains a list of all
JavaBeans that are currently available in the development environment. Amongst
the various features, besides customization of the beans behaviour, its appearances
and properties, builder tools can be used to convert the Bean into applets,
application, servlets and composite components (e.g. a JFrame), and connect
different other components to the event of the Bean or vice versa.
Points to remember while devising a JavaBeans
Java Beans are special java classes and hence while you are writing any of them
you should always remember the following points, without which your beans will
just get spoilt.
1. A Java Bean class should always be declared “public”.
2. A Java Bean should implement the “Serializable interface”.
3. A Java Bean should have a “no-argument constructor/default constructor”.
4. A Java Bean class should be derived from “javax.swing.JComponent or
java.awt.Component” class if it is to be visually manipulated.
The java.beans package consists of the classes and interfaces that help you
to create JavaBeans with proper implementations.

Self-Instructional
124 Material
The Java Bean components can exist in either of the following three phases BDK and JAR Files

of development: viz. 1. Construction phase, 2. Build phase and 3. Execution phase.


Java Beans support the standard component architecture that comprises of
components like- properties, events, methods, and persistence.
NOTES
Composition of a Java Bean
A Java Bean is composed of the followings: Properties, Methods, and Events. So,
you should know the basics of all these components of the java beans.
1. Properties
Java Bean properties are analogous to instance variables of a class in java. A bean
property is a named attribute of a bean that can affect its behaviour or appearance.
It means if you wish to change the behaviour or the appearance of the Java Beans,
then you can use this attribute. Examples of bean properties include colour, label,
font, font size, and display size.
2. Methods
The Java Bean methods are just the same as normal Java methods. Every
property should have accessor (get) and mutator (set) method. All Public
methods can be identified by the introspection and also there does not exist specific
naming standard for these methods. These are also known as getter and setter
methods.
Events
Events are similar to the events of Swing/AWT event handling. They also follow
the same event delegation model like Swing components.
The Java Bean Component Specification
The Java Beans component specification deals with following properties and
capabilities like customization of Bean properties, persistence, Beans to Beans
communications, etc.
1. Beans Customization: This is the ability of Java Bean to allow its properties
to be modified or altered in build phase and/or execution phase.
2. Beans Persistence: It can be defined as the JavaBeans ability to save its
state to disk or storage device and restore the saved state when it is reloaded.
3. Beans Communication: This can be defined as the ability of Java Bean to
communicate about change in its properties to other JavaBeans or the
container so that they can respond accordingly later on as per modifications.
4. Introspection: This is the ability of a Java Bean to allow an external
application to examine it and know the properties, methods, and events
supported by it so that it can be changed or used as needed.

Self-Instructional
Material 125
BDK and JAR Files Features of a Java Bean
1. Java bean supports “introspection”; it helps a builder tool analyse how a
bean works by inspecting its features.
NOTES 2. Java bean provides support for “customization” so that a developer can
easily customise the appearance and behaviour of a Java Bean and create
a new from the existing one.
3. Java beans supports “events” that act as a glue to bind two or more beans.
4. Java beans have “properties” that can be used for both customization and
for programmatic use.
5. Java beans support “persistence”, which is a mechanism of storing the
bean state initially and restoring later on need.

Fig. 7.1 Components of Java Bean

Beans Development Kit


Beans Development Kit (BDK) is a development environment that can be utilized
to create, configure, and test Java Beans. It has the following basic features:
 It is a graphical user interface helping a bean developer to create, configure,
and test Java Beans.
 It helps the bean developer to introspect the Java Bean properties and also
helps to manage and link multiple Java Beans in an application.
 It consists of a set of sample Java Beans which can be used for application
development.
 It also provides a base for utilising and associating the pre-existing events
with sample Java Beans to understand the event model.

Self-Instructional
126 Material
Identifying BDK Components BDK and JAR Files

 Execute the run.bat file of BDK to start the BDK development environment.

NOTES

Fig. 7.2 Run.bat file of BDK to start the BDK development environment

A BDK development environment is composed of the following modules:


 ToolBox
 BeanBox
 Properties
 Method Tracer

Fig. 7.3 A complete view of Bean Development Kit

Now, you will learn about the different components of the bean development
kit.
1. ToolBox window: A window that consists of the lists of sample
JavaBeans of BDK available to be reused to build up an application.

Self-Instructional
Material 127
BDK and JAR Files Below is the figure that shows the ToolBox window with various pre-
built beans:

NOTES

Fig. 7.4 ToolBox

2. BeanBox window: It is a workspace for creating the layout of Java


Bean application. Figure given below shows the BeanBox window:

Fig. 7.5 BeanBox

3. Properties window: This window displays all the exposed properties


of a Java Bean. You can modify Java Bean properties in the properties
window. Given below is the Properties window showing various
properties of a BeanBox:

Fig. 7.6 BeanBox Properties


Self-Instructional
128 Material
4. Method Tracer window: Method tracer window displays the debugging BDK and JAR Files

messages and method calls for a Java Bean application.


The following figure shows the Method Tracer window:
NOTES

Fig. 7.7 Method Tracer

Steps to Develop a User-Defined Java Bean


Follow the following steps to develop a user defined Java bean.
1. Create a directory for the new bean
Create a directory/folder like C:\Beans
2. Create bean source file - MyBean.java
import java.awt.*;
public class MyBean extends Canvas
{
public MyBean()
{
setSize(70,50);
setBackground(Color.green);
}
}
3. Compile the source file(s)
C:\Beans >Javac MyBean.java
4. Create a manifest file
Manifest File
The manifest file for a Java Bean application contains a list of all the class files that
make up a Java Bean. The entry in the manifest file enables the target application
to recognize the Java Bean classes for an application. For example, the entry for
the MyBean Java Bean in the manifest file is as shown:
Note: write that 2 lines code in the notepad and save that file as MyBean.mf
Manifest-Version: 1.0
Name: MyBean.class
Java-Bean: true Self-Instructional
Material 129
BDK and JAR Files The rules to create a manifest file are:
 Press the Enter key after typing each line in the manifest file.
 Leave a space after the colon.
NOTES  Type a hyphen between Java and Bean.
 No blank line between the Name and the Java-Bean entry.
5. Generate a JAR file
Syntax for creating jar file using manifest file
C:\Beans >jar cfm MyBean.jar MyBean.mf MyBean.class
6. Start BDK
Go to->
C:\bdk1_1\beans\beanbox
Click on run.bat file. When we click on run.bat file the BDK software
automatically started.
Manifest-Version: 1.0
Name: MyBean.class
Java-Bean: true
7. Load Jar file
Go to Beanbox->File->Load jar. Here we have to select our created jar
file when we click on ok, ourbean (userdefined) MyBean appear in the
ToolBox.
8. Test our created user defined bean
Select the MyBean from the ToolBox when we select that bean one +
simple appear then drag that Bean in to the Beanbox. If you want to apply
events for that bean, now we apply the events for that Bean.
Steps to develop a user defined Java bean
1. Create a directory for the new bean
2. Create the java bean source file(s)
3. Compile the source file(s)
4. Create a manifest file
5. Generate a JAR file
6. Start BDK
7. Load Jar file
8. Test.

Self-Instructional
130 Material
BDK and JAR Files
7.3 JAVA ARCHIVE FILE (JAR)

JAR file allows you to efficiently deploy a set of classes and their associated
resources. JAR file makes it much easier to deliver, install, and download. It is NOTES
compressed. The files of a Java Bean application are compressed and grouped as
JAR files to reduce the size and the download time of the files.
 The syntax to create a JAR file from the command prompt is:
jar <options> <file_names>
 The file_names is a list of files for a Java Bean application that are stored in
the JAR file.
The various options that you can specify while creating a JAR file are:
c: Indicates the new JAR file is created.
f: Indicates that the first file in the file_names list is the name of the JAR
file.
m:Indicates that the second file in the file_names list is the name of the
manifest file.
t: Indicates that all the files and resources in the JAR file are to be displayed
in a tabular format.
v: Indicates that the JAR file should generate a verbose output.
x: Indicates that the files and resources of a JAR file are to be extracted.
o: Indicates that the JAR file should not be compressed.
m:Indicates that the manifest file is not created.

Fig. 7.8 JAR utility as implemented on command prompt

Self-Instructional
Material 131
BDK and JAR Files
7.4 INTROSPECTION

Introspection is a technique which helps to retrieve the vital information about the
NOTES Java beans like what features does it have(bean properties), how it will
behave(bean methods) and what it can really be used for (bean events) etc.
Introspection is actually an analysis of bean capabilities so as to know what the
bean is capabale to do. Implementation of introspection is an automatic process in
bean builder tool to introspect which properties, methods, and events a bean
supports. It is an eminent process, without which you can never imagine to unleash
the real power of a Java Bean and utilize it further.
BDK Introspection
To automatically analyse the properties of a Java Bean, BDK Introspection is
done. It allows the builder tool to analyse the functioning of the bean. It can be
defined as the mechanism that allows the bean classes to publish their operations
and properties that they support along with a meta-mechanism which leads to the
discovery of such mechanisms. Introspection can be defined as the technique of
obtaining information about bean properties, events and methods or in short, it is
the analysis of bean capabilities as what it can do.
There are two ways in which the developer of a Bean can indicate which of
its properties, events, and methods should be exposed by the builder tool.
1. First one uses the mechanism of naming conventions that allows the
introspection mechanisms to infer information about a Bean.
2. Secondly, an additional class which contains the basic information is
provided that explicitly provides this information to the builder tools.

Check Your Progress


1. What is the builder tool?
2. What is a Java Bean?
3. How do Beans work in different local platforms?

7.5 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. The Builder tool is an application development tool which helps you to


build new beans or reuse the pre-existing ones to develop an application
visually.

Self-Instructional
132 Material
2. A Java Bean is a reusable and self-contained software component that inherits BDK and JAR Files

the basic implementations from sun’s java bean specification.


3. Beans are platform independent and hence can work in different local
platforms.
NOTES

7.6 SUMMARY

 A Java Bean is a reusable and self-contained software component that inherits


the basic implementations from sun’s java bean specification.
 A Java Bean is a not only reusable but also customizable and can be easily
manipulated visually in a builder tool.
 The Builder tool is an application development tool which helps you to
build new beans or reuse the pre-existing ones to develop an application
visually.
 Events are the mechanism of communication between two or more beans.
Beans follow the event delegation model where there is a listener and the
source for every event.
 The literary meaning of “Persistence” is long lasting. So, this enables the
beans to save and restore their state later when needed.
 A bean’s methods are similar to the Java methods, and can be called from
other beans or a scripting environment as required.
 The java beans are java components hence have the “Write once and run
anywhere” property.
 Beans are platform independent and hence can work in different local
platforms.
 The beans are persistent in nature and hence their configuration settings can
be saved in persistent storage and restored later during any contingency or
failure.
 A Bean can be too simple or too complex, whatever be the design and/or
configurations, but both are equally powerful in implementations.
 Java Bean properties are analogous to instance variables of a class in java.
 Java Bean supports “introspection”; it helps a builder tool analyse how a
bean works by inspecting its features.
 Java Beans support “persistence”, which is a mechanism of storing the bean
state initially and restoring later on need.
 The manifest file for a Java Bean application contains a list of all the class
files that make up a Java Bean.

Self-Instructional
Material 133
BDK and JAR Files
7.7 KEY WORDS

 Beans Customization: This is the ability of Java Bean to allow its


NOTES properties to be modified or altered in build phase and/or execution phase.
 Beans Persistence: It can be defined as the JavaBeans ability to save its
state to disk or storage device and restore the saved state when it is reloaded.
 Beans Communication: This can be defined as the ability of Java Bean to
communicate about change in its properties to other JavaBeans or the
container so that they can respond accordingly later on as per modifications.
 Introspection: This is the ability of a Java Bean to allow an external
application to examine it and know the properties, methods, and events
supported by it so that it can be changed or used as needed.

7.8 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short-Answer Questions
1. What are Java Beans? Discuss its uses.
2. Discuss the benefits of using Java Beans.
3. Analyse the Composition of a Java Bean.
Long-Answer Questions
1. Explain the power and capabilities of Java Bean.
2. Write a detailed note on Java Archive File (JAR) file.
3. What are the components of a Java Bean? Support your answer with a
diagrammatic representation.

7.9 FURTHER READINGS

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
134 Material
Design Patterns and

UNIT 8 DESIGN PATTERNS AND Event Handling

EVENT HANDLING
NOTES
Structure
8.0 Introduction
8.1 Objectives
8.2 Design patterns for Java Bean Properties
8.3 Introducing Event Handling
8.3.1 Event Classes
8.3.2 Sources of Events
8.3.3 Event Listener Interfaces
8.4 Process of Handling Events
8.4.1 ActionListener
8.4.2 AdjustmentListener
8.4.3 MouseListener
8.4.4 MouseMotionListener
8.4.5 WindowListener
8.4.6 KeyListener
8.5 Answers to Check Your Progress Questions
8.6 Summary
8.7 Key Words
8.8 Self Assessment Questions and Exercises
8.9 Further Readings

8.0 INTRODUCTION

Design pattern is a general repeatable solution to a commonly occurring problem


in software design. A design pattern isn’t a finished design that can be transformed
directly into code. It is a description or template for how to solve a problem that
can be used in many different situations. Design patterns can speed up the
development process by providing tested, proven development paradigms.
Effective software design requires considering issues that may not become visible
until later in the implementation. Design patterns are all about class instantiation.
This pattern can be further divided into class-creation patterns and object-creational
patterns. In this unit you will learn about design pattern for properties.

8.1 OBJECTIVES

After going through this unit, you will be able to:


 Design patterns for Java Bean properties
 Understand event delegation model in Java Beans
 Create event listeners
Self-Instructional
Material 135
Design Patterns and
Event Handling 8.2 DESIGN PATTERNS FOR JAVA BEAN
PROPERTIES

NOTES Defining a bean’s state means defining a property which can depict its state. A
bean property can be considered as a named attribute of a bean that can be used
to define its behaviour or appearance like colour, label, font, font size, and display
size, etc. Bean’s properties are private data members of the Java Bean classes
and can be used to take input from a user that can be implemented to customize a
Java Bean accordingly. These bean properties can access and determine the values
of various attributes, which in return define the behaviour of a Java Bean. On the
basis of the values they deal with, the number of values they take, the Java Beans
Properties can be listed as followings:
1. Simple properties
2. Boolean properties
3. Indexed properties
4. Bound Properties
5. Constrained Properties
Simple Properties
These properties are called simple as they have only a single value and are simple
to use. The getter and setter methods - getXXX() and setXXX() methods are
used to retrieve and specify values. A read/write property has both of these getter
and setter methods to access its values. The getXXX() methods are used to read
the value of the property specified while the setXXX() methods are used to set
the value of the property as defined. The getter and setter methods are also called
accessor methods and are used to set the property.
The syntax of get method is:
public return_type get<PropertyName>()
public T getN();
public void setN(T arg)
N is the name of the property and T is its type
Ex:
public double getWeight()
{
return Weight;
}
Read only property has only a get method.
The syntax of set method is:
public void set<PropertyName>(data_type value)
Self-Instructional
136 Material
Ex: Design Patterns and
Event Handling
public void setWeight(double d)
{
Weight=d;
NOTES
}
Note: The write only property has only a set method.
Boolean Properties
We know there are two specific Boolean values that are used in programs - True
and False. Hence, the property that is used to denote/use either of these values is
known as the Boolean Property of the bean.
Syntax
Let N be the name of the property and T be the type of the value then
public boolean isN();
public void setN(boolean parameter);
public Boolean getN();
 public boolean is<PropertyName>()
 public boolean get<PropertyName>()
First or second pattern can be used to retrieve the value of a Boolean.
 public void set<PropertyName>(boolean value)
For getting the values isN() and getN() methods are used and for setting the
Boolean values setN() method is used.
Ex:
public boolean dotted=false;
public boolean isDotted()
{
return dotted;
}
public void setDotted(boolean dotted)
{
this.dotted=dotted;
}
Indexed Properties
Some bean properties contains multiple values. These properties are called Indexed
Properties. Suppose a property holds an array of values, then such a property is
an indexed property. An indexed property may expose set/get methods to read/
write one element in the array (so-called ’index getter/setter’) and/or so-called
’array getter/setter’ which read/write the entire array. Indexed Properties enable
you to set or retrieve the values from an array of property values. Indexed Properties
are retrieved using the following get methods: Self-Instructional
Material 137
Design Patterns and Syntax: public int[] get<PropertyName>()
Event Handling
Ex:
private double data[];
public double getData(int index)
NOTES
{
return data[index];
}
Syntax: public property_datatype get<PropertyName> (int
index)
Ex:
public void setData(int index,double value)
{
Data[index]=value;
}
**Indexed Properties are specified using the following
set methods:

Syntax: public void set<PropertyName>(int index,


property_datatype value)
Ex:
public double[] getData()
{
return data;
}

Syntax: public void set<PropertyName>(property_datatype[]


property_array)
Ex:
public void setData(double[] values)
{
}
Since there exists no mechanism to handle these index properties, the output
cannot be displayed here.
Bound Properties
Bound Properties are the special properties of a Java Bean. These properties
delegate the changes in the values to the listeners by generating an event when the
property is manipulated. The PropertyChangeSupport class and its methods
are used to deal with the bound properties. Registration of the Bound Properties
is always done with an external event listener. The event is of type
PropertyChangeEvent and is delegated to objects that had pre-registered an
interest in receiving such notifications beans with bound property - Event source
Bean implementing listener — event target. In order to provide this notification
Self-Instructional service a Java Bean needs to have the following two methods:
138 Material
public void Design Patterns and
addPropertyChangeListener(PropertyChangeListener p) { Event Handling

changes.addPropertyChangeListener(p);
}
NOTES
public void
removePrertyChangeListener(PropertyChangeListener p)
{
changes.removePropertyChangeListener(p);
}
PropertyChangeListener is an interface declared in the java.beans package
having only one method i.e public void propertyChange(PropertyChangeEvent
e ) .Those who wish to be notified about the property changes must implement
this interface explixcitly..
public interface PropertyChangeListener extends
EventListener
{
public void propertyChange(PropertyChangeEvent e );
}
Constrained Properties
Constrained means “making more restrictive” .Constrained properties hence are
specifically restrictive and are implemented using the PropertyChangeEvent class,
and generates an event when its value is modified. The event thus generated is then
delegated to objects that had pre-registered to get any notification about the change
in the value of the property. These objects have the ability to veto the proposed
change and are capable of rejecting any unwanted changes.
Constrained properties are secure properties as they are protected from
being modified by other Java Bean classes. Constrained Properties are registered
with an external event listener that has the ability to either approve or reject the
change in the value of a constrained property. Constrained Properties can be
retrieved using the getter methods. The prototype of the get method is:
Syntax: public string get<ConstrainedPropertyName> ()
It can be specified using the set method. The prototype of the set method is:
Syntax: public string set<ConstrainedPropertyName> (String
str)throws PropertyVetoException

Check Your Progress


1. What are events?
2. What are constrained properties?

Self-Instructional
Material 139
Design Patterns and
Event Handling 8.3 INTRODUCING EVENT HANDLING
An event occurs when there is a change in the active state of components, such as
NOTES buttons and text boxes. Examples of events are when the end user clicks a button
or enters text in a textbox. Event handling is the process to monitor any change in
the state of an object and perform a corresponding action. These actions are
created in form of modules or functions and can further lead to events.
This unit describes the classes and interfaces in Java for handling events.
This unit explains the process to handle events. It also explains how to implement
the several interfaces provided by Java to handle events. This unit describes the
Adapter classes and how Adapter classes can be used for handling events.
Fundamentals of Event Handling in Java
Java uses a model called the event delegation model to handle events. Java provides
several event classes, such as ActionEvent and ItemEvent that define
event objects. A different event object represents a different type of an event, for
example ActionEvent class represents the event where an end user clicks a
button. The object of an ItemEvent class may represent the selection of a
radio button. Java also provides several interfaces that allow you to monitor events
that occur when the end user interacts with the Java Abstract Window Toolkit
(AWT) components.
Event Delegation Approach
The event delegation model defines the standards and mechanisms to handle events
in Java. The event delegation model is made up of three components:
 Source: Generates an event.
 Event: Describes the change in the source and is generated by the source.
 Event Listener: Receives and processes an event.
The user interface generates the event and the event listeners. Both the
events and event listeners are a part of the application logic that handles the events.
The event delegation model handles these events and event listeners separately. In
the event delegation model, a listener can receive an event notification after it is
registered with the source.
Events are the objects in an event delegation model that are generated when
the end user interacts with the AWT components, such as buttons, checkboxes
and text fields. Events are also generated from end-user input through the keyboard
and mouse. A source generates an event when the internal state of an object
changes. The source also registers event listeners so that the event listeners can
receive notification when an event is generated. Event listener is an object that
waits for an event to occur. When an event is triggered, an event listener is notified
by the source to which it is registered. Event listeners implement methods that
receive events and perform actions corresponding to events. Figure 8.1 shows the
Self-Instructional event delegation model.
140 Material
Design Patterns and
Event Handling

NOTES

Fig. 8.1 Event Delegation Model

8.3.1 Event Classes


The event classes represent the events that are generated when an end user interacts
with the AWT components. The EventObject class is the super class for
handling all events. This class exists in the package, java.util. The
AWTEvent class is the subclass of the EventObject class and all AWT
events originate from the AWTEvent class. This class is present in the
java.awt package. Another package, java.awt.event, defines the AWT
events derived from the AWTEvent class. The event classes contain constant
integer values, which provide information about the events and the state of
components generating events. Table 8.1 describes the classes for handling events.
Table 8.1 Event Handling Classes

Event Classes Description Integer Constants


ActionEvent Is generated when ALT_MASK
an end user clicks a
SHIFT_MASK
button or a menu
option. This event is CTRL_MASK
also generated when META_MASK
an end user double-
clicks a list item. ACTION_PERFORMED

Adjustment Is generated when BLOCK_DECREMENT


Event an end user moves
BLOCK_INCREMENT
the scrollbar.
TRACK
UNIT_DECREMENT
UNIT_INCREMENT
ADJUSTMENT_VALUE_CHANGED Self-Instructional
Material 141
Design Patterns and
Event Handling ComponentEv Is generated when COMPONENT_HIDDEN
ent an AWT component COMPONENT_SHOWN
is hidden, shown,
moved or resized. COMPONENT_MOVED
NOTES COMPONENT_RESIZED

ContainerEv Is generated when COMPONENT_ADDED


ent you add or remove
COMPONENT_REMOVED
an AWT component
to a container.

FocusEvent Is generated when FOCUS_GAINED


an AWT component
FOCUS_LOST
gains or loses input
focus.

HierarchyEv Is generated when HIERARCHY_FIRST


ent there is a change in
HIERARCHY_CHANGED
the component
hierarchy to which ANCESTOR_MOVED
the component ANCESTOR_RESIZED
belongs.
HIERARCHY_LAST
PARENT_CHANGED
DISPLAYABILITY_CHANGED
SHOWING_CHANGED

InputEvent Is the abstract super ALT_MASK


class for all AWT
ALT_GRAPH_MASK
component input
event classes. It is BUTTON1_MASK
the subclass of the BUTTON2_MASK
ComponentEven
t class. BUTTON3_MASK
CTRL_MASK
META_MASK
SHIFT_MASK
ALT_DOWN_MASK
ALT_GRAPH_ DOWN_MASK
BUTTON1_ DOWN_MASK
BUTTON2_ DOWN_MASK
BUTTON3_ DOWN_MASK
CTRL_ DOWN_MASK
META_ DOWN_MASK
SHIFT_ DOWN_MASK

Self-Instructional
142 Material
Design Patterns and
InputMethod Contains INPUT_METHOD_FIRST Event Handling
Event information about INPUT_METHOD_TEXT_
text, which is CHANGED
composed using an
input method. If the CARET_POSITION_CHANGED
text changes, then
NOTES
INPUT_METHOD_LAST
the input method
sends an event to the
event handler.

ItemEvent Is generated when a ITEM_STATE_CHANGED


checkbox, radio
DESELECTED
button, list item or
choice menu option SELECTED
is selected.

KeyEvent Is generated when KEY_PRESSED


an end user provides
KEY_RELEASED
an input through the
keyboard. KEY_TYPED
VK_ENTER
VK_ESCAPE
VK_CANCEL
VK_UP
VK_DOWN
VK_LEFT
VK_RIGHT
VK_PAGE_DOWN
VK_PAGE_UP
VK_SHIFT
VK_ALT
VK_CONTROL

MouseEvent Is generated when MOUSE_CLICKED


an end user works
MOUSE_DRAGGED
with the mouse.
MOUSE_ENTERED
MOUSE_EXITED
MOUSE_MOVED
MOUSE_PRESSED
MOUSE_RELEASED
MOUSE_WHEEL

Self-Instructional
Material 143
Design Patterns and
Event Handling MouseWheel Is generated when WHEEL_BLOCK_SCROLL
Event an end user rotates
WHEEL_UNIT_SCROLL
the mouse wheel.
MouseWheelEve
nt is the subclass of
NOTES the MouseEvent
class.

PaintEvent Ensures that the PAINT_FIRST


paint() and PAINT_LAST
update() method
calls are serialized. PAINT
UPDATE

TextEvent Is generated when TEXT_VALUE_CHANGED


characters are
entered in text fields
and text area boxes.

WindowEvent Is generated when WINDOW_ACTIVATED


an end user
WINDOW_CLOSED
activates,
deactivates, opens, WINDOW_CLOSING
closes, minimizes or WINDOW_DEACTIVATED
restores a window.
WINDOW_ICONIFIED
WINDOW_DEICONIFIED
WINDOW_GAINED_FOCUS
WINDOW_LOST_FOCUS
WINDOW_OPENED
WINDOW_STATE_CHANGED

8.3.2 Sources of Events


AWT components, such as buttons and text boxes are the sources of events. An
event is generated, when an end user interacts with AWT components. Table 8.2
describes the sources of events in Java.
Table 8.2 Sources of Events in Java

AWT Controls Events Generated


Button Generates an action event when a button is clicked.
Checkbox Generates an item event when checkboxes are selected or
deselected.
Radio Button Generates an item event when radio buttons are selected or
deselected.
Choice Generates an item event when choice options are changed.
List Generates an action event when options in a list box are
double-clicked. Generates an item event when options are
selected or deselected
Menu Options Generates an action event when options are changed.
Self-Instructional
144 Material
selected or deselected
Menu Options Generates an action event when options are changed. Design Patterns and
Event Handling
Checkbox Menu Generates an item event when an option is selected or
Options deselected.
Scrollbar Generates an adjustment event when moved.
Text Field Generates text events when an end user enters text in the text NOTES
field.
Text Area Box Generates text events when an end user enters text in the text
field.
Window Generates window events when a window is closed, opened,
activated, deactivated, minimized or restored.

8.3.3 Event Listener Interfaces


The event listeners are the interfaces in Java that define the methods for handling
events. A source, such as AWT button component invokes a method of the
corresponding event listeners when an event occurs. The event object is passed
as an argument to the method. It is important that the event listener is registered
with a source, so that any change in the internal state of the source is notified to the
event listener. Table 8.3 describes the event listeners in Java.
Table 8.3 Java Event Listeners

Event Listeners Description Method to Register


ActionListener Defines a single method, addActionListener
actionPerformed() that (ref);
receives an argument of the
ActionEvent class.
AdjustmentList Defines a single method, addAdjustment
ener adjustmentValueChang Listener(ref);
ed() that receives an
argument of the
AdjustmentEvent class.
AWTEventListen Defines a single method, addAWTEvent
er eventDispatched() that Listener(ref);
receives an argument of the
AWTEvent class.
ComponentListe Defines two methods, addComponent
ner componentResized() Listener(ref);
and componentMoved().
Both the methods receive an
argument of the
ComponentEvent class.
Container Defines two methods, addContainer
Listener componentAdded() and Listener(ref);
componentRemoved().
Both the methods receive an
argument of the
ContainerEvent class.
FocusListener Defines two methods, addFocusListener
focusGained() and (ref);
focusLost(). Both the
methods receive an argument
of the FocusEvent class.
HierarchyBound Defines two methods, addHierarchyBound
sListener ancestorMoved() and sListener(ref);
ancestorResized().
Both the methods receive an
argument of the
HierarchyEvent class. Self-Instructional
Material 145
Design Patterns and
Event Handling
Hierarchy Defines a single method, addHierarchy
Listener hierarchyChanged() Listener(ref);
that receives an argument of
the HierarchyEvent
class.
NOTES InputMethod Defines two methods, addInputMethod
Listener inputMethodText Listener(ref);
Changed() and
caretPosition
Changed(). Both the
methods receive an argument
of the
InputMethodEvent
class.

ItemListener Defines a single method, addItemListener


itemStateChanged() (ref);
that receives an argument of
the ItemEvent class.

KeyListener Defines three methods: addKeyListener


keyTyped(), (ref);
keyPressed() and
keyReleased(). All
methods receive an argument
of the KeyEvent class.

MouseListener Defines five methods: addMouseListener


mouseEntered(), (ref);
mouseExited(),
mousePressed(),
mouseReleased() and
mouseClicked(). These
methods receive an argument
of the MouseEvent class.

MouseMotion Defines two methods, addMouseMotion


Listener mouseMoved() and Listener(ref);
mouseDragged() that
receive an argument of the
MouseEvent class.

MouseWheel Defines a single method, addMouseWheel


Listener mouseWheelMoved() that Listener(ref);
receives an argument of the
MouseEvent class.

TextListener Defines a single method, addTextListener


textValueChanged() (ref);
that receives an argument of
the TextEvent class.

Self-Instructional
146 Material
Design Patterns and
WindowFocus Defines two methods, addWindowFocus
Event Handling
Listener windowGainedFocus() Listener(ref);
and windowLostFocus()
that receive an argument of
the WindowEvent class.
NOTES
WindowListener Defines seven methods: addWindowListener
windowActivated(), (ref);
windowDeactivated(),
windowIconified(),
windowDeiconified(),
windowClosed(),
windowOpened(),
windowClosing(). All
these methods receive an
argument of the
WindowEvent class.

WindowState Defines a single method, addWindowState


Listener windowStateChanged() Listener(ref);
that receives an argument of
the windowState
Changed class.

8.4 PROCESS OF HANDLING EVENTS

The delegation model explains how event handling takes place in Java. You can
map the event delegation model to the actual Java statements that are used for
handling events. For example, when an end user clicks an AWT button, a message
is displayed in the text field. The source in this case is the AWT button that the end
user interacts with. The event listener that receives and processes the button click
event in the example is the ActionListener interface. The class you will
create to handle this event should implement the ActionListener interface.
The A c t i o n L i s t e n e r interface defines a single method,
actionPerformed() that you will need to define within the class. The syntax
of the user-defined class to handle event is:
public class EventExample extends Applet implements
ActionListener
{
public void init()
{
}
public void actionPerformed(ActionEvent ae)
{
}
}
The above syntax shows a class that implements the ActionListener
interface and defines the actionPerformed() method.
Self-Instructional
Material 147
Design Patterns and You will need to register the ActionListener interface to the button
Event Handling
after creating the AWT button. The addActionListener(reference)
method is used for registering the ActionListener interface. The syntax of
the user-defined class to register event is:
NOTES public class EventExample extends Applet implements
ActionListener
{
Button b1;
public void init()
{
b1=new Button(“Message”);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
}
}
The above syntax shows how to use the
addActionListener()method to register the AWT button, which is the
source to the ActionListener interface, which is the event listener.
The following program code shows the complete program to display a
message in the text field when a button is clicked:
Using Event Handling
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=”EventExamp” width=200 height=200>
</applet>*/
public class EventExamp extends Applet implements
ActionListener
{
TextField t1;
Button b1;
public void init()
{
t1=new TextField(20);
b1=new Button(“Message”);
b1.addActionListener(this);
add(t1);
add(b1);
Self-Instructional
148 Material
} Design Patterns and
Event Handling
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
NOTES
{
t1.setText(“Event Handling in Java”);
}
}
}
The above code shows a process defined in the actionPerformed()
method that displays a message in the Text Field. The object, ae, is the object of
the ActionEvent class that is received by the actionPerformed()
method when the button click event occurs.
Figure 8.2 shows the output.

Fig. 8.2 Displaying Message in Textbox

8.4.1 ActionListener
The ActionListener interface declares a method that is called when an
action event is generated. The method defined in ActionListener interface
is a single method, void actionPerformed(ActionEvent ae). You
use the ActionListener interface when you handle events, such as clicking
AWT buttons. The addActionListener() method enables tracing a button
object for the occurrence of an action event. The following program code shows
how to implement the ActionListener interface:
Implementing ActionListener Interface
import java.awt.*;
import java.awt.event.*;
Self-Instructional
Material 149
Design Patterns and import java.applet.*;
Event Handling
/*<applet code=actlistn height=300 width=300>
</applet>*/
public class actlistn extends Applet implements
NOTES ActionListener
{
Button b1,b2,b3,b4;
public void init()
{
b1=new Button(“RED”);
b1.setBackground(Color.red);
b2=new Button(“BLUE”);
b2.setBackground(Color.blue);
b3=new Button(“GREEN”);
b3.setBackground(Color.green);
b4=new Button(“YELLOW”);
b4.setBackground(Color.yellow);
setLayout(new BorderLayout());
add(b1,”North”);
add(b2,”South”);
add(b3,”East”);
add(b4,”West”);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
Object ob=ae.getSource();
if(ob==b1)
setBackground(Color.red);
if(ob==b2)
setBackground(Color.blue);
if(ob==b3)
setBackground(Color.green);
if(ob==b4)
setBackground(Color.yellow);
}
}

Self-Instructional
150 Material
The above program code shows implementing the ActionListener Design Patterns and
Event Handling
with the instances of AWT Button class. Border layout is set to the applet window
and four button objects, RED, BLUE, GREEN and YELLOW are created. When
you click a button the color of background of the window changes to the color of
the button label. Figure 8.3 shows the output of the above program code. NOTES

Fig. 8.3 Using ActionListener Interface

8.4.2 AdjustmentListener
Adjustmentlistener is responsible for handling all the events that are
generated when an end user moves the scrollbar. The various integer constants
used by the adjustment listener method are:
 BLOCK_DECREMENT
 BLOCK_INCREMENT
 TRACK
 UNIT_DECREMENT
 UNIT_INCREMENT
 ADJUSTMENT_VALUE_CHANGED
8.4.3 MouseListener
The MouseListener interface defines five methods for handling different
operations that are associated with a mouse. These methods are:
 void mouseClicked(MouseEvent me): Is invoked when
you click a mouse button.

Self-Instructional
Material 151
Design Patterns and  void mouseEntered(MouseEvent me): Is invoked when the
Event Handling
mouse enters an AWT object to which the mouse event is associated.
 void mouseExited(MouseEvent me): Is invoked when the
mouse leaves an AWT object to which the mouse event is associated.
NOTES
 void mousePressed(MouseEvent me): Is invoked when the
mouse key is pressed.
 void mouseReleased(MouseEvent me): Is invoked when
the mouse key is released.
The addMouseListener() method is used for monitoring an AWT
object for the occurrence of a mouse event. The following program code shows
how to implement the MouseListener interface:
Implementing the MouseListener Interface
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code = mouslstn width = 400 height = 300></
applet>*/
public class mouslstn extends Applet implements
MouseListener
{
String msg=””;
int mx = 0, my = 0;
public void init()
{
addMouseListener(this);
}

public void mouseClicked(MouseEvent me)


{
mx = me.getX();
my = me.getY();
msg = “Mouse Clicked at Position “+mx+”:”+my;
repaint();
}
public void mouseEntered(MouseEvent me)
{
mx=10;
my=10;
msg=”Mouse Entered”;
repaint();
Self-Instructional }
152 Material
public void mouseExited(MouseEvent me) Design Patterns and
Event Handling
{
mx=10;
my=10;
NOTES
msg=”Mouse Left”;
repaint();
}
public void mousePressed(MouseEvent me)
{ }
public void mouseReleased(MouseEvent me)
{ }
public void paint(Graphics g)
{
g.drawString(msg,mx,my);
}
}
The above code shows how to implement MouseListener with the
Applet window object. The mouseClicked() method displays the position
where the mouse is clicked in the Applet window. The me.getX() method
retrieves the position of the X coordinate where the mouse is clicked. The
me.getY() method retrieves the position of the Y coordinate where the mouse
is clicked. The mouseEntered() method displays a message, Mouse
Entered, when the mouse enters the applet window. The mouseExited()
method displays a message, Mouse Exited, when the mouse enters the
applet window.
Figure 8.4 shows the output.

Fig. 8.4 Using the MouseListener Interface


Note: You need to give empty implementation of the methods that you do not create in
a program. Self-Instructional
Material 153
Design Patterns and 8.4.4 MouseMotionListener
Event Handling
MouseMotionListener is another built-in interface for handling mouse
events. This interface handles events that are associated with the movement of the
NOTES mouse. MouseMotionListener defines two methods that are associated
with the movement of a mouse. These methods are:
 void mouseMoved(MouseEvent me): Is invoked when you
move a mouse on an AWT object that is being traced for mouse movement
events.
 void mouseDragged(MouseEvent me): Is invoked when a
mouse button is pressed and the mouse is moved on an AWT object that is
being traced for mouse movement events.
The addMouseMotionListener() method is used for tracing an
AWT object for the occurrence of a mouse movement event. The following program
code shows how to implement the MouseMotionListener interface:
Implementing MouseMotionListener
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=freedraw height=300 width=300>
</applet>*/
public class freedraw extends Applet implements
MouseMotionListener
{
int x,y;

public void init()


{
setLayout(new GridLayout(5,2));
x=0;
y=0;
addMouseMotionListener(this);
}

public void mouseDragged(MouseEvent me)


{
x=me.getX();
y=me.getY();
repaint();

Self-Instructional
154 Material
} Design Patterns and
Event Handling
public void mouseMoved(MouseEvent me)
{}

NOTES
public void update(Graphics g)
{
paint(g);
}

public void paint(Graphics g)


{
g.fillOval(x,y,5,5);
}
}
The above code shows how to implement the MouseMotionListener
interface with the applet window. A freehand drawing mechanism is created where
dragging the cursor plots pixels at those positions creating an image. The
mouseDragged() method is used for retrieving and plotting the pixel positions.
Figure 8.5 shows the output.

Fig. 8.5 Freehand Drawing Using MouseMotionListener

Self-Instructional
Material 155
Design Patterns and 8.4.5 WindowListener
Event Handling
The WindowListener interface defines seven methods for handling window
events. An application of the WindowListener interface is to close a Frame
NOTES window. The seven methods of the WindowListener interface are:
 void windowActivated(WindowEvent we): Is invoked
when a window is activated.
 void windowDeactivated(WindowEvent we): Is invoked
when a window is deactivated.
 void windowOpened(WindowEvent we): Is invoked when a
window is opened.
 void windowClosed(WindowEvent we): Is invoked when a
window is closed.
 void windowClosing(WindowEvent we): Is invoked when
an end user clicks the close button in a window.
 void windowIconified(WindowEvent we): Is invoked
when a window is minimized.
 void windowDeiconified(WindowEvent we): Is invoked
when a window is restored.
The addWindowListener() method enables monitoring a window
for the occurrence of a window event. The following program code shows how to
implement the WindowListener interface:
Implementing the WindowListener Interface
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class windowlistn extends Frame implements
WindowListener
{
Label l1,l2;
TextField t1,t2;
Button b1;
public windowlistn()
{
super(“Implementing Window Listener”);
setLayout(new GridLayout(4,2));
l1=new Label(“Name”);
l2=new Label(“Password”);

Self-Instructional
156 Material
t1=new TextField(10); Design Patterns and
Event Handling
t2=new TextField(10);
t3.setEchoChar(‘*’);
b1=new Button(“Send”);
NOTES
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
addWindowListener(this);
}
public static void main(String ar[])
{
windowlistn d=new windowlistn();
d.setSize(400,400);
d.setVisible(true);
}
public void windowClosing(WindowEvent we)
{
this.setVisible(false);
System.exit(0);
}
public void windowActivated(WindowEvent we)
{}
public void windowDeactivated(WindowEvent we)
{}
public void windowOpened(WindowEvent we)
{}
public void windowClosed(WindowEvent we)
{}
public void windowIconified(WindowEvent we)
{}
public void windowDeiconified(WindowEvent we)
{}
}
The above code shows closing a Frame window using the
WindowListener interface. The windowClosing() method uses the
setVisible method to close the frame window. The System.exit(0)
method stops the program from running.

Self-Instructional
Material 157
Design Patterns and Figure 8.6 shows the output.
Event Handling

NOTES

Fig. 8.6 Closing the Frame Window

8.4.6 KeyListener
The KeyListener interface declares methods that handle input from the
keyboard. The methods defined in the KeyListener interface are:
 void keyPressed(KeyEvent ke): Is called when an end user
presses a key on the keyboard.
 void keyReleased(KeyEvent ke): Is called when an end
user releases a key on the keyboard.
 void keyTyped(KeyEvent ke): Is called when an end user
types a key on the keyboard, which is the operation of pressing and releasing
the key in one fast action.
The requestFocus() method of the Component class has to be
included in your program for receiving keyboard events. The
addKeylistener() method is used for monitoring keyboard events on
objects. The following program code shows how to use the KeyListener
interface for handling events:
Implementing the KeyListener Interface
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=”test” width=”300" height=”200">
</applet>*/

Self-Instructional
158 Material
public class test extends Applet implements KeyListener Design Patterns and
Event Handling
{
String msg[]={“”,””,””,””,””,””,””,””,””,””};
int x=15;
NOTES
int c=x;
int y=15;
int i=0;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
System.out.println(msg);
if(c<200)
{
c=c+5;
msg[i]+=ke.getKeyChar();
System.out.println(msg);
}
else
{
x=15;
y=y+20;
c=x;
i=i+1;
msg[i]+=ke.getKeyChar();
}
if(i>9)
{
for(int k=0;k<10;k++)
{
msg[0]=””;
}
x=15;
y=15;
c=x;
i=0;

Self-Instructional
Material 159
Design Patterns and }
Event Handling
repaint();
}
public void keyReleased(KeyEvent ke)
NOTES
{}
public void keyTyped(KeyEvent ke)
{
}
public void paint(Graphics g)
{
g.drawString(msg[i],x,y);
System.out.println(msg);
}
public void update(Graphics g)
{
paint(g);
}
}
The above code shows implementing the KeyListener Interface for
accepting input from the keyboard to the applet window. The getKeyChar()
method enables taking input from the keyboard and displaying the information in
the applet window. The keyPressed method is used for defining the statements
that are run when an end user enters input from the keyboard.
Figure 8.7 shows the output.

Fig. 8.7 Using KeyListener


Self-Instructional
160 Material
Design Patterns and
Event Handling
Check Your Progress
3. Define ActionListener interface.
4. What is the use of addMouseListener() method? NOTES

8.5 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. Event are activities that interrupts the normal flow of the current ongoing
activity.
2. Constrained Properties are the properties that are protected from being
changed by other Java Beans.
3. The ActionListener interface declares a method that is called when
an action event is generated. The method defined in ActionListener
interface is a single method, void a c t i o n P e r f o r m e d
(ActionEvent ae).
4. The addMouseListener() method is used for monitoring an AWT
object for the occurrence of a mouse event.

8.6 SUMMARY

 Defining a bean’s state means defining a property which can depict its state.
A bean property can be considered as a named attribute of a bean that can
be used to define its behaviour or appearance like colour, label, font, font
size, and display size, etc.
 An event occurs when there is a change in the active state of components
such as buttons and text boxes.
 The event delegation model defines the standards and mechanisms to handle
events in Java.
 Events are the objects in an event delegation model that are generated when
the end user interacts with the AWT components such as buttons,
checkboxes and text fields. Events are also generated from end-user input
through the keyboard and mouse.
 The EventObject class is the super class for handling all events. This
class exists in the package, java.util.

Self-Instructional
Material 161
Design Patterns and  AWT components such as buttons and text boxes are the sources of events.
Event Handling
 The event listeners are the interfaces in Java that define the methods for
handling events.
NOTES  The ActionListener interface declares a method that is called when
an action event is generated. The method defined in ActionListener
interface is a single method, void a c t i o n P e r f o r m e d
(ActionEvent ae).
 The addMouseListener() method is used for monitoring an AWT
object for the occurrence of a mouse event.
 MouseMotionListener is another built-in interface for handling
mouse events. This interface handles events that are associated with the
movement of the mouse.
 An application of the WindowListener interface is to close a Frame
window.

8.7 KEY WORDS

 Event handling: It is the process to monitor any change in the state of an


object and perform a corresponding action.
 Event classes: These classes represent the events that are generated when
an end user interacts with the AWT components.
 Action listener: It is an interface that is used to declare a method that is
called when an action event is generated.

8.8 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short-Answer Question
1. What do you understand by event delegation model in Java Beans?
2. How do you create event listeners?
3. What are the design patterns for Java Bean properties?
Long-Answer Questions
1. Write a detailed note on indexed properties.
2. What are events? How do you create custom events?
3. Write a detailed note on simple properties.

Self-Instructional
162 Material
Design Patterns and
8.9 FURTHER READINGS Event Handling

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill. NOTES
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
Material 163
Bean Properties and
Persistence
UNIT 9 BEAN PROPERTIES AND
PERSISTENCE
NOTES
Structure
9.0 Introduction
9.1 Objectives
9.2 Bound and Constrained Properties
9.2.1 Persistence
9.2.2 Customization
9.2.3 Bean Conventions
9.2.4 A Simple Bean
9.3 The Java Beans API
9.4 Answers to Check Your Progress Questions
9.5 Summary
9.6 Key Words
9.7 Self Assessment Questions and Exercises
9.8 Further Readings

9.0 INTRODUCTION

A Java Bean property is constrained when any change to that property can be
vetoed. Usually an outside object exercises the right to veto. However, in some
cases the Bean itself can also veto a property change. The JavaBeans API provides
an event mechanism. This mechanism is very similar to the bound property
mechanism that allows objects to veto a Bean’s property changes. The design
pattern for setting and getting constrained properties is similar to the design pattern
for properties that are not constrained. The difference is that the set method declares
that it throws the exception. In this unit you will study about Constrained Properties

9.1 OBJECTIVES

After going through this unit, you will be able to:


 Understand the bound and constrained properties
 Understand bean persistence
 Understand Java Beans API and their use

9.2 BOUND AND CONSTRAINED PROPERTIES

A bound property is a property that generates an event when its value is changed.
A bean provides this notification by following methods.
Self-Instructional
164 Material
public void Bean Properties and
addPropertyChangeListener(PropertyChangeListener p) Persistence

{
changes.addPropertyChangeListener (p);
NOTES
//provides notification when an attempt is made
//to change the bound property
}
public void
removePropertyChangeListener(PropertyChangeListener p)
{
changes.removePropertyChangeListener (p);
//to remove listener
}
Note: The PropertyChangeListener is an interface that is declared in java.beans
package.
A constrained property is a property that notifies other objects or
components when attempts are made to change their values. When other component
is not agreed to the change of the property it throws
PropertyVetoException. Following are the methods provided by
constrained properties.
public void addVetoableChangeListener
(VetoableChangeListener v)
{
vetos.addVetoableChangeListener (v);
}
public void removeVetoableChangeListener
(VetoableChangeListener v)
{
vetos.removeVetoableChangeListener (v);
}
9.2.1 Persistence
As stated earlier, a bean is a reusable software component that can be used in
other applications. To use it in other applications and to make it portable, its state
should be saved to the non volatile storage from where it can be retrieved later.
The process of saving the current state of bean is referred to as persistence.
Persistence can be achieved by serializing a bean. A bean can be serialized
by implementing the java.io.Serializable interface. This interface is
a marker interface that makes serialization automatic. In case a bean does not
implement the java.io.Serializable interface, serialization must be

Self-Instructional
Material 165
Bean Properties and provided explicitly by implementing the java.io.Externalizable
Persistence
interface.
Note: Object serialization is a method of converting an object into data stream.

NOTES 9.2.2 Customization


During the development process, it is required to configure the bean according to
requirement. To help other developers to configure the bean, customizer
can be provided. A customizer is a step-by-step guide that provides the
instructions to be followed for using the bean in specific context. Online
documentation can also be useful to configure the bean.
9.2.3 Bean Conventions
A bean is a simple Java class that follows some basic conventions which are as
follows:
 A bean should implement the Serializable interface.
 A bean should have a no-argument constructor.
 A bean should be public and provide getter and setter methods for accessing
its properties.
9.2.4 A Simple Bean
Let us consider a program of a simple bean.
Example 9.1: A simple bean
package com.start.bean.test //package statement
public class SimpleBeanExample implements
java.io.Serializable
{
/* Properties */
private String ename = null;
private int eid = 0;
/* Empty constructor */
public SimpleBeanExample()
{
}
/* Getter and Setter methods */
public String getEname()
{
return ename;
}
public void setEname(String s)
{

Self-Instructional
166 Material
ename = s; Bean Properties and
Persistence
}
public int getEid()
{
NOTES
return eid;
}
public void setEid(int i)
{
eid = i;
}
}
The explanation of this program is as follows:
 The statement package com.start.bean.test is the
package statement.
 The statement public class SimpleBeanExample
implements java.io.Serializable defines a class
named S i m p l e B e a n E x a m p l e that implements the
Serializable interface to provide persistence to the bean. Note
that the Serializable interface does not contain any method.
 The statements private String Ename = null and
private int Eid = 0 declare properties of the bean. The
properties are declared private, thus, are not accessible directly by other
classes.
 The statement public SimpleBeanExample(){} creates
an empty constructor. For behaving Java class as a bean, this is the
basic requirement.
 The methods getEname()and setEname()are the getter and
setter methods respectively of property Ename.
Like any other Java class file, compile the bean. Upon compilation,
SimpleBeanExample.class file will be created.

9.3 THE JAVA BEANS API

The classes and interfaces related to the development of beans are contained in
the package java.beans. The beans use only few classes while running in an
application. For example, the event classes are used by beans that generate
PropertyChangeEvent and VetoableChangeEvent. Most of the
classes in this package are used by a bean editor to customize and put beans
together to create an application. These classes enable the bean editor creating a
user interface that can be used by a developer to customize the bean.
Self-Instructional
Material 167
Bean Properties and Table 9.1 The Interfaces Defined in java.beans Package
Persistence

Interface Description
AppletInitializer It is designed to provide a mechanism for the
NOTES initialization of Java Beans that are applets.
BeanInfo It is implemented to provide explicit information
about the methods, properties, events, etc., of a
Bean.
Customizer It provides a complete custom GUI using which a
Java Bean can be customized.
DesignMode It allows determining whether a Bean is executing
in design mode.
ExceptionListener A method exceptionThrown of this interface is
invoked when an internal exceptions occurs.
PropertyChangeListener A method PropertyChangeEvent of this
interface gets fired whenever a bean changes a
bound property.
PropertyEditor It provides support for GUIs that allow users to
change a property value of a given type.
VetoableChangeListener A method VetoableChangeEvent of this
interface is invoked whenever a bean changes a
constrained property.
Visibility It enables a bean to run on servers where a GUI is
not available.

Table 4.3 The Classes Defined in java.beans Package

Class Description
BeanDescriptor It provides Bean specific information
including its Java class, its displayName,
etc.
Beans It provides methods to obtain general
information about a Bean.
DefaultPersistenceDelegate It is a concrete implementation of the
abstract PersistenceDelegate class
and is the delegate used by default for
classes about which no information is
available.
Encoder It is used to create streams that encode
the state of a collection of Java Beans in
terms of their public APIs.
EventHandler It provides support for dynamically
generating event listeners.
EventSetDescriptor It describes a group of events that a given
Java bean generates.

Self-Instructional
168 Material
Expression It encapsulates a call to a method that Bean Properties and
Persistence
returns a result.
FeatureDescriptor It is the base class for
PropertyDescriptor,
EventSetDescriptor, and NOTES
MethodDescriptor class.
IndexedPropertyChangeEvent An event of this type gets fired whenever
a Bean changes a bound indexed property.
IndexedPropertyDescriptor It describes a property that acts like an
array and has an indexed read and/or
indexed write method to access specific
elements of the array.
Introspector It provides a standard way to analyze
about the properties, events, and methods
supported by a Bean.
MethodDescriptor It describes a method that a Bean
supports for external access from other
components.
ParameterDescriptor It allows bean developer to provide
additional information about the
parameters of a method.
PersistenceDelegate It is used to express the state of an
instance of a given class in terms of the
methods in the class’s public API.
PropertyChangeEvent An event of this type is fired whenever a
bean changes a bound or constrained
property.
PropertyChangeListenerProxy It extends the EventListenerProxy
for implementing
PropertyChangeListener.
PropertyChangeSupport It is a utility class that is used by beans
that support bound properties.
PropertyDescriptor It describes one property that a Bean
exports using a pair of accessor methods.
PropertyEditorManager It is used to locate a property editor for
any given type name.
PropertyEditorSupport It provides functionality that helps in
building property editors.
SimpleBeanInfo It is a support class that helps to write
BeanInfo classes easily.
Statement It encapsulates a call to a method.
VetoableChangeListenerProxy It extends the EventListenerProxy
for associating a
VetoableChangeListener with a
constrained property.
Self-Instructional
Material 169
Bean Properties and VetoableChangeSupport It is a utility class that is used by beans
Persistence
that support constrained properties.
XMLDecoder It is used to read XML documents
created using the XMLEncoder .
NOTES XMLEncoder It allows to write a Bean to an XML
document.
IntrospectionException An IntrospectionException is
thrown when an exception occurs during
Introspection.
PropertyVetoException A PropertyVetoException is
thrown when a change to a property
indicates an unacceptable value.

Check Your Progress


1. What is persistence?
2. Define AppletInitializer.

9.4 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. The process of saving the current state of bean is referred to as persistence.


2. AppletInitializer it is designed to provide a mechanism for the mitialization
of Java Beans that are applets.

9.5 SUMMARY

 A bound property is a property that generates an event when its value is


changed.
 A constrained property is a property that notifies other objects or
components when attempts are made to change their values. When other
component is not agreed to the change of the property it throws
PropertyVetoException.
 The process of saving the current state of bean is referred to as persistence.
 A customizer is a step-by-step guide that provides the instructions to
be followed for using the bean in specific context.
 The classes and interfaces related to the development of beans are contained
in the package java.beans.

Self-Instructional
170 Material
Bean Properties and
9.6 KEY WORDS Persistence

 Persistence: Persistence in Java Beans can be defined as the ability to


save and store properties and events of the beans to some storage from NOTES
where these can be retrieved when needed.
 Package java.beans: It is a package that contains all the classes that can
help you in developing beans.

9.7 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short-Answer Question
1. Define bound property.
2. What are constrained properties?
3. How will you achieve persistence?
Long-Answer Questions
1. Explain the methods provided by the constrained properties.
2. Explain the interfaces defined in java.beans package.
3. What are the classes defined in java.beans package? Explain.

9.8 FURTHER READINGS

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
Material 171
Java Servlets
BLOCK - I
SERVLETS

NOTES
UNIT 10 JAVA SERVLETS
Structure
10.0 Introduction
10.1 Objectives
10.2 Introduction to Java Servlets
10.2.1 Servlets Vs CGI
10.3 Servlet Developmental History
10.4 Prerequisites for Servlets
10.4.1 HTML
10.4.2 Servers
10.4.3 Servlet Container
10.4.4 Installing and Configuring the Apache Tomcat Server
10.4.5 Starting and Stopping Tomcat
10.4.6 Testing Tomcat
10.5 Basics of Servlets
10.5.1 The Java Servlet API
10.5.2 Servlet Life Cycle
10.6 Coding a Servlet
10.6.1 GenericServlet Class
10.6.2 An Example of GenericServlet Class implementation
10.6.3 The Dissection
10.6.4 Output
10.7 Http Servlet Class
10.7.1 Methods of Http Servlet Class
10.7.2 An Example of Http Servlet Class implementation
10.7.3 The Dissection
10.8 The First Run
10.9 First Web Application Using Servlet
10.10 A Web Application based on HTML Web Page and Servlet
10.11 A Web Application Handling User Inputs via Forms Using Servlets
10.12 Answers to Check Your Progress Questions
10.13 Summary
10.14 Key Words
10.15 Self Assessment Questions and Exercises
10.16 Further Readings

10.0 INTRODUCTION

Java servlets are the Java programs that are used to handle server-side operations
in client-server architecture. CGI scripts were used prior to Java servlet for client-
server computing. This unit discusses the servlet life cycle using various methods
Self-Instructional
172 Material
such as init(), service() and destroy(). It then describes the Java Servlets

generic servlets that are used to service the client request and http servlets, which
are used to service the server request.

NOTES
10.1 OBJECTIVES

After going through the chapter, you will be able to:


 Define the Servlets and state their usages
 Differentiate between Servlets and CGI
 Update with latest Servlet Specification
 Understand the Servlet life cycle and how a container manages a Servlet
 Code the Servlets according to the need of Reading Initialization Parameters,
Reading Servlet Parameters
 Discuss the Session management using Servlets
 Conceptualize the methods of debugging the Servlets

10.2 INTRODUCTION TO JAVA SERVLETS

Java has become an undoubtedly the best language for server side programming
due to Java Servlets. Java Servlets provide a standard way of server extension-
i.e. Servlets extend the functionality of the web servers to support dynamic content
generation. They reside in a Servlet container and generate dynamic contents in
response to client requests. The primary purpose of the Servlet specification is to
define a secure and robust mechanism for sending contents to a client as defined
by the Client/Server model. Servlets are most popularly used for generating dynamic
contents on the Web and have native support for HTTP. So, Servlets are now
essential parts of large web projects called web applications.
Java Servlets can be defined as the java programs, with an inbuilt support
to HTTP for getting requests and sending responses, which are implemented at
the server side for processing and creating dynamic contents for the client. These
are specialized java programs which do not have any main method, as their
implementation is the functionality of the web server where they reside. Java servlets
have native support to HTTP, and this is the biggest advantage that servlets have
used for their popularity by interweaving a complete specification across it.
With the introduction of the J2EE specification for enterprise applications,
Servlets have substituted every possible technology available for server side
programming as the primary interface for thin-client (browsers are universally
available thin clients) based web applications. The existing technologies like CGI,
ASP, and PHP did the same thing as Servlets–i.e. they too helped servers handle

Self-Instructional
Material 173
Java Servlets the client request and dynamically create responses accordingly, but Java Servlets
have some major advantages above all. A few of them can be highlighted as follows:
 Servlets are persistent between invocations; hence improve the
performance drastically relative to CGI programs.
NOTES
 Servlets are cent-percent portable across all the major operating systems
and servers available in the market.
 Servlets pertains to J2EE specification, hence has access to all the Java
APIs be it Java Beans or database connectivity using JDBC APIs.
Java Servlets have always stood as a top performer in providing an efficient
and powerful solution for creating dynamic content for the Web. Hence, they are
also considered as the fundamental building block of mainstream server-side Java.
The efficiency and the power that Servlets have, has come from the use of
Java as a platform and from interaction with a Servlet container.
The Java platform provides a Servlet developer with robust APIs, object-
orientated programming methodology, platform independence, I18N
(Internationalization), strict types, garbage collection and above all, the security
features of the Java Virtual Machine (JVM). To complement this, the Servlet
container provides life cycle management, process to share and manage application-
wide resources, and help interact with a web server properly. This combination of
Java API support and Servlet container together makes Servlets a super desirable
technology for server-side programming.
So let’s begin with the Java Servlets basics and understand the key APIs of
Java Servlets that make them work. The latest version of Java Servlets is 3.1.

Fig.10.1 Servlets in Action

Self-Instructional
174 Material
10.2.1 Servlets Vs CGI Java Servlets

The table below explains why Servlets out performed CGI, the first server side
technology?
Table 10.1 Servlets Vs CGI NOTES

SERVLETS CGI(Common Gateway Interface

1. Servlets can link directly to the Web 1. CGI cannot directly link to Web
server. server.
2. Servlets can share data among each 2. CGI does not provide sharing
other. property.
3. Servlets can perform session tracking 3. CGI cannot perform session
and caching of previous tracking and caching of previous
computations. computations.
4. Servlets are portable. 4. CGI is not portable.
5. In Servlets, the Java Virtual Machine 5. In CGI, each request is handled by
stays up, and each request is handled a heavyweight operating system
by a lightweight Java thread. process.
6. Servlets automatically parse and 6. CGI need explicit parsing and
decode the HTML form data. decoding of the HTML form data.
7. Servlets can read and set HTTP 7. CGI cannot read and set HTTP
headers, handle cookies, tracking headers, handle cookies, tracking
sessions. sessions.
8. Servlets is platform independent, 8. CGI is platform dependent.
robust.
9. Follow OOPS principle as it is a Java 9. No such support for OOPS in
Specification. CGI.
10. Servlets do not support multiple 10. CGI Supports Multiple Languages
languages except Java. like C,C++,Perl etc.

10.3 SERVLET DEVELOPMENTAL HISTORY

The Servlets that we use today are far more powerful and dynamic than the one
that laid the foundation of the robust, multithreaded Server Side programming in
1970.Servlet specification has taken a long journey to reach to this level, and still
there are advancements and modifications that are continuing so that it can make
pace with the contemporary technological changes.

Self-Instructional
Material 175
Java Servlets The developmental history of Java Servlets can be seen in the table below:
Table 10.2 Servlet Developmental History

Servlet API Platforms Release Updates


NOTES Version supported Date
Servlet 3.1 JavaEE 7 May 2013  Support Non-blocking I/O
 HTTP protocol upgrade mechanism
 Security enhancements
 Clarifications in Servlet Specifications
and APIs.
Servlet 3.0 JavaEE6, Dec 2009  Security enhancements
JavaSE 6  Ease of development,
 Async Servlet, Security, File Uploading
 Pluggability
Servlet 2.5 JavaEE 5, Sep 2005  A new dependency on J2SE5.0
JavaSE 5  Support for Annotations
 Conveniences in web.xml
 Some added restrictions and clarifications
with some cleaning

Servlet 2.4 J2EE 1.4, Nov 2003  Servlets now require HTTP/1.1 and J2SE
J2SE 1.3 (Java 2 Platform, Standard Edition) 1.3,
and can work with J2EE 1.4
 ServletRequest has new methods to
observe the client connection
 New support for internationalization and
charset choice
 RequestDispatcher has new features and
clarifications
 New ServletRequest listener classes and
methods
 A deprecated SingleThreadModel
 HttpSession details and interaction with
logins has been clarified
 Class loading and welcome-file behavior
has been clarified
 The web.xml file now uses XML Schema
and has added a slew of new elements
Servlet 2.3 J2EE 1.3, Aug 2001 1. Servlets now require JDK 1.2 or later
J2SE 1.2 2. A filter mechanism has been created
(finally!)
3. Application lifecycle events have
been added
4. New internationalization support has
been added
5. The technique to express inter-JAR
dependencies has been formalized
6. Rules for class loading have been
clarified
7. New error and security attributes
have been added
8. The HttpUtils class has been
deprecated
9. Various new helpful methods have
been added
10. Several DTD behaviors have been
expanded and clarified

Self-Instructional
176 Material
Servlet 2.2 J2EE 1.2, Mid 1999  Servlets are now part of the Java Java Servlets
J2SE 1.2 2 Platform, Enterprise Edition
specification
 Servlets now embrace the notion
of pluggable Web applications,
which can be configured and NOTES
deployed in a server-independent
manner
 Rules have been provided that
define how Servlets can be
distributed across multiple back-
end servers
 Response output buffering has
been added
 Control over HTTP headers has
been enhanced
 New styles of request dispatching
have been added
 More advanced error handling
can now be used
 Several method signatures have
been changed to keep the API
consistent
Servlet 2.1 Unspecified Nov 1998  The API has been "cleaned up" to
make method names more
consistent and predictable
 Servlets can now delegate request
handling to other server
components
 Servlets can now share
information using their
ServletContext
 There's a new way to abstract
servlet resources
 Servlets now have more control
over session management
 No direct servlet references

Servlet 2.0 JDK 1.1 1997-1998 Part of Java Servlet Development Kit 2.0
Servlet 1.0 June 1997 First specification release

10.4 PREREQUISITES FOR SERVLETS

Servlets are java programs, with an inbuilt support to HTTP for getting requests
and sending responses. Hence, one should be well acquainted with the Java
programming syntax and semantics apart from knowledge of HTTP methods. In
the previous chapter, enough material has been provided on HTTP and its methods.
Though we are going to program a server on client-server architecture, the language
of communication between the server and the client will be HTML, so one should
also know the basics of HTML as well for proper formatting of the display pages
(the responses). There is one more technology-XML (eXtensible Markup
Language) that you should know, though just a little but it will surely help in proper
execution of the Servlets. XML works as the interface between the Servlet and
the Server. A web.xml file is created for a Servlet which has the configuration
Self-Instructional
Material 177
Java Servlets details of the servlet that the server uses for its execution. Even if there is a single
error in the xml, then also your servlet will not execute as Server will not have the
information regarding the servlet. A separate chapter on XML has been included
in the book which will provide all that you need, so it will not be discussed here.
NOTES
So, the prerequisites for understanding the Servlets can be summarized as:
1. Java Programming syntax and semantics for coding the Servlets.
2. HTML Basics for form handling and response generation.
3. XML Basics for configuration of Servlet.
4. HTTP protocols and all its methods.
5. Server Basics like starting, deployment mechanics and shutting down
the Server along with server setup and configurations.
You will have to be well versed in Java Programming language before
proceeding further as it will be difficult for you to understand the logics and the
code. HTTP has already been discussed in the previous chapter. You will learn
about the other preliminaries like HTML, Servers, and XML in the coming sections
in the book. Now let’s see HTML in brief in this section itself aiding to the
understanding of servlet properly.
10.4.1 HTML
In this section, only the tags that have been used in the examples have been stated.
You will learn about the tags and their description here and uses in the examples of
the servlets.
HTML tag Description
1. <html>, </html>
 Compulsory Tag
 These tags mark the start and the end of an HTML document.
 Every HTML document must start with this tag and also end with this
tag.
2. <head>, </head>
 Optional Tag
 This tag marks the start and end of the head section of an HTML
document.
3. <title>, </title>
 Optional Tag
 This tag is used to mark a title element. The text between the start and
end tags is shown in the title bar of the browser window.

Self-Instructional
178 Material
4. <body>, </body> Java Servlets

 Compulsory Tag
 This tag marks the start and end of the body section of an HTML
document which contains the content to be displayed on the web page. NOTES
 The content of the document is provided between these tags.
5. <h1>, </h1>; <h2>, </h2> ; <h3>, </h3>
 Optional Tags
 These tags format the text between them as a level-1 heading,level-2
heading and level-3 heading respectively.
6. <form action=”url”, method=”method”> </form>
 Optional Tags
 This tag marks the start of a form. The action attribute specifies the
name of the page, servlet, etc. where the form is posted to. The method
attribute can be GET or POST; it indicates the type of HTTP request
sent to the server.
 </form> Marks the end of the form. It is compulsory to close.
7. <input type=”type”, name=”name”>
 Optional Tag
 This tag helps to create an input field.
 Specify type=”text” to create a text field or type=”submit” to create a
Submit button.
 The name attribute provides the name you use in the program to retrieve
the data entered by the user.
8. &nbsp;
 Represents a non breaking space.
Note: Try to create HTML web pages before implementing these tags in the Servlets
for better understanding and also run them on the browser for getting the realistic
feel.
10.4.2 Servers
Servlets do not have a main () method like their counterparts in core Java-the
applets or any simple Java program. So it is the server or the container who has to
take care of the proper execution of the servlet by invoking the Servlet methods.
As the servlet program will run only on a server, you should be familiar with the
various servers available and their configurations to run a servlet. So you might be
having a question why Servlets run only in a server and not as a standalone
application? It is because the Servlets form the extended API of Java Specifications
and are not bundled with the Java Standard Development Kit. Servers have the
Self-Instructional
Material 179
Java Servlets APIs that support the servlet execution and manage the various requirements of a
servlet hence it should be kept in the server context. Various servers that can be
used are as follows:
1. Oracle Weblogic Server
NOTES
2. J2EE server
3. Apache Tomcat HTTP Server
4. Jetty
5. JBoss
6. Glassfish Servers
10.4.3 Servlet Container
A servlet container is the application software that is used to run servlets. A servlet
container uses a Java Virtual Machine (JVM) to run servlet code as requested by
a web server. The main task of the Servlet container is to help a servlet properly
complete their lifecycle and perform specific tasks. The servlet container is also
responsible for managing user sessions, class loading, servlet contexts, servlet
configuration information, servlet persistence, and temporary storage apart from
the basic servlet lifecycle. As interaction with servlets occurs through a web browser,
these servlet engines aren’t useful on their own.
There are different types of servlet containers on the basis of their uses.
Some of them simply work as add-ons to existing web servers like JServ. Apache
JServ is a Servlets container (based on Servlet 2.0 Specification) that adds servlet
capability to the Apache Web Server. Some servlet engines include embedded
web servers like Jetty server and IBM’s WebSphere. Finally, there are some
more servlet engines that can be used either as standalone web servers or connected
to other servers, like Apache Tomcat server.
Apache Tomcat is the reference implementation for the Servlet API , all the
examples in this chapter have been tested using it.
So, in this section we will discuss the servers and their configurations as
needed. The most popular one to be used is Apaches Tomcat Server, though it
just acts as a container providing the servlet a support to all its life cycle methods-
i.e. can cater the basic needs of a servlet. But when it comes to high level support
like for connection pooling, database configurations, etc., Tomcat has an extreme
limitation. As Tomcat is a basic server, it can be used for general testing and
debugging the Servlets. And if any additional support is required it can be fulfilled
using Apache Tomcat HTTP server.
10.4.4 Installing and Configuring the Apache Tomcat Server
If you want to run servlet programs on your computer, you have to install a special
program called a servlet engine to convert your computer into a server which is

Self-Instructional
180 Material
capable of running the Servlets. The best-known and easily configurable servlet Java Servlets

engine is Apache Tomcat, which is open source software freely distributed by the
Apache Software Foundation at http://tomcat.apache.org.Tomcat simply works
as a basic web server. In actual production environments, Tomcat is usually used
in combination with a specialized web server, such as Apache’s HTTP Server. NOTES
Here are the steps you can follow to set up Tomcat
1. Download an executable setup from the Apache website (http://
tomcat.apache.org).
2. Double Click and install the setup. as instructed

Fig. 10.2 Click the Next button

Fig. 10.3 Click the I Agree button Click I Agree button

Self-Instructional
Material 181
Java Servlets

NOTES

Fig. 10.4 Select all the options and then click on the Next Button

Fig. 10.5 Proceed with Next

Change the Http/1.1 connector Port as 8888(If you wish you can keep
the same but it should not conflict with any existing application on the system.If
you wish give username and pasword also.click on the Next Button once you
are done.

Self-Instructional
182 Material
Java Servlets

NOTES

Fig. 10.6 Select the path of the Java SE. Click Next button

Fig. 10.7 Wait until the progress is complete.

Self-Instructional
Material 183
Java Servlets

NOTES

Fig. 10.8 Now, you are ready for rocking. The Tomcat has successfully installed. Just
Click on Finish button. And you should see this

Fig. 10.9 If the progress completes without any error then your tomcat is ready to serve
as the server

3. Copy the “servlet-api.jar” file to the jre\lib\ext folder in your JDK root or
simply you can copy the address of servlet-api.jar to the environment variable
“classpath”. I prefer the latter. If you skip this step or copy the servlet-
api.jar file to the wrong place, you can’t compile your servlet programs. If
you get compiler messages complaining that the javax.servlet package
doesn’t exist, double-
Check this step to make sure you performed it right.
10.4.5 Starting and Stopping Tomcat
After you have successfully installed and configured Tomcat,
Go to Program Files => ApacheSoftwareFoundations =>Tomcat =>bin
=>Click on Tomcat7w.exe .
You will see the following window.
Self-Instructional
184 Material
Java Servlets

NOTES

Fig. 10.10 If this window displays Service Status: started then it means your tomcat is
running. If you wish to stop the services click on Stop and Apply.

10.4.6 Testing Tomcat


To find out whether you have installed Tomcat correctly or not, you can give hand
on running the test Servlets that are automatically installed with the Tomcat server.
Open a web-browser window, and type this address:
http://localhost:8888
If you get the following Tomcat page then it means your server has properly
installed and is running.

Fig. 10.11 Tomact Server Welcome Page.


Self-Instructional
Material 185
Java Servlets
10.5 BASICS OF SERVLETS

Java Servlets can be defined as some platform independent, robust server side
NOTES programs coded in Java. These programs execute inside an application server or
a Java enabled web server. Some define servlet as a protocol used for execution
of server side java programs. Servlets can be regarded as server side applets also
as these are loaded and executed within the JVM of the server used which is
pretty similar to the applets which are loaded and executed within the JVM of the
browser (web client).Since no GUI is needed for Servlets, as they run inside a
server, they are often termed as faceless objects.
What CGI programs could not do, Servlets have performed them very
well-be it providing security, persistence between invocations or servicing a large
number of requests efficiently, Servlets have been the number one choice of the
web developers for all scenarios.
Servlets implement a request-response methodology, wherein the client
application sends a request to the server, server then forwards this request to the
servlet which generates responses according to the client’s requests and in due
course Servlets can also communicate with external resources like database servers
etc for fulfilling the client’s requests. These responses are then channeled to the
server which finally displays them to the client with additions like forms, etc.
The power of Java Servlets comes from the Java Servlet API which is a
standard interface between web server and web clients. These APIs are confined
only to the server, so are not present in the standard Java development Toolkits.
The Java Servlet API is a set of predefined Java classes which provides a standard
interface between client and the server.
The Java Servlet API is an extension API, which is not bundled or distributed
with the Java SDK; rather it is available as an additional package in any of the
servers-Tomcat, Weblogic, and Jetty etc as servlet-api.jar. Only thing that you
have to do is to show the operating system the path to that package so that operating
system can include them when required.
10.5.1 The Java Servlet API
The Java Servlet API is a set of Java classes, interfaces and methods which defines
a standard interface between a client and a web server. It is the specification that
every server and servlet has to comply with for proper execution of the Servlets.
We will be using the Java Servlet Development Kit API (JSDK) V2.1 conventions
throughout this chapter.
The Java Servlet API comprises of two packages:
 javax.servlet
 javax.servlet.http

Self-Instructional
186 Material
1. javax.servlet package Java Servlets

This javax.servlet package consists of the classes and interfaces that support generic
protocol independent Servlets. These Servlets include support to many protocols,
like HTTP and FTP. NOTES
This package consists of the main interface-the Servlet interface that contains
the basic lifecycle methods of a servlet which every servlet must implement.
GenericServlet class implements the Servlet interface. Hence, the implementation
of these life cycle methods (init (), service () and destroy ()) are itself provided in
a GenericServlet class except the service () method. This is because the task that
a servlet need to perform is to be written inside the service () method which is in
the discretion of the programmer not the server.

Fig.10.12 The Servlet API

So, whatever you wish to do, you have to write it in the service () method
overriding it in your servlet by extending the GenericServlet class. If necessary,
you can override the remaining methods also. There are several interfaces and
classes found in this javax.servlet package.
They are as follows:
Interfaces:
1. Servlet interface: It is the main interface that every Servlet must implement.
It defines the key methods that a Servlet container calls to control the Servlet.
2. ServletRequest interface: This interface provides the methods to gather
information from a client request.
3. ServletResponse interface: This interface helps to provide various
methods to create and send the response to the client’s request.
Self-Instructional
Material 187
Java Servlets 4. ServletConfig interface: This interface allows the servlet container to
pass the configuration related information to a servlet.
5. ServletContext interface: This interface allows the servlet to communicate
with its container. Also called Communication Interface.
NOTES
6. SingleThreadModel interface: This interface is used to make a servlet
service one request at a time. Though it has been deprecated, it can be still
used in development.
Classes:
1. Abstract Class GenericServlet: Every Servlet has to extend this abstract
class as this class implements all the methods of the Servlet interface except
the service () method. This is protocol independent class. This abstract
class also implements the ServletConfig interface which allows the servlet
container to pass configuration related information to the servlet.
2. ServletInputStream: This class provides an input stream for reading
requests from the client.
3. ServletOutputStream:This class provides an output stream for writing
the responses to a client.
4. ServletException: A general exception class to signal servlet runtime errors
and exceptions.
5. UnavailableException:An exception class to signal that a servlet is
permanently or temporarily unavailable.
2. javax.servlet. http package
The Web content is basically accessed via the HyperText Transfer Protocol (HTTP).
A basic Servlet knows nothing about HTTP, but there is a special implementation
of Servlet, javax.servlet.http.Http Servlet that is designed especially for it and it is
found inside the javax.servlet.http package.
This javax.servlet.http package consists of classes that extend the base
package (javax.servlet) functionality to provide support to HTTP protocol and its
methods like GET and POST. If you wish to write a servlet from scratch, this
package will provide you the required classes and interfaces.
There are several interfaces and classes found in this javax.servlet.http
package. They are as follows:
1. Abstract class Http Servlet: This abstract class extends the
GenericServlet class and is used for implementing HTTP Servlets, i.e.
Servlets which use HTTP for requests and responses. Basically, it
provides stubs for the doHttpRequestMethodName() methods which

Self-Instructional
188 Material
correspond to the HTTP methods used in the request (GET, POST, Java Servlets

HEAD, etc.) correspondingly as doGet(), doPost(), doDelete(), doPut()


etc . A servlet can override the any of the above mentioned helper methods
to handle the different HTTP requests.
NOTES
2. Http ServletRequest interface: This interface extends the
ServletRequest interface to handle HTTP requests.
3. Http ServletResponse interface: This interface extends the
ServletResponse interface to create and send an appropriate HTTP
response to an HTTP request.
4. HttpSession interface: This interface provides a way to identify a
user across mor than one page request or visit to a Web site and to
store information about that user.
5. Cookie class: This class provides support for cookies to be used in
requests and responses.
In either of the cases, the top level package is javax, instead of java. An
additional ‘x’ in java as javax states that the Servlet API is a standard extension of
the java.
10.5.2 Servlet Life Cycle
If you want to get a clear insight of the basic functionality of Servlets, then you
need to understand the life cycle they follow. It should be noted that the Servlets
do not have a main () method like their counterparts in core Java-the applets. So
it is the server or the container who has to take care of the proper execution of the
Servlet and all its methods. Servlet life cycle comprises of the basic methods that
are well supported by the containers called lifecycle methods. It is the container/
server who has to execute these methods using the built in JVM i.e. Servlet
Containers provide a runtime environment for the Servlet to function properly.
The Servlet life cycle creates a runtime multi-threaded environment that Servlets
run in and provides some methods for sharing server-side resources as well.
The Servlets complete their life in three-phases:
(a)Initialization,
(b)Service, and
(c)Destruction.
(a) Initialization Phase
When a Servlet is requested by the client (read browser here), the Servlet is
loaded onto the server, the server initiates the Servlet initialization phase by calling
init () method. In this phase, creation and initialization of the resources is done that
the servelet requires.

Self-Instructional
Material 189
Java Servlets

NOTES

Fig.10.13 Servlet Life Cycle

Also, this phase can be used for the creation of I/O intensive resources like
database connectivity for multiple invocations. It is a onetime initialization process
that prepares the Servlet to service the client’s requests properly and helps in
improving the performance dramatically.
The initialization phase is represented in Servlet as init () method. All the
Servlets must comply with the implementation of the javax.servlet.Servlet interface,
which consists the init () method definition. As execution of servlet is managed by
the servlet container or the server, init () method is invoked by the container or the
server when the Servlet is loaded, to provide all the resources it requires just once
at its loading time.
The init () method is invoked before servicing any client request and is
called only once per cycle when a Servlet is first loaded onto the server and does
not invoke if the same Servlet is called again and again which improves the
throughput drastically for multiple invocations from clients. After the initialization
phase the server marks the Servlet as available for service.
The init () method has the following prototype:
Public void init (ServletConfig config) throws
ServletException
{
\\ the initialization code (database connections etc.)
}
(b) Service Phase
For each request coming for a servlet, servlet container calls a service () method
for performing the task.The Servlet activity is coded inside the service () method,
which represents the service phase of a Servlet. The service () method can have
access to all the resources acquired by the Servlet at the initialization time. The
service () method is defined in the javax.servlet.Servlet interface .Hence if you
want your Servlet to perform any task then either your Servlet needs to implement
this javax.servlet.Servlet interface or extend a class implementing the
javax.servlet.Servlet interface and override the service () method. The easiest
Self-Instructional
190 Material
way is to extend a class that implements the javax.servlet.Servlet interface as this Java Servlets

will reduce the pain of implementing all the methods of the javax.servlet.Servlet
interface.
The service () method takes two parameters: a javax.servlet.ServletRequest
NOTES
and a javax.servlet.ServletResponse object. The service () method is invoked
once per request.The javax.servlet.ServletRequest object represents a client’s
request for the dynamic resources whereas the javax.servlet.ServletResponse object
represents the Servlet’s response to the requests sent by client. There are two
types of service method, one is public and other one is protected. The service ()
method has following implementation.
1. public void service(ServletRequest request,ServletResponse
response)
The purpose of this public method is to dispatch the request to the
protected service method by converting the request and response object
into HTTP type.
2. protected void service(Http ServletRequest request, Http
ServletResponse response)
This method receives the request from the public service() method. It
dispatches the request to the doXXX() method depending on the incoming http
request type.
The service () method has the following prototype:
Public void service (ServletRequest srq, ServletResponse
srp) throws ServletException
{
//Service code here…
}
(c) Destruction Phase
When a Servlet has serviced the client’s requests properly and is no longer needed
further, then the container removes the Servlet and all the resources are taken
away from the Servlet so that they could be used by other server dependents.
The server may decide to remove a previously loaded servlet instance,
perhaps because it is explicitly asked to do so by the server administrator, or
perhaps because the servlet is idle for a long time. Before it does, however, it calls
the servlet’s destroy method. This method gives your servlet a chance to close
database connections, halt background threads, write cookie lists or hit counts to
disk, and perform other such cleanup activities. Be aware, however, that it is
possible for the Web Destruction phase is marked by the destroy () method of the
Servlet interface which is called by the container for removing the Servlet whose
task has been completed and is not further required by the application. This method
is also just performed once, at last.
Self-Instructional
Material 191
Java Servlets The destroy () method has the following prototype:
Public void destroy ()
{
//Anything that you wish to be terminated/closed
NOTES
}
By proper use of the initialization, service, and destruction phases of the
Servlet life cycle, a Servlet can efficiently manage application resources. During
initialization a Servlet loads everything it needs to use for servicing requests. The
resources are then readily used during the service phase and can then be cleaned
up in the destruction phase. These three events form the Servlet life cycle, but in
practice there are some more methods which are needed by advanced programmers.
The unique feature to be noted here is that the initialization and the destruction
processes are performed only once whereas the service can be performed many
times as per client requests to the Servlet. Actually service () method is loaded
only once onto the server like init () and destroy () methods. But upon a new
request for the same Servlet every time after it has been loaded, a new service
thread is created which does the processing and returns the responses. This is the
feature in addition to the security feature which has helped Servlets outperform
the CGI applications and become the king of web applications.

Check Your Progress


1. What is a servlet container?
2. How will you access the Web content?

10.6 CODING A SERVLET

Every Servlet that is to be written must pertain to the J2EE specifications, and
must implement the javax.servlet.Servlet interface. Implementing this interface means
getting access to the life cycle methods of a Servlet and some methods for sharing
the resources. You need to override these methods for performing the task.
The Servlet interface consists of five basic methods:
1. public void init(ServletConfig config)
2. public void service(ServletRequest srq, ServletResponse srp)
3. public void destroy()
4. public ServletConfig getServletConfig()
5. public String getServletInfo()
You need to override the service () method only for making the servlet do
the task, and hence it is unnecessary to override all the other methods when you
Self-Instructional
192 Material
do not require anything extra to be done while implementing the Servlet interface Java Servlets

in your Servlet. To overcome this problem of unnecessary and unwanted overriding,


javax.servlet package consists of an abstract class, GenericServlet class which
implements all the methods except the service () method. You can write your
Servlets extending GenericServlet class, so that you just need to write the code NOTES
for the service () method only without considering for all other methods until required
seriously.
As Generic Servlet is protocol independent, in many occasions you may
need to code Servlets for specific protocols-like HTTP, then for that you need
additional packages and classes. For this, Servlet API has provided
javax.servlet.http package extending the base package - javax.servlet package.
Also, Http Servlet class which extends the GenericServlet class is given for the
use. You will see the details and implementations of these classes in the following
sections.
10.6.1 GenericServlet Class
As the name specifies, GenericServlet class is used when you do not require any
specific communication protocol like HTTP or other. GenericServlet class is an
abstract class, means it cannot be instantiated and you have to extend it if you wish
to use all its features. Extending the GenericServlet class in your Servlet will provide
the implementations of all the methods of the javax.servlet.Servlet interface except
one-the service () method. You need to override this method in your Servlet and
perform the specific task. Whatever task you want your Servlet to do, you need
to code it in the service () method essentially.
10.6.2 An Example of GenericServlet Class implementation
1. import javax.servlet.*;
2. import java.io.*;
3. public class GenericServletEx extends GenericServlet
4. {
5. public void service(ServletRequest req, ServletResponse resp) throws
ServletException, IOException
6. {
7. resp.setContentType(“text/plain”);
8. PrintWriter out = resp.getWriter();
9. out.println(“Congrats ! You have executed your first servlet.”);
10. }
11. }
Note: If you wish to run this servlet, you will have to follow the mechanism and
instructions as given in the coming section.
Self-Instructional
Material 193
Java Servlets 10.6.3 The Dissection
This section will witness the dissection of the program into lines with appropriate
explanation for the code given in the lines.
NOTES 1. Imports the javax.servlet package with all its methods and classes to be
used in the program.
2. Imports the input/output package for standard input and output .
3. Class GenericServletEx is declared extending the GenericServlet class,
means now only service () method is to be overridden in the program as
discussed earlier.
4. Parenthesis opened for writing the class body.
5. Implementation of the service () method which takes two parameters
ServletRequest and ServletResponse objects for taking requests and sending
the responses respectively. As, during the servicing there may occur errors
and exceptions, these are handled by throwing the subsequent exceptions
in the service () method.
6. Parenthesis opened for the service () method body.
7. Setting the content type, the MIME type for response generation using the
response object.
8. Getting the writer for output stream.
9. Displaying or transmitting the result as response/output.
10. Parenthesis closed for the service () method body.
11. Parenthesis closed for the class definition.
10.6.4 Output
On successful execution of the servlet code, you will get the following message on
the browser.
“Congrats! You have executed your first servlet.”
Activity: Try to display the following message on the browser as “Now you
are well versed in executing Servlets.”
Note: If you wish to run this Servlet, you will have to follow the mechanism
and instructions given in the coming sections 2.9. Output is left as activity to you
students

10.7 HTTP SERVLET CLASS

If you are to work with the Web, you need to work with the protocol it uses-the
HTTP and its method-Get, POST etc. GenericServlet is independent to any
protocol, hence has a limitation that you should override the service () method
Self-Instructional
194 Material
only, irrespective of the methods used in the communication-the GET and the Java Servlets

POST methods. Though this is a benefit that you do not have to worry about the
communication protocol but on the other hand it is resource exploitation as the
methods of HTTP have different data load and characteristics.
NOTES
This is overcome in Java Servlets by the extension of the base package
javax.servlet to javax.servlet. http, with add on capabilities of handling the HTTP
protocol and all its methods. Also, Http Servlet class is devised which extends the
GenericServlet Class that comprises of methods for handling the HTTP protocol
specific data. Http Servlet is a subclass of GenericServlet class with add-on features
to support the web protocol HTTP. It is also abstract class. Http Servlet class
provides support to the methods of HTTP also, providing a number of helper
methods like doGet(), doPost(),doTrace(),doPut() etc. These methods can easily
handle the specific types of HTTP requests-be it GET, POST, PUT or Delete.
The execution of these methods is controlled by the service () method. The service
() method tracks the kind of request made by the client and invokes the
corresponding method to perform the task. Though there are total of seven such
helper methods, only one of them is invoked according to the request specification
by the server. There may be a scenario when you may need to call more than one
in your servlet, then you need to override them such that they call each other.
10.7.1 Methods of Http Servlet Class
GenericServlet is too generic to be used with the basic methods only. Hence, the
Http Servlet class is the main class that you will see being used in the chapter as it
provides everything that is needed to create good servlets with maximum capabilities.
As Http Servlet class extends GenericServlet, it comprises of the basic
servlet lifecycle methods plus some additional helper methods specific to HTTP
protocol and Servlet configurations.

Fig.10.14 Http Servlet Skeleton

Self-Instructional
Material 195
Java Servlets 1. Servlet Lifecycle Methods
i) init()-This is the initialization method that is called once ,when the servlet
first loads onto the server .This method provides the essential resources
NOTES needed by the servlet.
ii) destroy()-This method is also called once by the servlet container to de-
allocate the resources used by servlet during its execution, after its work is
completed.
iii) service()-You will never override this method while using the Http Servlet
class as there are other methods equivalent to this with specific functionalities
which has been discussed in the next section. Service () method gets
differentiated into various sub methods according to the HTTP requests,
they are doXXX() methods where XXX represent the HTTP request
methods. There are two types of service method, one is public and other
one is protected. The service () method has following implementation.

Fig.10.15 Service() method handling the dispatch methods doGet() & doPost()

1. public void service(ServletRequest request,ServletResponse


response)
The purpose of this public method is to dispatch the request to the
protected service method by converting the request and response object
into HTTP type.
2. protected void service(Http ServletRequest request, Http
ServletResponse response)
This method receives the request from the public service() method. It
dispatches the request to the doXXX() method depending on the
incoming http request type.
2. Methods specific to HTTP requests (doXXX() dispatch methods)
1. protected void doGet(Http ServletRequest request, Http
ServletResponse response)
It handles the GET request. It is invoked by the web container.

Self-Instructional
196 Material
2. protected void doPost(Http ServletRequest request, Http Java Servlets

ServletResponse response)
Similar to doGet() method, it also gets invoked by the web container and it
handles the POST request.
NOTES
3. protected void doHead(Http ServletRequest request, Http
ServletResponse response)
It handles the HEAD request.
4. protected void doOptions(Http ServletRequest request, Http
ServletResponse response)
Performs the HTTP OPTIONS operation; the default implementation of
this method automatically determines what HTTP Options are supported.
5. protected void doPut(Http ServletRequest request, Http ServletResponse
response)
Performs the HTTP PUT operation; the default implementation reports an
HTTP BAD_REQUEST error.
6. protected void doTrace (Http ServletRequest request, Http
ServletResponse response)
Performs the HTTP TRACE operation; the default implementation of this
method causes a response with a message containing all of the headers sent
in the trace request.
7. protected void doDelete(Http ServletRequest request, Http
ServletResponse response):
Performs the HTTP DELETE operation; the default implementation reports
an HTTP BAD_REQUEST error.
3. Method related to Servlet Configuration

a) protected long getLastModified(Http ServletRequest request):


This method helps gets the modified time of the requested entity. By default it will
return a negative number, indicating that the modification time is unknown and
hence should not be used for conditional GET operations or for other cache control
operations as this implementation will always return the contents.
10.7.2 An Example of Http Servlet Class implementation
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class Http ServletEx extends Http Servlet {
5. public void doGet(Http ServletRequest req, Http ServletResponse resp)
throws ServletException, IOException Self-Instructional
Material 197
Java Servlets 6. {
7. resp.setContentType(“text/html”);
8. PrintWriter out = resp.getWriter();
NOTES 9. out.println(“<HTML>”);
10. out.println(“<HEAD><TITLE>Http Servlets are extensions of the
GenericServlet Class.</TITLE></HEAD>”);
11. out.println(“<BODY><H1>Amazed!</H1><H6>Again.</H6></
BODY></HTML>”);
12. }}
Note: If you wish to run this Servlet, you will have to follow the mechanism and
instructions given in the coming section 4.9. Output is left as activity to you students.
10.7.3 The Dissection
1. Imports the javax.servlet package with all its methods and classes to be
used in the program.
2. Imports the javax.servlet.http package with all its supported methods and
classes that may be used in the program.
3. Imports the input/output package for standard input and output.
4. Class Http ServletEx is declared which extends the Http Servlet class, means
now only doGet() or doPost() method is to be overridden in the program
as discussed earlier and not the service method()as before[why?].
Parenthesis opened for writing the class body.
5. Implementation of the doGet() method which takes two parameters Http
ServletRequest and Http ServletResponse objects for taking requests and
sending the responses respectively. As, during the servicing there may occur
errors and exceptions, these are handled by throwing the subsequent
exceptions in the service () method.
6. Parenthesis opened for the service () method body.
7. Setting the content type, the MIME type for response generation using the
response object.
8. Getting the writer for output stream.
9. Displaying or transmitting the result as response/output encoded in HTML.
10. Displaying or transmitting the result as response/output.
11. Displaying or transmitting the result as response/output.
12. Parenthesis closed for the class definition.
You have now learned about the different methods of creating Servlets. It
will be upon you to decide how you want to create Servlets-by implementing the
Servlet interface, extending the GenericServlet Class or extending the Http Servlet
Self-Instructional Class. All have their own advantages and shortcomings by the point of view of a
198 Material
developer. As learning the functionalities of the Servlet is the main aim, in this Java Servlets

book, you will find the use of Http Servlet Class the most as it provides greater
functionality and implementations than the others.
There are many other advanced but essential interfaces and classes that you
NOTES
need to be going through in the servlets. But to understand their mechanics, you
need to first understand the technique of running a servlet successfully. Once you
have run a servlet properly, it will be easier for you to get on with some advanced
concepts like servlet collaborations, servlet context and configurations.

10.8 THE FIRST RUN

Well, you have now learned the basics of the servlet, but there are a few things still
left before you have the first run of your servlet. These are the key things that you
should learn before running any Servlet.
They are as follows:
1. The Directory Structure Of The Web Application
2. The Deployment Descriptor(web.xml)
3. Servlet Code Compilation(Getting the .class file)
1. The Directory Structure Of The Web Application
Whatever structure a web application displays on the browser, on disk, it is merely
a directory with various sub directories that help get the online structure. The
parent directory contains a subdirectory called WEB-INF, and whatever other
content is required for the application like HTML pages and other static resources.
The WEB-INF directory contains a classes directory (containing application
code), a lib directory (containing application JAR files), and a deployment descriptor
called web.xml. It can be shown in diagram as follows:

Fig. 10.16 Directory Structure


Self-Instructional
Material 199
Java Servlets

NOTES

Fig. 10.17 A simplest web application directory structure

2. The Deployment Descriptor(web.xml)


A Servlet is invoked by the server, so the server should know what servlet
looks like and what does it require. It means there should be an interface between
the server and the Servlet which specifies various configuration parameters,
description of the servlet, the servlet path etc to the server so that server can
provide the environment to the servlet as per the specification. This communication
interface is created using an XML file, the web.xml. The web.xml file contains all
of the configuration information for the servlets within the context, including names,
path mappings and initialization parameters and context-level configuration
information.
The web.xml is also known as deployment descriptor, which stores the key
information regarding configuration and deployment of the Servlet. Without this
file, you cannot run your Servlet. Even a single mistake in your web.xml file can
make your project fail.
As web.xml is an XML file and XML files are known for their structural
element arrangement according to the child parent relationship.
web.xml has the general structure:
<?xml version=”1.0" encoding=”ISO-8859-1"?>
<web-app >
<servlet>
<servlet-name>Manager</servlet-name>
<servlet-class>ManagerServlet</servlet-class>

Self-Instructional
200 Material
</servlet> Java Servlets
<servlet-mapping>
<servlet-name>Manager</servlet-name>
<url-pattern>/mgt</url-pattern>
NOTES
</servlet-mapping>
</web-app>
3. Servlet Code Compilation(Getting the .class file)
Servlets are java classes, and they too need to be compiled before they are executed
by JVM just like simple java programs. The process of compiling a java servlet is
similar to that of an ordinary java program i.e. using the default “javac” utility at the
command prompt. Only thing to consider is setting the path to servlet-api.jar,
which consists of the complete specification for java Servlet. The easiest way is to
copy servlet-api.jar from the tomcat lib folder to Java program folder, or set the
environment variable class path to the jar archive.
Now, you are ready to get started with your first Servlet. Let’s kick start
writing Servlets and develop new web applications.

10.9 FIRST WEB APPLICATION USING SERVLET

The step wise mechanism of creating a web application for your use and
understanding is given below:
Algorithm:
Step1: Create a directory structure of the web application.
Step2: Write a Servlet code. Save it with .java extension.
Step3: Compile the Servlet to obtain the .class file. Place this .class file into
the classes folder in the WEB-INF (web descriptor) folder of the
application.
Step4: Create the deployment descriptor i.e. web.xml file according to the
servlets. Place this XML file in the WEB-INF folder of the application.
Step5: Start the Tomcat Server.
Step6: Deploy the application on the web server by placing the public folder
into the C:\Program Files\Apache Software Foundation\Tomcat
7.0\webapps folder.
Step7: Test the application by giving the relative URL on the browser.
For example : localhost:8888/Servlet1/fts1
Now you will see the execution of a servlet according to the steps mentioned
above.

Self-Instructional
Material 201
Java Servlets Implementation
Step1: Create the directory structure of the web application as discussed in
the previous section.
NOTES Step2: Write the Servlet file, FirstTestServlet.java.
FirstTestServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstTestServlet extends Http Servlet {
public void doGet(Http ServletRequest request, Http
ServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println(“If You are viewing me on the browser,means
your servlet has successfully deployed and
executed.Congratsss!”);
}
}
Step3: Compile the Servlet to obtain the .class file. Place this .class file into
the classes folder in the WEB-INF (web descriptor) folder of the
application.
Step4: Create the deployment descriptor i.e. web.xml file according to the
servlets. Place this XML file in the WEB-INF folder of the application.
web.xml
<?xml version=”1.0" encoding=”ISO-8859-1"?>
<web-app >
<servlet>
<servlet-name>FTS</servlet-name>
<servlet-class>FirstTestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FTS</servlet-name>
<url-pattern>/fts1</url-pattern>
</servlet-mapping>
</web-app>
Step5 Start the tomcat server as directed in the previous sections.
Step6: Deploy the application on the web server.

Self-Instructional
202 Material
Deployment can be defined as the process of loading the application files Java Servlets

on to the server, so that the server can provide an execution environment to them
and the web application expose out all its features. There are two ways of deploying
the web application and its files on to the server, viz.1.Hot Deployment and 2.Cold
Deployment. NOTES

Output:

Fig. 10.18 Output file

You must have now successfully deployed and executed your first Servlet
only application. You can create a complete web application using servlets only; it
will be a monotonous application. And you also know that a web application
consists of varieties of web pages – some in HTML, some as Servlets which may
interact with each other for the proper functioning of the web application. So, an
interactive web application will make a judicious use of servlets, HTML pages,
etc. The presentation will be completely dependent on HTML and the business
logic will depend upon the servlet used in such web applications. You will witness
the simplest of the web application developed using HTML page and a servlet in
the coming section.

10.10 A WEB APPLICATION BASED ON HTML WEB


PAGE AND SERVLET

A simple step wise implementation for your use and understanding is given below:
Algorithm:
Step1: Create a directory structure of the web application.
Step2: Write an HTML web page .Save it with .htm or .html extensions.
Place this HTML page into the parent directory parallel to WEB-INF
folder.
Step3: Write a Servlet code. Save it with .java extension.
Step4: Compile the Servlet to obtain the .class file. Place this .class file into
the classes folder in the WEB-INF (web descriptor) folder of the
application.
Step5: Create the deployment descriptor i.e. web.xml file according to the
servlets. Place this XML file in the WEB-INF folder of the application.
Step6: Deploy the application on the web server.
Self-Instructional
Material 203
Java Servlets Now you will see the execution of a servlet according to the steps mentioned
above. Check that the HTML page is properly saved along with the XML file.
Now you will see the execution of a servlet according to the steps mentioned
above.
NOTES
Implementation

Index.html
<HTML><BODY>
<A HREF=”hbs”>Click Here! < /A>
</BODY>
</HTML>
Place this file in the parent folder, keeping it parallel to the WEB-INF folder.
Note: A folder which has WEB-INF folder in it is considered as the public folder
for the web application.
HtmlBasedServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HtmlBasedServlet extends Http Servlet {
public void doGet(Http ServletRequest request, Http
ServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println(“<HTML><HEAD><TITLE>”);
out.println(“SERVLET WITH HTML OUTPUT”);
out.println(“</TITLE></HEAD><BODY BGCOLOR=RED>”);
out.println(“If You are viewing me on the browser,
means your servlet has successfully deployed and
executed. Congratsss!”);
out.println(“</BODY></HTML>”);
}
Save, compile and place the .class file in the classes folder in the WEB-INF
directory.
web.xml
<?xml version=”1.0" encoding=”ISO-8859-1"?>
<web-app >
<servlet>
<servlet-name>HBS</servlet-name>
Self-Instructional
204 Material
<servlet-class>HtmlBasedServlet</servlet-class> Java Servlets
</servlet>
<servlet-mapping>
<servlet-name>HBS</servlet-name>
NOTES
<url-pattern>/hbs</url-pattern>
</servlet-mapping>
</web-app>
Save and place the web.xml file inside the WEB-INF folder in the parent
folder. Now your application is ready for the deployment. You can use either of
the deployment methods-Hot Deployment or Cold Deployment. Deploy and
execute on the web browser and enjoy!
These Servlets are static Servlets as these will be displaying plain texts or
HTML output only, but you want more, interactive applications, one which will
take input from the user and do the task accordingly. These will be considered as
the dynamic servlets. You will see the dynamic servlets in action in the coming
section.

10.11 A WEB APPLICATION HANDLING USER


INPUTS VIA FORMS USING SERVLETS

Interactivity on the web can only be felt when the web application is getting input
from the user and the web application is performing the specified task. To achieve
this there are various mechanisms, as you are a learner now, a small form based
web application will be discussed so that you get the insight and create your own
application learning this. The steps will be the same as followed in the previous
sections 10.9 and 10.10.
This is the extension of the web application you have just created in the
previous section using HTML web page.
Implementation

FormGenerator.html
<HTML>
<HEAD>
<TITLE>FormGenerator</TITLE>
</HEAD>
<BODY BGCOLOR=”#5D35E6">
<H1 ALIGN=”CENTER”>Collecting Three Parameters</H1>
<FORM ACTION=”FormHandler”>
Name: <INPUT TYPE=”TEXT” NAME=”parameter1"><BR>
Class: <INPUT TYPE=”TEXT” NAME=”parameter2"><BR>
Self-Instructional
Material 205
Java Servlets RollNo: <INPUT TYPE=”TEXT” NAME=”parameter3"><BR>
<CENTER><INPUT TYPE=”SUBMIT”></CENTER>
</FORM>
</BODY>
NOTES
</HTML>
FormHandlingServlet.java
// Servlet that reads form data and displays in HTMl
text format.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FormHandlingServletEx extends Http Servlet
{
public void doGet(Http ServletRequest request, Http
ServletResponse response)
throws ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
out.println(“<BODY BGCOLOR=\”#F6E5E6\”>\n” +
“<H1 ALIGN=\”CENTER\”>” + title + “</H1>\n” +
“<UL>\n” +
“ <LI><B>Name: </B>: “+
request.getParameter(“parameter1”) + “\n” +
“ <LI><B>Class:</B>: “+
request.getParameter(“parameter2”) + “\n” +
“ <LI><B>RollNo.:</B>: “+
request.getParameter(“parameter3”) + “\n” +
“</UL>\n” +”</BODY></HTML>”);}
}
web.xml
<?xml version=”1.0" encoding=”ISO-8859-1"?>
<web-app >
<servlet>
<servlet-name>FHSE</servlet-name>
<servlet-class> FormHandlingServletEx</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>FHSE</servlet-name>

Self-Instructional
206 Material
<url-pattern>/FormHandler</url-pattern> Java Servlets
</servlet-mapping>
</web-app>

NOTES
Check Your Progress
3. What is a Servlet invoked by?
4. What is a Http Servlet?

10.12 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. A servlet container is the application software that is used to run servlets.


2. The Web content is basically accessed via the HyperText Transfer Protocol
(HTTP).
3. A Servlet is invoked by the server.
4. Http Servlet is a subclass of GenericServlet class with add-on features to
support the web protocol HTTP.

10.13 SUMMARY

 Java has become an undoubtedly the best language for server side
programming due to Java Servlets.
 Java Servlets have always stood as a top performer in providing an efficient
and powerful solution for creating dynamic content for the Web.
 The Java platform provides a Servlet developer with robust APIs, object-
orientated programming methodology, platform independence, I18N
(Internationalization), strict types, garbage collection and above all, the
security features of the Java Virtual Machine (JVM).
 Servlets are java programs, with an inbuilt support to HTTP for getting
requests and sending responses.
 A web.xml file is created for a Servlet which has the configuration details of
the servlet that the server uses for its execution.
 Servlets do not have a main () method like their counterparts in core Java-
the applets or any simple Java program.
 A servlet container is the application software that is used to run servlets.
 Tomcat is a basic server, it can be used for general testing and debugging
the Servlets.

Self-Instructional
Material 207
Java Servlets  If you want to run servlet programs on your computer, you have to install a
special program called a servlet engine to convert your computer into a
server which is capable of running the Servlets.
 Java Servlets can be defined as some platform independent, robust server
NOTES
side programs coded in Java.
 The power of Java Servlets comes from the Java Servlet API which is a
standard interface between web server and web clients.
 The Java Servlet API is a set of Java classes, interfaces and methods which
defines a standard interface between a client and a web server.
 This javax.servlet package consists of the classes and interfaces that support
generic protocol independent Servlets.
 Every Servlet has to extend this abstract class as this class implements all
the methods of the Servlet interface except the service () method.
 The Web content is basically accessed via the HyperText Transfer Protocol
(HTTP).
 Every Servlet that is to be written must pertain to the J2EE specifications,
and must implement the javax.servlet.Servlet interface.
 You need to override the service () method only for making the servlet do
the task.
 As Generic Servlet is protocol independent, in many occasions you may
need to code Servlets for specific protocols-like HTTP, then for that you
need additional packages and classes.
 Http Servlet is a subclass of GenericServlet class with add-on features to
support the web protocol HTTP.
 GenericServlet is too generic to be used with the basic methods only. Hence,
the Http Servlet class is the main class that you will see being used in the
chapter as it provides everything that is needed to create good servlets with
maximum capabilities.
 A Servlet is invoked by the server, so the server should know what servlet
looks like and what does it require.

10.14 KEY WORDS

 init(): This is the initialization method that is called once ,when the servlet
first loads onto the server .This method provides the essential resources
needed by the servlet.
 destroy(): This method is also called once by the servlet container to de-
allocate the resources used by servlet during its execution, after its work is
completed.
Self-Instructional
208 Material
Java Servlets
10.15 SELF ASSESSMENT QUESTIONS AND
EXERCISES

Short-Answer Question NOTES

1. Define what are Servlets and also state their use.


2. Differentiate between Servlets and CGI.
3. Discuss about the latest Servlet Specification.
Long-Answer Questions
1. What do you understand by the Servlet life cycle? How does a container
manage a Servlet?
2. Write to code the Servlets according to the need of reading initialization
parameters, and reading servlet parameters.
3. Discuss the Session management using Servlets.
4. Conceptualize the methods of debugging the Servlets.

10.16 FURTHER READINGS

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
Material 209
Servlet Parameters

UNIT 11 SERVLET PARAMETERS


NOTES Structure
11.0 Introduction
11.1 Objectives
11.2 Understanding the Servlet Requests and Servlet Responses Mechanism
11.3 Servlet Responses
11.4 HttpServletResponse Interface
11.5 Servlets Interactions
11.6 Answers to Check Your Progress Questions
11.7 Summary
11.8 Key Words
11.9 Self Assessment Questions and Exercises
11.10 Further Readings

11.0 INTRODUCTION

Java Servlet, as the name suggests is a Java technology under J2EE flavor of Java
that has changed the web scenario completely, especially with its security and
multithreading capabilities. Servlets outperformed and replaced CGI, the first server
side technology to provide dynamic capabilities to the web and became the world
leader in Sever Side Programming. Servlets are really very powerful. They also
form the basis for the Java Server Pages (JSP), the web scripting language that is
popularly used in web programming. Behind every JSP that executes is a servlet
always. You will see varieties of implementations of servlets as you proceed with
the chapter and understand the underlying concepts as well. In this unit you will
learn about reading initialization, parameters, and reading servlet parameters.

11.1 OBJECTIVES

After going through this unit, you will be able to:


 Understand servlet responses
 Discuss some useful methods of ServletRequest interface
 Analyse HttpServletResponse interface
 Explain servlet interactions
 Discuss the methods of ServletConfig
 Discuss about ServletContext

Self-Instructional
210 Material
Servlet Parameters
11.2 UNDERSTANDING THE SERVLET REQUESTS
AND SERVLET RESPONSES MECHANISM

Working with any client–server technology is to carefully deal with the requests NOTES
and responses, the prime mechanism of interaction between the two. Request and
responses are used Request and responses are used for communication between
the client and the server it interacts with. A client application shoots the requests as
received from the user interface to the server using some protocols for
accomplishing some task. The server takes up the request and then after processing
the request, it reverts back with appropriate response to the client application.
Similar paradigm is used in Servlets as well. This section will help you understand
the requests and responses as you may need to deal with in your Servlets.
Servlet Requests
For processing a request, a Servlet requires some specific information like
configuration and context information about the request so as to process it properly.
The Servlet API has provided two interfaces-
1. ServletRequest interface
2. HttpServletRequest interface
Both of these interfaces are of great help while devising servlets and provide
the server access to the information as needed for processing. When a Servlet is
asked to handle a request, the server passes it a request object that implements
one of these interfaces. With this object, the servlet can distinguish between the
actual request (e.g., protocol, URL, type), access parts of the raw request (e.g.,
headers, input stream), and get any client-specific request parameters (e.g., form
variables, extra path information).
If you are creating servlets implementing the Servlet Interface ,then do not
forget to consider ServletRequest Interface for creating the request object. Or
else if you are using the HttpServlet, then use HttpServletRequest for the accessing
the request object.
ServletRequest Interface
ServletRequest Interface defines an object that takes the client request information
to a Servlet. The Servlet container creates a ServletRequest object and passes it
as an argument to the Servlet’s service method.
Information delegated by the ServletRequest object includes data including
parameter name and values, attributes, and an input stream. Interfaces that extend
ServletRequest can provide additional protocol-specific data (for example, HTTP
data is provided by HttpServletRequest).

Self-Instructional
Material 211
Servlet Parameters Table 11.1 shows some useful methods of ServletRequest interface.
Table 11.1 Useful Methods of ServletRequest Interface

Methods Description
NOTES Object getAttribute(String name) Return attribute set on request object by name
Enumeration getAttributeName() Return an Enumeration containing the names of the
attributes available in this request
int getContentLength() Return size of request body
int getContentType() Return media type of request content
ServletInputStream Returns a input stream for reading binary data
getInputStream()
String getParameter(String name) Returns value of parameter by name
String getLocalAddr() Returns the Internet Protocol(IP) address of the
interface on which the request was received
Enumeration getParameterNames() Returns an enumeration of all parameter names
String[] getParameterValues(String Returns an array of String objects containing all of
name) the values the given request parameter has, or null if
the parameter does not exist
ServletContext getServletContext() Return the servlet context of current request.
String getServerName() Returns the host name of the server to which the
request was sent
int getServerPort() Returns the port number to which the request was
sent
boolean isSecure() Returns a boolean indicating whether this request
was made using a secure channel, such as HTTPS.
void removeAttribute(String name) Removes an attribute from this request
void setAttribute(String name, Stores an attribute in this request
Object o)

HttpServletRequest Interface
This interface extends the ServletRequest interface and provides request information
for HTTP.So, it extends an old legacy apart from some new special methods
handling HTTP-specific request data apart from the existing ServletRequest
interface.. The Servlet container creates an HttpServletRequest object and passes
it as an argument to the Servlet’s service methods (doGet, doPost, etc). For
example, the getHeaderNames() returns an enumeration of the names of all the
HTTP headers submitted with a request, while getHeader() returns a particular
header value.

Fig.11.1 Relation between ServletRequest and HttpServletRequest Interfaces


Self-Instructional
212 Material
Table 11.2 Important methods of HttpServletRequest Servlet Parameters

Methods Description
String returns the portion of the request URI that indicates the
getContextPath() context of the request
Cookies getCookies() returns an array containing all of the Cookie objects the NOTES
client sent with this request
String returns the query string that is contained in the request
getQueryString() URL after the path
HttpSession returns the current HttpSession associated with this
getSession() request or, if there is no current session and create is
true, returns a new session
String getMethod() Returns the name of the HTTP method with which this
request was made, for example, GET, POST, or PUT.
Part getPart(String gets the Part with the given name
name)
String getPathInfo() returns any extra path information associated with the
URL the client sent when it made this request.
String getServletPath() returns the part of this request's URL that calls the
servlet

HttpServletRequest Interface Implementation


In this implementation of the HttpServletRequest Interface you will see how a
parameter is passed to a servlet in a request object from HTML page.
index.html
<html>
<head><title>HttpServletRequestExample</title></head>
<body bgcolor=”green”>

<form method=”post” action=”paramcheck”>


Name <input type=”text” name=”user” >
<input type=”submit” value=”submit”>
</form>
</body>
</html>
web.xml
<?xml version=”1.0" encoding=”ISO-8859-1"?>
<web-app >
<servlet>
<servlet-name>ServletEx</servlet-name>
<servlet-class>HttpServletRequestEx</servlet-class>
</servlet>
<servlet-mapping>

Self-Instructional
Material 213
Servlet Parameters <servlet-name>ServletEx</servlet-name>
<url-pattern>/paramcheck</url-pattern>
</servlet-mapping>
</web-app>
NOTES
HttpServletRequestEx.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HttpServletRequestEx extends HttpServlet


{
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
try {
String user=request.getParameter(“user”);
out.println(“<h2> Welcome “+user+”</h2>”);
} finally {
out.close();
}
}
}

11.3 SERVLET RESPONSES

For every request that comes to the server, the servlet has to send back
some response as a token of processing the request successfully. Responses can
be one liner, like a status code simply, or a description that includes all the three-
a status code, any number of HTTP headers, and a response body as in the HTTP
For Servlet responses, Java Servlet API has provided two basic interfaces
that can be used to create and manipulate a Servlet’s output.
They are:
1. ServletResponse Interface
2. HttpServletResponse interface
ServletResponse Interface
This interface defines an object to help a Servlet in sending a response to the
client. The servlet container creates a ServletResponse object and passes it as an
Self-Instructional argument to the Servlet’s service method.
214 Material
If you wish to send binary data in a MIME body response, you need to use Servlet Parameters

the ServletOutputStream returned by getOutputStream(). And to send character


data, you are required to use the PrintWriter object returned by getWriter().But if
you want to mix binary and text data, for example, to create a multipart response,
then you must use a ServletOutputStream and manage the character sections NOTES
manually.
The charset for the MIME body response can be specified explicitly using
the setCharacterEncoding(java.lang.String) and setContentType(java.lang.String)
methods, or you can also use thesetLocale (java.util.Locale). Whatever be the
specifications, always remember the explicit specifications take precedence over
implicit specifications. If no charset is specified, ISO-8859-1 will be used. The
setCharacterEncoding(),setContentType() etc. methods must be called before
getWriter() is called and before committing the response for the character encoding
to be used.
Some Basic Methods of ServletResponse Interface

Table 11.3 Basic Methods of ServletResponse Interface

Methods Description
PrintWriter getWriter() Returns a PrintWriter object that can send
character text to the client.
void setBufferSize(int size) Sets the preferred buffer size for the body of the
response
void setContentLength(int len) Sets the length of the content body in the
response In HTTP servlets, this method sets the
HTTP Content-Length header
void setContentType(String type) Sets the content type of the response being sent
to the client before sending the respond.
void setBufferSize(int size) Sets the preferred buffer size for the body of the
response.
boolean isCommitted() Returns a boolean indicating if the response has
been committed
void setLocale(Locale loc) Sets the locale of the response, if the response
has not been committed yet.

11.4 HTTPSERVLETRESPONSE INTERFACE

This interface extends the ServletResponse interface to provide HTTP-specific


functionality in sending a response. The servlet container creates an
HttpServletResponse object and passes it as an argument to the servlet’s service
methods (doGet, doPost, etc).
HttpServletResponse interface also houses a number of methods for handling
HTTP responses. Many of these allow you to manipulate the HTTP header fields
like setHeader(), setIntHeader(), and setDateHeader().These methods help you
to set the value of a specified HTTP header, while containsHeader() checks if a

Self-Instructional
Material 215
Servlet Parameters certain header has already been set. setStatus() or sendError() methods can be
used to specify the status code sent back to the server.
HttpServletResponse interface also defines a list of integer constants that
represent specific status codes. Don’t worry about setting a status code, as the
NOTES
default code is 200 (“OK”), meaning that the servlet sent a normal response.
Table 11.4 Methods of HttpServletResponse Interface

Methods Description
void addCookie(Cookie cookie) adds the specified cookie to the response.
void sendRedirect(String location) Sends a temporary redirect response to the
client using the specified redirect location
URL and clears the buffer

int getStatus() gets the current status code of this response


String getHeader(String name) gets the value of the response header with
the given name.

void setHeader(String name, String value) sets a response header with the given name
and value

void setStatus(int sc) sets the status code for this response
void sendError(int sc, String msg) sends an error response to the client using
the specified status and clears the buffer

11.5 SERVLETS INTERACTIONS

“What can a single servlet do?” Just a specific task will be the answer. But in the
real world, single servlets have no use at all. What you really need is the grouping
together of various servlets to form an application which may consist of servlets,
shared objects, and other resource files, such as HTML and JSPs. And this is only
possible when these servlets interact with each other; communicate with each
other in a certain context by sharing their resources at application level.
There are various scenarios that discuss the implementation of the servlet
interactions, they are as follows:
1. Servlet collaboration: Combining two or more servlets such that either
they delegate the responses or collaborate to produce a common
response is called Servlet Collaboration. The two techniques for servlet
collaboration are servlet filtering and chaining. Here, multiple Servlets
collaborate for producing a single response for a client. The Servlets
themselves are not really interacting directly with each other; rather, the
web application server is responsible for binding the servlets together.

Self-Instructional
216 Material
2. Calling servlets from servlets: Since servlets are Java programs, Servlet Parameters

they can do anything a standard Java program can do, such as make a
network connection. In this way, we have implicit servlet interaction.
Additionally, because a servlet is just a Java class, we can instantiate
and call a servlet’s public methods. NOTES
3. Response redirection: We can redirect the servlet response to another
application resource, such as another servlet or an error page (HTML
or JSP).
4. Request dispatching: Through the RequestDispatcher object, we can
forward a request to another servlet, which can handle the request and
return the response. Additionally, we can include directly another servlet’s
response within the context of a calling servlet. We can use request
dispatching to dispatch the handling to another active application
resource.
5. Resource usage: We can interact with an application’s resources
through the servlet context. The ServletContext object allows us access
to these resources through the getResource() method.
6. Sharing of objects in scope: There are three levels of object scope
for a servlet. Application scope is between all servlets in the same
application, and is accessed through the ServletContext object. User
session objects are accessed through the HttpSession object, and request
level objects through the servlet request.
As you are getting into the basics of Servlet, you will just require some basic
servlet interactions like sharing of resources, response redirection, and request
dispatching.
Sharing of Resources
It is easy to create a servlet which displays information. You have done it.
Sometimes, you may be asked to share the common resources of a server among
all the servlets. Then to achieve this ,you will have to get help of the following
interfaces:
(a) ServletConfig Interface
(b) ServletContext Interface
ServletConfig
The javax.servlet.ServletConfig interface provides a support to pass information
to a servlet during initialization by getting configuration information from web.xml
(Deployment Descriptor). A servlet configuration object is used by a servlet container
to pass the information to a servlet during initialization.
This ServletConfig object is created when the web container first initializes
the Servlet. There exists only one ServletConfig object per servlet. Essentially, it is
Self-Instructional
Material 217
Servlet Parameters used to pass the deploy time information to the servlet that you do not want to
hardcode into the servlet.
Methods of ServletConfig
NOTES  String getInitParameter(String name)
This method returns a String value initialized parameter, or NULL if the
parameter does not exist.
 Enumeration getInitParameterNames():
This method returns the names of the servlet’s initialization parameters as
an Enumeration of String objects, or an empty Enumeration if the servlet
has no initialization parameters.
 ServletContext getServletContext()
This method returns a reference to the ServletContext
 String getServletName()
This method returns the name of the servlet instance.
Whenever an explicit initialization parameter is to be used in the Servlet ,it
needs to be provided in the web.xml file in the sub element of Servlet <init-
param>…</init-param> inside the web application. You can see the implementation
in the example below which illustrates an example on using ServletConfig Interface
to get the parameters from the web.xml.
Example 11.1:
// Servlet Config program to get a parameter from the
web.xml.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ConfigServletEx extends HttpServlet {
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();  
String driver=config.getInitParameter(“driver”);
out.print(“Driver is: ”+driver);
out.close(); } }
web.xml
<web-app>
<servlet>
<servlet-name>CSE</servlet-name>
<servlet-class> ConfigServletEx </servlet-class>
Self-Instructional <init-param>
218 Material
<param-name>driver</param-name> Servlet Parameters
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-
value>
</init-param>
</servlet> NOTES
<servlet-mapping>
<servlet-name> ConfigServletEx </servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>

Fig. 11.2 ServletConfig & SevletContext

ServletContext
The javax.servlet.ServletContext interface primarily provides the reference to the
web application in which the servlets execute. It allows servlets to access server
information, and there exists only one ServletContext for each web application on
the server. Through the ServletContext interface, a Servlet can access any raw
input streams to web application resources, a way to virtual directory translation
(a common mechanism for logging information) and an application scope for binding
objects. The container vendors may provide different implementations of
ServletContext objects, but with the same functionality as defined by the
ServletContext interface.
ServletContext interface basically works as the communication interface
for the servlets of a web application .It works like a bulletin board for all the
servlets of a web application and differs with every web application. A
ServletContext object gets created as soon as the web application is deployed
onto the server with everything that is common to all within the application context.
Self-Instructional
Material 219
Servlet Parameters Just similar to ServletConfig, all the parameters of this ServletContext are set
once in the deployment descriptor.
You need to use this interface and its methods, if you wish to share the
common resources with all the servlets of a web application.
NOTES
Using ServletContext, servlets can be:
 Used to provide communication between Servlets
 Used to get access to configuration information like initialization
parameters from web.xml.
 Used for sharing attributes with other servlets in the context(within the
context of web application)
 Used to get configuration information from web.xml
Important Methods of ServletContext Interface

Table 11.5 Methods Of ServletContext Interface

Methods Description
Object getAttribute(String name) Rreturns the container attribute with
the given name, or NULL if there is
no attribute by that name.
String getInitParameter(String name) Returns parameter value for the
specified parameter name, or NULL
if the parameter does not exist
Enumeration getInitParameterNames() Returns the names of the context's
initialization parameters as an
Enumeration of String objects
void setAttribute(String name,Object obj) Set an object with the given attribute
name in the application scope
void removeAttribute(String name) Removes the attribute with the
specified name from the application
context

Response Redirection
Response redirection, also referred to as URL redirection, means calling a servlet
from another servlet and transferring the entire response to it. This is also. A very
handy technique if you wish to redirect your clients to your application which has
been relocated or shifted from its address to a new location onto the web. Also, it
can help you to provide your client content from an old location without any overhead
and any additional effort. Servlet API has provided the sendRedirect() method to
serve this purpose.

Self-Instructional
220 Material
Servlet Parameters

NOTES

Fig. 11.3 Illustrating sendRedirect() Method

sendRedirect() Method
sendRedirect() method redirects the response to another resource. This method
actually makes the client (browser) to create a new request to get to the resource.
The client can see the new url in the browser. sendRedirect() accepts relative
URL, so it can go for resources inside or outside the server.
Example 11.2: Demonstrating the usage of sendRedirect()
MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
PrintWriter out = response.getWriter();
try {
response.sendRedirect(“http://
www.vikaspublishing.com”);
}
finally {
out.close();
}
}
}

Self-Instructional
Material 221
Servlet Parameters Servlet Collaboration
Servlet collaboration or specifically servlet communication is a very powerful feature
of Java Servlets. It helps forwarding the clients request to a new servlet and also
NOTES helps in including the response of one servlet in that of the other servlets. A single
client’s request can move across many Servlets and/or to any other resource in
the Web Application. This complete process well occurs on the server-side and,
unlike response redirection, does not mandate for any action from a client or extra
information sent between the client and server. This can be achieved through the
javax.servlet.RequestDispatcher object. You can call an appropriate instance of a
RequestDispatcher object by calling either of the following methods of a
ServletRequest interface:
 getRequestDispatcher(java.lang.String path)
The getRequestDispatcher() method returns the RequestDispatcher object
for a given path. The path value may lead to any resource in the Web
Application and must start from the root directory, “/”.
 getNamedDispatcher(java.lang.String name)
The getNamedDispatcher() method returns the RequestDispatcher object
for the named Servlet. Valid names are defined by the servlet-name elements
of web.xml.
A RequestDispatcher object provides two methods for including different
resources and for forwarding a request to a different resource.
 forward (javax.servlet.ServletRequest, javax.servlet.ServletResponse)
The forward () method delegates a request and response to the resource
of the RequestDispatcher object. A call to the forward () method may be
used only if no content has been previously sent to a client. No further data
can be sent to the client after the forward has completed.

Fig. 11.4 RequestDispatcher forward() method mechanism

 include (javax.servlet.ServletRequest, javax.servlet.Servlet


Response): The include () method works similarly to forward () but with
restrictions. A Servlet can include () any number of resources that can each
generate responses, but the resource is not allowed to set headers or commit
a response.
Self-Instructional
222 Material
Servlet Parameters

NOTES

Fig. 11.5 RequestDispatcher include() method mechanism

Example 11.3: Demonstrating usage of RequestDispatcher interface


The example given below depicts how RequestDispatcher is used to forward or
include response of a resource in a Servlet. To show this three files are required
apart from the deployment descriptor , first is the master page named as index.html
to get username and password from the user, then Validate Servlet file ,which will
be used to validate the password entered by the user, if the user has entered
“studytonight” as password, then he will be forwarded to the last file - Welcome
Servlet. If not, then he will stay on the index.html page and an error message will
be displayed.
Files to be created:
 Index.html will have form fields to get user information.
 ValidateServlet.java will validate the data entered by the user.
 WelcomeServlet.java will be the welcome page.
 web.xml, the deployment descriptor.
index.html
<form method=”post” action=”Validate”>
Name:<input type=”text” name=”user” /><br/>
Password:<input type=”password” name=”pass” ><br/>
<input type=”submit” value=”submit”>
</form>
ValidateServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ValidateServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
Self-Instructional
Material 223
Servlet Parameters PrintWriter out = response.getWriter();
try {
String name = request.getParameter(“user”);
String password = request.getParameter(“pass”);
NOTES
if(password.equals(“studytonight”))
{
RequestDispatcher rd =
request.getRequestDispatcher(“Welcome”);
rd.forward(request, response);
}
else
{
out.println(“<font color=’red’><b>You have entered
incorrect password</b></font>”);
RequestDispatcher rd =
request.getRequestDispatcher(“index.html”);
rd.include(request, response);
}
}finally {
out.close();
}
}
}
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
PrintWriter out = response.getWriter();
try {
ut.println(“<h2>Welcome user</h2>”);
}
Finally
{

Self-Instructional
224 Material
out.close(); Servlet Parameters
}
}
}
NOTES
web.xml
<web-app>
<servlet>
<servlet-name>VS</servlet-name>
<servlet-class>ValidateServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>WS</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>VS</servlet-name>
<url-pattern>/Validate</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WS</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Index.html</welcome-file>
</welcome-file-list>
</web-app>

Check Your Progress


1. What does a ServletRequest object provide?
2. What does combining two or more servlets do?
3. What does response redirection pertain to?

11.6 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. A ServletRequest object provides data including parameter name and values,


attributes, and an input stream.

Self-Instructional
Material 225
Servlet Parameters 2. Combining two or more servlets such that either they delegate the responses
or collaborate to produce a common response is called Servlet
Collaboration.
3. Response redirection pertains basically to calling a servlet from another
NOTES
servlet and transferring the response to it.

11.7 SUMMARY

 The basic mechanism of interaction in client–server technology occurs only


with the requests and responses, between the client and the server.
 A client sends requests to the server for accomplishing some task and the
server reverts back with appropriate response to the client. This same
paradigm is used in Servlets as well.
 A Servlet needs specific information about a request so that it can process
the request appropriately.
 These interfaces provide the server access to the information required for
processing. When a Servlet is asked to handle a request, the server passes
it a request object that implements one of these interfaces.
 This interface defines an object to provide client request information to a
Servlet.
 A ServletRequest object provides data including parameter name and
values, attributes, and an input stream.
 HttpServletRequest interface comprises of some additional methods for
handling HTTP-specific request data apart from the existing ServletRequest
interface.
 In this implementation of the HttpServletRequest Interface you will see how
a parameter is passed to a Servlet in a request object from HTML page.
 For every request that comes to the server, the servlet has to send back
some response as a token of processing the request successfully.
 This interface defines an object to help a Servlet in sending a response to
the client. The servlet container creates a ServletResponse object and passes
it as an argument to the Servlet’s service method.
 This interface extends the ServletResponse interface to provide HTTP-
specific functionality in sending a response.
 Combining two or more servlets such that either they delegate the responses
or collaborate to produce a common response is called Servlet
Collaboration.

Self-Instructional
226 Material
 Since servlets are Java programs, they can do anything a standard Java Servlet Parameters

program can do, such as make a network connection. In this way, we have
implicit servlet interaction.
 Through the RequestDispatcher object, we can forward a request to another
NOTES
servlet, which can handle the request and return the response.
 The javax.servlet.ServletConfig interface provides a support to pass
information to a servlet during initialization by getting configuration information
from web.xml (Deployment Descriptor).
 The javax.servlet.ServletContext interface primarily provides the reference
to the web application in which the servlets execute.
 Response redirection pertains basically to calling a servlet from another
servlet and transferring the response to it.
 Servlet collaboration or specifically servlet communication is a very powerful
feature of Java Servlets.

11.8 KEY WORDS

 Servlet Collaboration: This refers to combining two or more servlets such


that either they delegate the responses or collaborate to produce a common
response is called Servlet Collaboration.
 The getRequestDispatcher(): It is a method returns the RequestDispatcher
object for a given path. The path value may lead to any resource in the Web
Application and must start from the root directory, “/”.

11.9 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short-Answer Question
1. What do you understand by Servlet Responses?
2. Discuss some useful methods of ServletRequest Interface.
3. Analyse HttpServletResponse Interface and its functionality.
4. Explain servlets interactions and their use.
Long-Answer Questions
1. Explain the methods of ServletConfig.
2. Explain the ServletContext. State few examples.
3. Share and explain some examples demonstrating usage of
RequestDispatcher interface.
Self-Instructional
Material 227
Servlet Parameters
11.10 FURTHER READINGS

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
NOTES Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
228 Material
Cookies and Session

UNIT 12 COOKIES AND SESSION Tracking

TRACKING
NOTES
Structure
12.0 Introduction
12.1 Objectives
12.2 Session Management/Tracking
12.3 Servlet Debugging
12.4 Answers to Check Your Progress Questions
12.5 Summary
12.6 Key Words
12.7 Self Assessment Questions and Exercises
12.8 Further Readings

12.0 INTRODUCTION

In this unit, you will learn about the session management with the session tracking
Servlet APIs and various other methods. Session management is essential in every
e-commerce web applications so as to keep track of their user’s preferences and
the site visitors. Session tracking is the mechanism of identifying the user, if he
revisits the website and storing his state throughout his stay on the website.

12.1 OBJECTIVES

After going through this unit, you will be able to:


 Understand session management and tracking
 Explain about client side session tracking
 Analyse the server side session tracking
 Discuss the advantage of cookie’s
 Explain about the hidden form fields
 Discuss the Http session interface and the session tracking API

12.2 SESSION MANAGEMENT/TRACKING

The Web knows only one protocol for communication, HTTP but it is stateless.
HTTP protocol cannot save the session state information of the client it just can
exchange requests from the client, and response from the server till the connection
between them is open. Once the connection is closed/lost, server forgets the client

Self-Instructional
Material 229
Cookies and Session as nothing about the client was conveyed to it .And if the same client requests
Tracking
again to the same server then, the server will treat it as a new ,fresh request with
no relation to the previous activity. This is why HTTP is considered as stateless
and useless protocol for session management. So, to accomplish the session
NOTES management, it cannot be used.
The second option is to use server to maintain the state and session, but the
server itself cannot do anything, it cannot automatically maintain contextual
information about the clients.
Now, the problem is, “How to maintain the session and the context
information about the client?” You need to answer this question if you are building
an E-Com website.
So there are basically two ways that you can use to track the client and they
are discussed below:
1. Client Side Session Tracking
Utilizing the client side applications (like browsers) to store the client information
and then creating a mechanism to send the information to the server so that it
recognizes the client is generally referred to as Client Side Session tracking. It
involves the following methods:
 Using Cookies,
 Implementing URL rewriting,
 Including hidden form fields

Fig. 12.1 Session Management /Tracking

2. Server Side Session tracking.


In this method, Client Side Trackers like cookies and Hidden form fields are
utilized by the server resident program (like Servlet) for getting the session
information. The client cannot disable this tracker like he can, in case of cookies.
All the three mechanisms i.e., using Cookies, implementing URL rewriting
and including hidden form fields in the web page provide solutions without using
the built in session tracking APIs as they are used at client side for session tracking.
Self-Instructional
230 Material
The fourth one is the mechanism that is the actual server side implementation for Cookies and Session
Tracking
session tracking which uses the Servlet APIs,the topic of main focus.
Using Cookies
This is an excellent solution and is the most widely used approach for session NOTES
handling. Servlets are so powerful enough that they not only have a higher-level
API that handles all this but also accomplish the following tedious tasks:
 Extracting the cookie that is capable of storing the session identifier from
the other cookies as well.
 Setting a suitable expiration time for the cookie used.
 Associating the hash tables with each request for further use in session
management.
 Generating the unique session identifiers to be used extensively.
So “what are cookies?” .Cookies are the text files that are sent and
stored on the client computer so as to track the client .These text files may store
various information like name, a single value, and optional attributes such as a
comment, path and domain qualifiers, a maximum age, and a version number elated
to the client. Cookies are created using Cookie class present in Servlet API.
Cookies are added to response object which sends cookie information over the
HTTP response stream. Pictorially it can be shown as:

Fig. 12.2 Cookies in Action

Advantages of Cookie
 It is the simplest technique of maintaining the state.
 Cookie are maintained at client side so no server side overhead.
 All server side technology and all web servers, application servers support
cookies.
 Persistent cookies can remember client data during session and after session
with expiry time.
Limitations of Cookie
 It will not work if cookie is disabled from the browser.
Self-Instructional
Material 231
Cookies and Session  Cookies are text files, hence not secure. Anyone can change this file.
Tracking
 Cookies cannot store java objects as values; they only store text or string.
The Cookie Class
NOTES
The javax.servlet.http.Cookie class provides the functionality of using cookies.
Cookies are created using Cookie class present in Servlet API. Cookies are added
to response object using the addCookie() method. This addCookie() method
reverts with the cookie information over the HTTP response stream back to the
server. getCookies() method is used access the cookies that are added to response
object returning from the client.
In HttpSession technique, the Servlet container implicitly generates a cookies
for transferring the session ID between server and client. Apart from container
generated cookie a servlet programmer can also generate cookies explicitly for
storing the client information.
Cookie class provides some constructor and methods for cookies which
have been tabulated below:
Constructors of Cookie Class
Constructor Description
Cookie() Used for constructs a cookie.
Cookie(String name, String value) Used for constructs a cookie with a
specified name and value.

Methods of Cookie class


Methods Description
public void setMaxAge(int expiry) It is used for Sets the maximum age of the
cookie in seconds.
public String getName() It is used for Returns the name of the cookie.
The name cannot be changed after creation.
public String getValue() It is used for Returns the value of the cookie.
public void setName(String name) It is used for changes the name of the cookie.
public void setValue(String value) It is used for changes the value of the cookie.
public void addCookie(Cookie ck) It is method of HttpServletResponse interface
which is used to add cookie in response object.
public Cookie[] getCookies() It is method of HttpServletRequest interface
which is used to return all the cookies from the
browser.

Example 12.1: Implementation of session tracking using Cookies


index.html
<html>
<head><title>SessionTrackingUsingCookies</title>
</head>
<body>
Self-Instructional
232 Material
<form action=”servlet1"> Cookies and Session
Tracking
Name:<input type=”text” name=”userName”/> <br/>
<input type=”submit” value=”continue”/>
</form>
NOTES
</body>
</html>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
String n=request.getParameter(“userName”);
out.print(“Welcome “+n);
Cookie ck=new Cookie(“uname”,n);//creating cookie
object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print(“<form action=’servlet2'>”);
out.print(“<input type=’submit’ value=’continue’>”);
out.print(“</form>”);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {


public void doPost(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
Self-Instructional
Material 233
Cookies and Session out.print(“Hello “+ck[0].getValue());
Tracking
out.close();
}catch(Exception e){System.out.println(e);}
} }
NOTES
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Note: In this web.xml, you can see there are two Servlets given with their respective
URL patterns mapped accordingly.
Activity: Try using three Servlets and the session management using cookies.
URL Rewriting
URL rewriting is one of the best methods that can be implemented to track a
session when cookies do not work on the browsers or cookies have been disabled
by the user. With this approach, the client appends some extra data at the end of
each URL that identifies the session. On receiving the appended identifier, the
server associates it with the data it has stored about that session. And like this the
server tracks the user.
This can be elaborated by the example,with http:/file.html;jsessionid=x12,
the session information is attached as jsessionid=x12.
However, it has most of the same problems as cookies, namely, that the
server-side program has a lot of straightforward but tedious processing to do. In
addition, you have to be very careful that every URL that references your site and
Self-Instructional
234 Material
is returned to the user (even by indirect means like Location fields in server redirects) Cookies and Session
Tracking
has the extra information appended. And, if the user leaves the session and comes
back via a bookmark or link, the session information can be lost.
Hidden Form Fields NOTES
As the name suggest, these are the HTML form fields that are hidden in the forms.
Every time the form is submitted to the server ,these hidden fields provide the
information regarding the session.
HTML forms fields have the following syntax:
<INPUT TYPE=”HIDDEN” NAME=”session” VALUE=”...”>
This syntax specifies that, when the form is submitted, the specified name
and value are included in the GET or POST data and sent to the server .Then the
server can identify the client by the information. This hidden field can be used to
store information about the session but has the major shortcoming that it will work
only if every page is dynamically generated by the form submission. Hence, hidden
form fields do not provide enough support to general session tracking. These are
beneficial only when you need to track the user for some certain activities.
HttpSession Interface-The Session Tracking API
You have seen various methods for tracking the user activities form cookies to
hidden form fields, but Servlets provide a marvelous technical solution: the
HttpSession API. This high-level interface, HttpSession interface has advantages
over cookies or URL rewriting and most interestingly it works on top of cookies
or URL rewriting.
Using sessions in Servlets is very clear .It involves the following mechanism:
 Looking up the session object associated with the current request,
 Creating a new session object when necessary,
 Looking up information associated with a session,
 Storing information in a session, and
 Discarding completed or abandoned sessions.
With cookies the session can be managed easily. But if any URLs is returned
to the clients that reference your site and URL rewriting is being used, then the
session information need to be attached to the URLs so that it could be used to
track the client.
1. Looking up the HttpSession object associated with
the current request
Looking up of the HttpSession object can be done by calling the getSession()
method of HttpServletRequest. If getSession() returns null, this means that the
user is not already participating in a session, so you can create a new session. But
what exactly happened behind the scenes- the system extracts a user ID from a
Self-Instructional
Material 235
Cookies and Session cookie or appended URL data, and uses it as a key to look up into a table of
Tracking
previously created HttpSession objects.
2. Creating a new session
NOTES You can easily create a new session and also check if it’s a new one or the existing
one. HttpSession APIs provide an option to automatically create a new session if
one doesn’t already exist. What you have to do is to pass “true” to getSession()
method like this:
HttpSession session = request.getSession(true);
And if you wish know whether the session already existed or is a newly created
one.Just use the method isNew() to check.If it returns true then the session object
is new else it is one from the pool.
3. Looking up information associated with a session and storing them
HttpSession objects reside on the server and are automatically associated with
the client by a hidden mechanism like cookies or URL rewriting. These session
objects use a built-in data structure to you store any number of keys and associated
values using the setAttributes() method. Like as shown below
HttpSession session = request.getSession(true);
PurchasedItems purchItems =
(PurchasedItems)session.getAttribute(“PurchasedItem”);
if (purchItems == null) // No purchItems already in
session
{
purchItems = new PurchasedItems();
session.setAttribute(“PurchasedItems”, purchItems);
}
doSomethingWith(purchItems);
All the attribute names in a given session can be listed by calling the
getValueNames () method, which returns an array of strings. And you can use
getAttributeName,it returns an Enumeration, just like the getHeaderNames() and
getParameter Names() methods of HttpServletRequest.
Methods of HttpSession Interface
1. public void HttpSession.setAttribute(String name, Object value)
This method adds data to a session object.
2. public Object HttpSession.getAttribute(String name)
You can use the given method to retrieve an object from a session
3. public Enumeration HttpSession.getAttributeNames()
You can use this method to get the names of all objects in a session
Self-Instructional
236 Material
4. public void HttpSession.removeAttribute(String name) Cookies and Session
Tracking
You can use this method to remove an object from a session.
5. boolean isNew()
Returns true if the client does not yet know about the session or if the client NOTES
chooses not to join the session.
6. void invalidate()
Invalidates this session then unbinds any objects bound to it.
7. long getCreationTime()
Returns the time when this session was created, measured in milliseconds
since midnight January 1, 1970 GMT.
8. long getLastAccessedTime()
Returns the last time the client sent a request associated with this session, as
the number of milliseconds since midnight January 1, 1970 GMT, and
marked by the time the container received the request.
Note: The use of these methods can be seen in the application discussed as example.
Deprecated methods since API 2.2 (NOT IN USE NOW)
(i) putValue(),
(ii) getValue();
(iii) getValueNames();
(iv) removeValue()
A Web Page Visit-Counter Servlet
A real feel of the servlet use can be taken once you run it on the browser. Down
below is the complete code of an application illustrating use of HttpSession APIs.
Just deploy the application as instructed in previous section.
VisitCounterServletEx.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class VisitCounterServletEx extends HttpServlet
{
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter out = resp.getWriter();
resp.setContentType(“text/html”);
HttpSession thisUser = req.getSession(true);
Integer visits; Self-Instructional
Material 237
Cookies and Session if (!thisUser.isNew()) { //Don’t check newly created
Tracking sessions
visits =
(Integer)thisUser.getValue(“visitcounter.visits”);
NOTES if(visits == null)
visits = new Integer(1);
else
visits = new Integer(visits.intValue() + 1);
}
else
visits = new Integer(1);
// Put the new count in the session
thisUser.putValue(“visitcounter.visits”, visits);
// Finally, display the results and give them the
session ID too
out.println(“<HTML><HEAD><TITLE>Visit Counter</TITLE></
HEAD>”);
out.println(“<BODY>You have visited this page “ +
visits + “ time[s]”);
out.println(“since your last session expired.”);
out.println(“Your Session ID is “ + thisUser.getId());
out.println(“</BODY></HTML>”);
}}
web.xml
<?xml version=”1.0" encoding=”ISO-8859-1"?>
<web-app >
<servlet>
<servlet-name>VCSE</servlet-name>
<servlet-class>VisitCounterServletEx</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>VCSE</servlet-name>
<url-pattern>/fts1</url-pattern>
</servlet-mapping>
</web-app>
Output:
What you will see is a statement on the browser about how many times you have
visited the page since you page last expired. Every refreshing to the URL will
increase the number of visits.
Self-Instructional
238 Material
Activity: Try to open the web page in multiple browsers in the same system. Cookies and Session
Tracking
Find the results and make conclusions. Also try implementing in your application.

12.3 SERVLET DEBUGGING NOTES


Many times you do not get what was intended from the Servlets, it may be because
you did not code well or it may be because of some bugs in the programs. So the
best way is to track where the errors or mistakes have been done and rectify them
as and where they occurred. To achieve this, you need to debug your Servlet and
this section entirely deals with various mechanisms for Servlet debugging.
Servlet debugging is the process of finding the errors and bugs in the Servlet
programs meant for the web applications and rectifying them as per specifications.
Some of the techniques for doing this have been discussed below:
1. Use print statements
The easiest technique is to insert a couple of print statements to find out which line
of code generated the error. When in doubt, gather more information
2. Use an integrated debugger in your IDE
The integrated development environments (IDEs) have advanced debugging tools
that can be integrated with your servlet and JSP container. But an expertise in
these IDE is a a must for this. The Enterprise editions of IDEs like Borland JBuilder,
Oracle JDeveloper, IBM WebSphere Studio, Eclipse, BEA WebLogic Studio,
Sun ONE Studio, etc., typically let you insert breakpoints, trace method calls, and
so on.
3. Use the log file
Reading debugging message from the log file is a convenient method than watching
them directly from a window as with the above two approaches. Using the log file
is the best option even when running on a remote server where print statements
are rarely useful and only some of the advanced IDEs support remote debugging.
4. Look at the HTML source
If the result you see in the browser looks odd, choose View Source from the
browser’s menu. Sometimes a small HTML error like <TABLE> instead of </
TABLE> can prevent much of the page from being viewed. Even better, use a
formal HTML validator on the servlet’s output.
5. Check the web.xml file
Sometimes, we make minor mistakes in writing the web.xml for the servlets, like
missing to write any parenthesis or writing the names of the Servlet class in the
descriptor. So a careful analysis of the web.xml can end up with eradicating the
possible source of errors.
Self-Instructional
Material 239
Cookies and Session 6. Stop and restart the server
Tracking
Perhaps, when everything is correct and then also your Servlet is not executing,
then trying to stop and restart the server may help you get your Servlet working as
NOTES sometimes the configuration of the server may have invalidated the Servlets.

Check Your Progress


1. How do you look up of the HttpSession object?
2. When can a real feel of the servlet use be taken?
3. What is the best method to track a session when cookies do not work?

12.4 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. Looking up of the HttpSession object can be done by calling the getSession()


method of HttpServletRequest.
2. A real feel of the servlet use can be taken once you run it on the browser.
3. URL rewriting is one of the best methods that can be implemented to track
a session when cookies do not work.

12.5 SUMMARY

 The Web knows only one protocol for communication, HTTP but it is
stateless.
 Session management is essential in every E-Com web applications so as to
keep track of their user’s preferences and the site visitors.
 Utilizing the client side applications (like browsers) to store the client
information and then creating a mechanism to send the information to the
server so that it recognizes the client is generally referred to as Client Side
Session tracking.
 This is an excellent solution and is the most widely used approach for session
handling.
 In HttpSession technique, the Servlet container implicitly generates a cookies
for transferring the session ID between server and client.
 URL rewriting is one of the best methods that can be implemented to track
a session when cookies do not work on the browsers or cookies have
been disabled by the user.

Self-Instructional
240 Material
 Looking up of the HttpSession object can be done by calling the getSession() Cookies and Session
Tracking
method of HttpServletRequest.
 You can easily create a new session and also check if it’s a new one or the
existing one.
NOTES
 A real feel of the servlet use can be taken once you run it on the browser.
 Many times you do not get what was intended from the Servlets, it may be
because you did not code well or it may be because of some bugs in the
programs.
 The easiest technique is to insert a couple of print statements to find out
which line of code generated the error.
 The integrated development environments (IDEs) have advanced debugging
tools that can be integrated with your servlet and JSP container. But an
expertise in these IDE is a must for this.
 Sometimes, we make minor mistakes in writing the web.xml for the servlets,
like missing to write any parenthesis or writing the names of the Servlet
class in the descriptor.

12.6 KEY WORDS

 Server Side Session Tracking: It is a method where the Client Side


Trackers like cookies and hidden form fields are utilized by the server resident
program (like Servlet) for getting the session information.
 Cookies: These are small files which are stored on a user’s computer.

12.7 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short-Answer Questions
1. What do you understand by session management and tracking?
2. Explain about client side session tracking.
3. Analyse the server side session tracking.
Long-Answer Questions
1. Explain how to look up the HttpSession object associated with the current
request.
2. What are the advantage of cookies? Explain.
3. What do you mean by the the hidden form fields?
4. What do you mean by Http session interface and the session tracking API?
Self-Instructional
Material 241
Cookies and Session
Tracking 12.8 FURTHER READINGS

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
NOTES Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
242 Material
Java Interface

UNIT 13 JAVA INTERFACE Components

COMPONENTS
NOTES
Structure
13.0 Introduction
13.1 Objectives
13.2 Swing Components and Containers
13.2.1 Swing Components (JComponent Class)
13.2.2 Swing Containers
13.3 Creating a Swing Applet and Application
13.4 User Interface Components
13.4.1 JApplet
13.4.2 JFrame
13.4.3 Label
13.4.4 Button
13.4.5 ToggleButton
13.4.6 CheckBox
13.4.7 TextField
13.4.8 TextArea
13.4.9 RadioButton
13.4.10 Panel
13.4.11 ScrollPane
13.4.12 ComboBox
13.4.13 JTree Class
13.5 Programming using Panes
13.5.1 Layered Panes
13.5.2 Split Panes
13.5.3 Tabbed Panes
13.6 JTable
13.7 Answers to Check Your Progress Questions
13.8 Summary
13.9 Key Words
13.10 Self Assessment Questions and Exercises
13.11 Further Readings

13.0 INTRODUCTION

In this unit, you will learn about the various components of swing. Swing, a part of
Java Federation Classes (JFC) is the next generation GUI toolkit that allows us to
develop large scale enterprise applications in Java. It is a set of classes which
provides many powerful and flexible components for creating graphical user
interface. Earlier, the concept of Swing did not exist in Java and the user interfaces
were built by using the Java’s original GUI system, AWT. Because of the limitations
of the AWT, Swing was introduced in 1997 by the Sun Microsystems. It provides
new and improved components that enhance the look and functionality of GUIs.
Self-Instructional
Material 243
Java Interface
Components 13.1 OBJECTIVES

After going through this unit, you will be able to:


NOTES  Understand the concept of Swing components and containers
 Understand how to create swing applet
 Explain the various user interface components
 Understand the use of the various pane classes

13.2 SWING COMPONENTS AND CONTAINERS

Like AWT GUI, Swing GUI is also based on the concept of components and
containers. A container is a type of component that can hold other components. A
component must always be placed within a container. A container can also hold
other containers, thus, they can be organized in a hierarchy. This class hierarchy is
similar to that of AWT but in Swing, the name of class is preceded by ‘J’.
13.2.1 Swing Components (JComponent Class)
Swing component is an independent control, such as button, label, text field, etc.
They need a container to display themselves. Swing components are derived from
JComponent class. JComponent provides the functionality common for
all components. JComponent inherits the AWT class Container and
Component. Thus, a Swing component and AWT component are compatible
with each other. Table 13.1 lists the classes required for creating various Swing
components (including those used as containers).
Table 13.1 List of Classes for Swing Components

We will discuss some of the important components later in this Unit.

Self-Instructional
244 Material
13.2.2 Swing Containers Java Interface
Components
There are two types of containers namely, top-level containers and lightweight
containers.
Top-Level Containers NOTES

A top-level container, as the name suggests, lies at the top of the containment
hierarchy. The top-level containers are JFrame, JApplet, and JDialog.
These containers do not inherit JComponent class but inherit the AWT
classes’ Component and Container. These containers are heavyweight
components. The most commonly used containers are JFrame and JApplet.
Each top-level container defines a set of panes. JRootPane is a special
container which extends JComponent and manages the appearance of
JApplet and JFrame objects. It contains a fixed set of panes, namely, glass
pane, content pane, and layered pane.
 Glass Pane: A glass pane is a top-level pane which covers all other
panes. By default, it is a transparent instance of JPanel class. It is
used to handle the mouse events affecting the entire container.
 Layered Pane: A layered pane is an instance of JLayeredPane
class. It holds a container called the content pane and an optional menu
bar.
 Content Pane: A content pane is a pane which is used to hold the
components. All the visual components like buttons, labels are added to
content pane. By default, it is an opaque instance of JPanel class
and uses border layout. The content pane is accessed via
getContentPane() method of JApplet and JFrame classes.
Note: In AWT, the components are directly added to the applet or frame window,
however, in Swing, they are required to be added to the content pane.
Lightweight Containers
Lightweight containers lie next to the top-level containers in the containment
hierarchy. They inherit JComponent. One of the examples of lightweight
container is JPanel. As lightweight container can be contained within another
container, they can be used to organize and manage groups of related components.

13.3 CREATING A SWING APPLET AND


APPLICATION

The sample program given below shows an example to write a Swing application.
It uses two Swing components: JFrame (top-level container) and JButton
(component which creates a push button).

Self-Instructional
Material 245
Java Interface Example 13.1: A program to demonstrate the creation of a Swing application.
Components
import javax.swing.*;
class MySwingDemo extends JApplet
{
NOTES
public static void main(String str[])
{
//creates a new frame
JFrame jf = new JFrame(“Swing application”);
//specify the initial size of the frame
jf.setSize(300,125);
//Terminates the program
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
//create a new button
JButton b1 = new JButton(“Click”);
//Adding button to the frame
jf.add(b1);
//Display the frame
jf.setVisible(true);
}
}
Swing programs are compiled and executed like any other Java application.
The program given in Example 13.1 can be compiled by using the following
command.
javac MySwingDemo.java
To execute the program, following command is used.
java MySwingDemo
The output of the program is

The explanation of this program is as follows:


1. In the beginning of the program, the javax.swing package is imported.
2. Next, MySwingDemo class which extends the JApplet class is
declared. An object of JFrame class is created using the statement.
JFrame jf = new JFrame(“Swing application”);
Self-Instructional
246 Material
It creates a container called jf that defines a rectangular window with a Java Interface
Components
specified string displayed on the title bar.
3. The size of the window is specified by using the statement.
jf.setSize(300, 125); NOTES
The general form of setSize() method to set the size of the window
is:
void setSize(int width, int height)
where,
width is the width of the window
height is the height of the window
4. The statement used for terminating the program when the window is closed
is
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
When the above statement is executed, the entire application terminates
with the closing of window.
The general form of setDefaultCloseOperation() is
void setDefaultCloseOperation(int w)
where,
w specifies the action to be performed on the window when it is closed. It
has several options which are as follows:
JFrame.DISPOSE_ON_CLOSE
JFrame.HIDE_ON_CLOSE
JFrame.DO_NOTHING_ON_CLOSE
By default, when the top-level window is closed, the application is not
terminated. It simply removes the window from the screen.
5. A Swing component JButton is created using the statement.
JButton b1 = new JButton(“Click”);
6. The button is added to the content pane of the frame by using the statement.
jf.add(b1);
The component is added to the frame’s content pane by calling add()
method on the JFrame reference (jf ). JFrame inherits the add()
method from the AWT class Container.
The general form of add() method is:
Component add(Component comp)
where,
comp is the object of the component to be added
7. The statement to make the window visible is
jf.setVisible(true);
Self-Instructional
Material 247
Java Interface The setVisible() method is inherited from the AWT Component
Components
class. If it is set to true, the window will be displayed, otherwise not. By
default, a JFrame is invisible.
Note: Prior to JDK 5, the content pane was obtained by calling getContentPane()
NOTES method. However, today, the use of getContentPane() is no longer necessary. We
can call add(), remove(), and setLayout() directly on JFrame as they operate
on the content pane automatically.

13.4 USER INTERFACE COMPONENTS

In this section, we will present an overview of some of the components of Swing.


13.4.1 JApplet
JApplet is a class that represents the Swing applet. It is a subclass of Applet
class and must be extended by all the applets that use Swing. It provides all the
functionalities of the AWT applet as well as support for menubars and layering of
components. Whenever, we require to add a component to it, the component is
added to the content pane.
The JApplet defines the following constructor.
JApplet()
13.4.2 JFrame
Frame is the most common container used to create top-level window having title,
border and window-management buttons. It can also be used to create secondary
windows for an application. A frame is an object of JFrame class.
The constructors defined by this class JFrame class are as follow:
JFrame()
JFrame(String title)
where,
title specifies the title for the frame
Example 13.2: A program to demonstrate the use JFrame class
import java.awt.*;
import javax.swing.*;
class FrameExample extends JApplet
{
JFrame jf ;
FrameExample()
{
jf = new JFrame(“Frame Example”);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setSize(400,300);
Self-Instructional
248 Material
jf.setVisible(true); Java Interface
Components
}
public static void main(String args[])
{
NOTES
FrameExample se = new FrameExample();
}
}
The output of the program is

By, default when user clicks the close button, the window is removed from
the display; however, the application is not terminated. The application still occupies
space in memory, which is not required in most of the cases. To terminate the
application when user clicks the close button of the top-level window, the
setDefaultCloseOperation() method is used.
13.4.3 Label
A label is a simple control which is used to display text (non-editable) on the
window. Since it does not possess any user interactive feature, it is considered as
a passive control. A label is an object of JLabel class.
Some of the constructors defined by JLabel class are as follows:
JLabel()
JLabel(String string)
JLabel(String string, int align)
where,
string is the text used for the label
align specifies the horizontal alignment of the text contained in the label,
and can have one of the following values: LEFT, RIGHT, CENTER, LEADING
or TRAILING Self-Instructional
Material 249
Java Interface 13.4.4 Button
Components
A button, also known as push button, is an active control that has a 3-dimensional
appearance. It triggers an event when it is clicked or activated. Swing also provides
NOTES an ability to associate an icon, a string, or both with the buttons. A push button is
an object of JButton class.
Some of the constructors defined by JButton class are as follows:
JButton()
JButton(Icon icon)
JButton(String string)
where,
string represents the string used for the button
icon represents the icon used for the button
Note: All the buttons are derived from AbstractButton class.

13.4.5 ToggleButton
Swing provides a variant of push button called ToggleButton which has
two states: pushed and released. When ToggleButton is pressed for the
first time, it remains pressed and it is released only when it is pressed for the
second time. This button toggles between pushed and released state.
ToggleButton is an object of JToggleButton class.
Some of the constructors defined by JToggleButton class are as
follows:
JToggleButton()
JToggleButton(String string)
JToggleButton(String string, boolean state)
where,
string specifies the text
state can have one of the two values: true, if the button is initially
selected, otherwise false (default value)
13.4.6 CheckBox
A checkBox is a control that consists of a combination of a small box and a
label. The label provides the description of the box with which it is associated. It
is a two-state control having states true (checked) and false (unchecked).
The state of a CheckBox can be changed by clicking on it. A CheckBox is an
object of JCheckBox class.
Some of the constructors defined by JCheckBox class are as follows:
JCheckBox()
JCheckBox(String string)
Self-Instructional
JCheckBox(String string, boolean isSelected)
250 Material
where, Java Interface
Components
string is the text used as a label for the CheckBox
isSelected is used to set the initial state of the CheckBox. If it is
true, the CheckBox is checked, otherwise it is unchecked. The default state NOTES
of the CheckBox is false.
13.4.7 TextField
TextField control creates a single-line text area. The TextField allows
the user to enter and edit the text using cut, copy and paste keys, arrow keys and
mouse selections. It is an object of JTextField class which is a subclass of
JTextComponent.
Some of the constructors defined by JTextField class are as follows:
JTextField()
JTextField(int cols)
JTextField(String string, int cols)
JTextField(String string)
where,
string is the initial string contained in the text field
cols is the width of the text field in terms of columns
13.4.8 TextArea
The TextArea creates a multi-line text area. It does not provide scrolling
facility; however, scroll bars can be added by adding the JTextArea in
JScrollPane container. A TextArea is an object of JTextArea class
which is a subclass of JComponent.
Some of the constructors defined by JTextArea class are as follows:
JTextArea()
JTextArea(String str1)
JTextArea(int rows, int cols)
JTextArea(String str1, int rows, int cols)
where,
str1 is the initial string contained in TextArea
rows represents the height of the TextArea or the maximum rows a
text area can have
cols represents the width of the text area, that is, the maximum number
of characters each line of the text area can contain
13.4.9 RadioButton
Radio buttons are a group of buttons, in which, only one radio button can be
selected at one time. That is, when you select any one RadioButton, then the
Self-Instructional
Material 251
Java Interface other selected RadioButton will get deselected automatically. A
Components
RadioButton is an object of JRadioButton class.
Some of the constructors defined by JRadioButton class are as follows:
NOTES JRadioButton()
JRadioButton(String string)
JRadioButton(String string, boolean state)
where,
string specifies the text
state can have one of the two values: true, if the button is initially
selected, otherwise false (default value)
Note: Button groups (javax.swing.ButtonGroup) are used in combination with
radio buttons to ensure that only one radio button is selected at a time.
13.4.10 Panel
Panel is a container to hold different Swing components. One can add any number
of components to a panel and there can be multiple panels in the same frame. It
also supports double buffering which is used in animation to avoid flickering. In
double buffering, object is first written to an off-screen memory before display
and then switched over to the panel. Flow layout is the default layout for the panel.
A panel is an object of class JPanel which is present in package
javax.swing.
Some of the constructors defined by JPanel class are as follows:
JPanel()
JPanel(boolean isDoubleBuffered)
JPanel(LayoutManager layout)
JPanel(LayoutManager layout, boolean isDoubleBuffered)
where,
isDoubleBuffered defines whether the panel is double buffered or
not. It can have one of the values: true (double buffered) or false (not double
buffered)
layout defines the layout of the panel
13.4.11 ScrollPane
A ScrollPane is a container that represents a small area to view other
component. If the component is larger than the visible area, ScrollPane
provides horizontal and/or vertical scroll bars automatically for scrolling the
components through the pane. A ScrollPane is an object of the
JScrollPane class which extends JComponent.
Some of the constructors defined by JScrollPane class are as follows:
JSrollPane()
Self-Instructional JScrollPane(Component component)
252 Material
JScrollPane(int ver, int hor) Java Interface
Components
JScrollPane(Component component, int ver, int hor)
where,
component is the component to be added to the ScrollPane NOTES
ver and hor specify the policies to display the vertical and horizontal
scroll bar, respectively. Some of the standard policies are:
H O R I Z O N T A L _ S C R O L L B A R _ A L W A Y S ,
HO RIZO NTAL _SCR OLL BAR_AS_N EEDED,
V E R T I C A L _ S C R O L L B A R _ A L W A Y S ,
VERTICAL_SCROLLBAR_AS_NEEDED
Note: JScrollPane is a lightweight container.

13.4.12 ComboBox
A ComboBox is a combination of a list component and text field component. It
can consist of more than one item, however, displays only one item at any point of
time. It also allows user to type their selection. Unlike list component, combo box
allows user to select only one item at a time. A ComboBox is an object of
JComboBox class.
Some of the constructors defined by JComboBox class are as follows:
JComboBox()
JComboBox(Object combodata[])
where,
combodata represents the array of Object type that displays the
elements
Example 13.3: A program to demonstrate the use of JComboBox class
import java.awt.*;
import javax.swing.*;
public class ComboBoxExample extends JApplet
{
ComboBoxExample()
{
JFrame jf=new JFrame(“Example of ComboBox”);
JPanel jp1=new JPanel(new GridLayout(5,2));
JPanel jp2=new JPanel();
JPanel jp3=new JPanel(new GridLayout(2,2));
JLabel jl1,jl2,jl3,jl4;
JTextField jt1,jt2,jt3,jt4,jt5;
JButton jb1,jb2;
JComboBox jc1;
jl1=new JLabel(“ Name:”);
jl2=new JLabel(“Address:”); Self-Instructional
Material 253
Java Interface jl3=new JLabel(“Contact:”);
Components
jl4=new JLabel(“Country:”);
jt1=new JTextField(20);
jt2=new JTextField();
NOTES
jt3=new JTextField();
jt4=new JTextField();
jt5=new JTextField();
jb1=new JButton(“Submit”);
jb1.setSize(3,4);
jb2=new JButton(“Cancel”);
jc1=new JComboBox();
//creating an instance
//of ComboBox
jc1.addItem(“India”);
jc1.addItem(“USA”);
jc1.addItem(“UK”);
jc1.addItem(“Sri lanka”);
jc1.addItem(“China”);
jc1.addItem(“Nepal”);
jp1.add(jl1);
jp1.add(jt1);
jp1.add(jl2);
jp1.add(jt2);
jp1.add(jl3);
jp1.add(jt3);
jp1.add(jl4);
jp1.add(jc1);
jp2.add(jb1);
jp2.add(jb2);
jp3.add(jp1);
jp3.add(jp2);
jf.add(jp3);
jf.setVisible(true);
jf.setSize(400,300);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
ComboBoxExample combo= new ComboBoxExample();
}
Self-Instructional
}
254 Material
The output of the program is Java Interface
Components

NOTES

The default form

The form with enteries

13.4.13 JTree Class


It implements the graphical tree structure to display the various nodes in a
hierarchical manner. Each node represents the data or entity or some text. One
can design the graphical tree structure of directory structure present in a partition
by the use of methods and constructors in this class.
Normally, when one wants to display the entities in tree structure, then
two-stage approach is followed. In the first stage, the root is developed and in the
second stage, child is spawned from the root node. To create a root node, the
JTree() constructor is invoked. In the next stage, to spawn the child,
the constructor of DefaultMutableTreeNode() is invoked. The argument
passed to JTree class constructor can either be the entity of hash-table containing
keys and values or an element of vector.

Self-Instructional
Material 255
Java Interface Methods
Components
The various methods are:
add(Object node)
NOTES This method is invoked by the root node in order to add a node to the root node.
getNewLeadSelectionPath()
Each node present in the tree contains data or element. When one selects an item,
this method is used to return the path that describes the position of the element in
the tree. This method returns a TreePath object.
getLastPathcomponent()
This method returns the item or element that is selected by the user.
getPathCount()
This method is invoked to know the number of paths available to the particular
node.

Check Your Progress


1. What are the two types of swing containers?
2. What is JApplet?
3. Define panel.

13.5 PROGRAMMING USING PANES

In this section, we will discuss working the various pane classes, namely,
JLayeredPane, JTabbedPane and JSplitPane.
13.5.1 Layered Panes
A layered pane is a Swing container which is used to hold the various components
using the concept of layers. The components present in the upper layer overlaps
the components present in the lower layer. The layered pane is created using the
J L a y e r e d P a n e class. The only constructor of this class is
JLayeredPane().
Example 13.4: A program to demonstrate the use of JLayeredPane class
import java.awt.*;
import javax.swing.*;
class LayerExample extends JApplet
{
JFrame jf ;
JLayeredPane LPane;
Self-Instructional JButton first, second, third;
256 Material
LayerExample() Java Interface
Components
{
jf = new JFrame(“Layered Pane Example”);
LPane = new JLayeredPane();
NOTES
jf.getContentPane().add(LPane);
first = new JButton(“First”);
first.setBackground(Color.red);
first.setBounds(50,30,100,100);
second = new JButton(“Second”);
second.setBackground(Color.yellow);
second.setBounds(140,60,100,100);
third = new JButton(“Third”);
third.setBackground(Color.green);
third.setBounds(230,90,100,100);
LPane.add(first, new Integer(3));
LPane.add(second, new Integer(2));
LPane.add(third, new Integer(1));
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setSize(400,300);
jf.setVisible(true);
}
public static void main(String args[])
{
LayerExample le = new LayerExample();
}
}
The output of the program is

Self-Instructional
Material 257
Java Interface 13.5.2 Split Panes
Components
A split pane is a lightweight container that allows you to arrange two components
(only two) side by side horizontally or vertically in a single pane. The display areas
NOTES of both the components can also be adjusted at the runtime by the user. A split
pane is an object of JSplitPane class.
Some of the constructors defined by JSplitPane class are as follows:
JSplitPane()
JSpliPane(int orientation, boolean continuousLayout)
JSplitPane(int orientation, Component TopOrLeft, Component
BottomOrRight)
JSplitPane(int orientation, boolean continuousLayout ,
Component TopOrLeft, Component BottomOrRight)
where,
orientation specifies how components will be arranged—can have
one of the two values: HORIZONTAL_SPLIT and VERTICAL_SPLIT
continuousLayout can have one of the two values: true, if the
components are resizable when divider is moved, otherwise false (default value)

TopOrLeft specifies the object to be placed at top or left


BottomOrRight specifies the object to be placed at bottom or right
Example 13.5: A program to demonstrate the use of JSplitPane
import java.awt.*;
import javax.swing.*;
class SplitExample extends JApplet
{
JFrame jf ;
JSplitPane SPane;
JTextArea top, bottom;
String
sampleText = “A split pane is lightweight container
that allows you to arrange two components (only two)
side by side horizontally or vertically in a single
pane. The display areas of both the components can also
be adjusted at the runtime by the user.”;
SplitExample()
{
jf = new JFrame(“Split Pane Example”);
top = new JTextArea(sampleText);
top.setLineWrap(true);
bottom = new JTextArea(sampleText);
bottom.setLineWrap(true);
Self-Instructional SPane = new JSplitPane(
258 Material
JSplitPane.VERTICAL_SPLIT, top, bottom); Java Interface
Components

jf.getContentPane().add(SPane, BorderLayout.
CENTER);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE); NOTES
jf.setSize(400,300);
jf.setVisible(true);
}
public static void main(String args[])
{
SplitExample se = new SplitExample();
}
}
The output of the program is

Two Components Arranged Horizontally

Two Components Resized After the Slider is Moved


Self-Instructional
Material 259
Java Interface 13.5.3 Tabbed Panes
Components
Sometimes a situation may arise when there are lots of components that cannot be
accommodated in a single screen. In that case, tabbed pane is used to create tabs,
NOTES where each tab contains group of related components. When a particular tab is
clicked, the components of that tab are displayed in the forefront. Tabbed pane is
very common feature of GUI interfaces. It is commonly used in dialog boxes
containing lots of commands. A tabbed pane is an object of JTabbedPane
class.
Some of the constructors defined by JTabbedPane class are as follows:
JTabbedPane()
JTabbedPane(int tabPlacement)
where,
tabPlacement specifies the position of tabs—can have one of the
four values: TOP, BOTTOM, LEFT or RIGHT
Example 13.6: A program to demonstrate the use of JTabbedPane class
import java.awt.*;
import javax.swing.*;
class TabbedExample extends JApplet
{
JFrame jf;
JTabbedPane TPane;
JPanel panel1, panel2;
JLabel lab1, lab2;
JCheckBox city1, city2, state1, state2;
TabbedExample()
{
jf = new JFrame(“Tabbed Pane Example”);
TPane = new JTabbedPane();

jf.getContentPane().add(TPane, BorderLayout.
CENTER);
lab1 = new JLabel(“Select city:”);
city1 = new JCheckBox(“Chennai”,true);
city2 = new JCheckBox(“Mumbai”);
lab2 = new JLabel(“Select state:”);
state1 = new JCheckBox(“Tamil Nadu”, true);
state2 = new JCheckBox(“Maharashtra”);
panel1 = new JPanel(new GridLayout(1,3));
panel2 = new JPanel(new GridLayout(1,3));

Self-Instructional
260 Material
panel1.add(lab1); Java Interface
Components
panel1.add(city1);
panel1.add(city2);
panel2.add(lab2);
NOTES
panel2.add(state1);
panel2.add(state2);
TPane.addTab(“Cities”, panel1);
TPane.addTab(“States”, panel2);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setSize(400,200);
jf.setVisible(true);
}
public static void main(String args[])
{
TabbedExample se = new TabbedExample();
}
}
The output of the program is

Cities Tab in Front

States Tab in Front

Self-Instructional
Material 261
Java Interface
Components 13.6 JTable

A table is used to display data in the form of rows and columns. It can also allow
NOTES editing of data which is optional. By default, the columns of a table can be resized.
It can be accomplished by dragging the mouse along with their boundaries. The
columns can also be dragged to a new position. A table is an object of class
JTable which is a subclass of JComponent.
Some of the constructors defined by the JTable class are as follows:
JTable()
JTable(int rows, int cols)
JTable(Object[][] rowData, colNames)
where,
rows represents the number of rows with empty cells
cols represents the number of columns with empty cells
rowData represents the two-dimensional array containing the data of
rows
colNames specifies the name of the columns
Example 13.7: A program to demonstrate the use of a table
import javax.swing.*;
class SwingTable extends JApplet
{
public static void main(String str[])
{
JFrame jf = new JFrame(“Demo of table”);
String data[][] = {
{“1”, “Premashis”, “89%”},
{“2”, “Preeti”, “88%”},
{“3”, “Pooja”, “87%”},
{“4”, “Niti”, “86%”},
{“5”, “Shruti”, “85%”},
{“6”, “Vriti”, “84%”},
{“7”, “Surender”, “83%”},
{“8”, “Rajesh”, “82%”},
{“9”, “Raja”, “81%”},
{“10”, “Meenu”, “80%”},
{“11”, “Uma”, “79%”}
};
String fields[] = {“

Self-Instructional
262 Material
RollNumber”, “Name”, “Percentage”}; Java Interface
Components
JTable jt = new JTable(data,fields);
JScrollPane pane = new JScrollPane(jt);
jf.add(pane);
NOTES
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setSize(300,200);
jf.setVisible(true);
}
}
The output of the program is

Check Your Progress


4. What is a layered pane?
5. What is split pane?

13.7 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. There are two types of containers namely, top-level containers and lightweight
containers.
2. JApplet is a class that represents the Swing applet. It is a subclass of Applet
class and must be extended by all the applets that use Swing.
3. Panel is a container to hold different Swing components. One can add any
number of components to a panel and there can be multiple panels in the
same frame.
Self-Instructional
Material 263
Java Interface 4. A layered pane is a Swing container which is used to hold the various
Components
components using the concept of layers.
5. A split pane is a lightweight container that allows you to arrange two
components (only two) side by side horizontally or vertically in a single
NOTES
pane.

13.8 SUMMARY

 Like AWT GUI, Swing GUI is also based on the concept of components
and containers. A container is a type of component that can hold other
components.
 Swing component is an independent control, such as button, label, text
field, etc. They need a container to display themselves. Swing components
are derived from JComponent class.
 There are two types of containers namely, top-level containers and
lightweight containers.
 A top-level container, as the name suggests, lies at the top of the containment
hierarchy. The top-level containers are JFrame, JApplet, and
JDialog. These containers do not inherit JComponent class but
inherit the AWT classes’ Component and Container.
 Lightweight containers lie next to the top-level containers in the containment
hierarchy. They inherit JComponent.
 JApplet is a class that represents the Swing applet. It is a subclass of Applet
class and must be extended by all the applets that use Swing.
 A button, also known as push button, is an active control that has a 3-
dimensional appearance. It triggers an event when it is clicked or activated.
 Swing provides a variant of push button called ToggleButton which
has two states: pushed and released. When ToggleButton is pressed
for the first time, it remains pressed and it is released only when it is pressed
for the second time.
 A ScrollPane is a container that represents a small area to view other
component.
 A ComboBox is a combination of a list component and text field
component. It can consist of more than one item, however, displays only
one item at any point of time.
 A table is an object of class JTable which is a subclass of
JComponent.

Self-Instructional
264 Material
Java Interface
13.9 KEY WORDS Components

 Lightweight components: The Swing components that are written entirely


in Java and do not depend on native peers. NOTES
 Pluggable look and feel: It is a feature that allows customizing the look
and feel of the application and applets to the standard looks like, Windows
and Motif.
 Component: An independent control, such as button, label, text field, etc.

13.10 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short-Answer Questions
1. What are swing components and containers?
2. What are the constructors defined by JPanel?
3. Write a note on JTabbedPane and JSplitPane.
Long-Answer Questions
1. Explain the top-level containers.
2. Write a program to demonstrate the creation of swing application.
3. Explain the following interface components.
(i) JApplet
(ii) JTable
(iii) JTree
(iv) Button

13.11 FURTHER READINGS

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
Material 265
AWT Classes and
Working with Graphics
UNIT 14 AWT CLASSES AND
WORKING WITH
NOTES
GRAPHICS
Structure
14.0 Introduction
14.1 Objectives
14.2 Introducing Abstract Window Toolkit
14.2.1 Component Class
14.2.2 Container Class
14.3 Working with Graphics
14.3.1 Using Graphics Class
14.3.2 Using Color Class
14.3.3 Using Font Class
14.3.4 Using Image Class
14.4 Answers to Check Your Progress Questions
14.5 Summary
14.6 Key Words
14.7 Self Assessment Questions and Exercises
14.8 Further Readings

14.0 INTRODUCTION

In this unit, you will learn about the AWT (Abstract Window Toolkit). Abstract
Window Toolkit provides several graphics, windowing and user interface tools
which are used to develop GUI of applets as well as stand-alone applications
running in GUI environment. In order to use the classes and interfaces defined in
AWT, java.awt.* package needs to be imported. You will also learn how
to create applet that uses various classes to draw shapes, images and display text.

14.1 OBJECTIVES

After going through this unit, you will be able to:


 Discuss the features of AWT package
 Explain the methods of component and container class
 Understand the significance of Graphics class in applets
 Learn and use various methods defined in the Graphics class

Self-Instructional
266 Material
AWT Classes and
14.2 INTRODUCING ABSTRACT WINDOW Working with Graphics

TOOLKIT

An end user interacts with applications via an interface. Java Development Kit NOTES
(JDK) provides a package called the Abstract Window Toolkit (AWT) that enables
you to design user-friendly interfaces. The AWT package is a collection of classes
and methods that allow an end user to design and manage Graphical User Interface
(GUI) based applications. AWT is used to support Applet windows and it also
helps in creating independent windows, such as frame window or panel window
that run in GUI environment.
This unit describes the different classes of the AWT package. It explains
how to create and set properties for a frame window. This unit also discusses how
to manage fonts and colors in a frame window. The unit explains how to design
and implement graphics, such as lines, rectangles, ellipses and polygons in a frame
window or panel.
AWT is Java’s largest package and can be included in Java program by
giving the java.awt.* statement. It is a part of Java Foundation Classes
(JFC). AWT has 63 classes and 14 interfaces used for creating user interfaces.
You can use AWT classes and interfaces to design and manage components, such
as lines, rectangles, ellipses, polygons, text boxes, command buttons, lists, menus
and scroll bars.
Features of the AWT package are:
 It provides graphics and imaging tools that enable you to develop GUI.
 It provides layout managers that enable an end user to develop window
layouts.
 It supports event handling. For example, an error occurred in between
execution of a program.
The java.awt package contains all the classes used for developing
graphical interfaces. These classes are organized in a hierarchical order. Figure
14.1 shows the hierarchy of classes in the java.awt package.
The above figure shows the multi-level inheritance structure of AWT classes
and subclasses. Multi-level inheritance means that a derived class has more than
one base class, for example, Frame class is derived from Window class, which
is derived from the Container class. Component class and Container
class are the two important classes of AWT package. Component class
Consists of subclasses and methods for creating Components, such as
command button, text boxes and labels. The container class enables you to create
objects, such as frames that contain components.

Self-Instructional
Material 267
AWT Classes and
Working with Graphics

NOTES

Fig. 14.1 AWT Class Hierarchy

All other classes are the subclasses of these two classes. Each subclass
inherits the characteristics of its super class. Apart from inheriting the functionality
of the upper class, it also has some additional functionality that is unique to its
level.
14.2.1 Component Class
Component class is at the top of the AWT inheritance class hierarchy. It is the
super class and all other classes in the hierarchy inherit its characteristics directly
or indirectly. Component class is an abstract class that encapsulates all the
properties of a visual component or object.
Component class defines various methods that are used to handle events,
define the layout of component, providing content of the component and repainting
the window in between the execution of the program. The methods that the objects
of the components class use include:
 void setSize (int width, int height): Defines the
size of a component in terms of width and size.
 void setLocation (int x, int y): Specifies the
location of a component, in the window, at the position specified by the
x and y coordinates.
 void setBounds (int x, int y, int width, int
height): Sets the bounds of a component in terms of position x & y
Self-Instructional and size in terms of width and height.
268 Material
 void setForeground (Color B): Sets the foreground AWT Classes and
Working with Graphics
color of the component.
 void setBackground (Color B): Sets the background
color of the component.
NOTES
14.2.2 Container Class
Container class is the subclass of Component class and its objects inherit
all the characteristics of the Component class. Therefore, container objects
can also be used as component objects. The objects of Container class are
also known as containers. This class supports nested container objects. You can
place one container object inside another container object, if required.
It is the function of the container object to determine the position of other
component objects that it contains. Layout managers are responsible for performing
this function.
Containers use the add() function to nest other components inside it.
Methods that are used to manipulate components on container objects are:
 void add (object o): Nests a component or an object inside
a container.
 void remove (object o): Removes a component or an
object from a container.
 void removeALL(): Removes all the components or objects that
are placed inside a container.
Panel Class
Panel is a subclass of the Container class and is used for organizing
components. Panel class inherits methods from its super class rather than defining
them. Panel class uses the add() method to nest components inside it.
Panel class is the super class of Applet class. Panel class does not
contain border, title bar or menu bar. It supports nested panel objects. A panel
container object can have more than one panel and different panels can have
different layouts.
In addition to the add() method, the methods that the Panel class uses
are:
 panel(): Creates an object of the Panel class.
 setLocation(): Determines the position of a component inside
the panel.
 setSize(): Sets the size of a component in terms of width and
height.
 setBounds(): Sets the bounds of a component in terms of position
and size.
Self-Instructional
Material 269
AWT Classes and Window Class
Working with Graphics
Window is another subclass of the Container class. Its objects are called
windows and they are the top-level containers. Window objects are not contained
NOTES in any other object.
You can place window objects directly on the desktop. The Window
class has two subclasses, frames and dialog.
The methods used by the Window class include:
 void pack(): Adjusts the layout of a window according to the size
and number of components it holds.
 void show(): Displays a window on the screen and places the
window on the top of other windows that may be open on the desktop.
 void dispose(): Deallocates the memory allotted to a window.
Frame Class
Frame is the subclass of the Window class. The frame class enables you to
create pop-up windows. Frame class is an important class of AWT that enables
an end user to create stand-alone applications. Frame window has a border, title
bar and menu bar. Default layout for frame is border layout. Its objects respond to
mouse, keyboard and focus events.
Frame objects are created either through an Applet program or through any
other Java program using its constructor. If a frame object is created in an applet,
it displays a message like Java Applet Window. Objects can be added to a frame
using the add() method.
Canvas Class
Canvas class is another type of Window class and is used to create blank
windows. Canvas objects are used for the drawing purpose only, but they can
enable an end user to create customized components. Canvas constructor takes
no arguments and creates an empty drawing area. Canvas class does not define
any method. It inherits the paint() method from the Component class that
needs to be overridden to provide the drawing functionality.

14.3 WORKING WITH GRAPHICS

Java also allows creating applet that uses various classes to draw figures of different
shapes, add images, display text in different fonts and styles, use and create various
colors, etc. Some of these classes are discussed in this section.
14.3.1 Using Graphics Class
The Graphics class provides different methods to draw and fill various shapes.
Self-Instructional
270 Material
Drawing Lines AWT Classes and
Working with Graphics
A line can be drawn using the drawLine() method of the Graphics class.
This method takes four parameters which represent the coordinates of the end
points of the line. NOTES
The general form of the drawLine() method is
void drawLine(int a1, int b1, int a2, int b2)
where,
a1, b1 is the coordinate of the starting points of the line
a2, b2 is the coordinate of the starting points of the line
For example, the statement gra.drawLine(20,100,90,100)
will draw a straight line from the coordinate point (20,100) to (90,100)
as shown in Figure 14.2.

(20, 100) (90, 100)

Fig. 14.2 A Straight Line Having Coordinates (20,100) and (90,100)

Drawing and Filling Rectangles


A rectangle can be drawn by using the drawRect() method. This method also
takes the four parameters.
The general form of the drawRect() method is
void drawLine(int a1, int b1, int w, int h)
where,
a1, b1 is the coordinate of the top left corner of the rectangle
w is the width of the rectangle
h is the height of the rectangle
For example, the statement gra.drawRect(20,20,50,30) will draw a
rectangle starting at (20,20) with width of 50 pixels and height of 30 pixels
as shown in Figure 14.3.
(20, 20)

30 (height)

50 (width)

Fig. 14.3 A Rectangle with Width 50 pixels and Height 30 pixels

Note that the drawRect() method draws only the boundary of the
rectangle. To draw a solid (filled) rectangle, fillRect() method is used. This
method also takes four parameters similar to the drawRect() method. Self-Instructional
Material 271
AWT Classes and To draw a solid rectangle the having same parameters as above, you can
Working with Graphics
use the statement gra.fillRect(20,20,50,30) which draws the
rectangle as shown in Figure 14.4.

NOTES (20, 20)

30 (height)

50 (width)
Fig. 14.4 A Filled Rectangle with Width 50 pixels and Height 30 pixels

A rounded, outlined rectangle can be drawn by using the


drawRoundRect() method. This method takes the six parameters.
The general form of the drawRoundRect() method is
void drawRoundRect(int a1, int b1, int w, int h, int
xdia, int ydia)

(a1, b1) h(height )

w(width)
xdia, ydia (arc)

Fig. 14.5 A Rounded Rectangle

where,
xdia is the diameter of the rounding arc (along X-axis)
ydia is the diameter of the rounding arc (along Y-axis)
Similarly, a rounded filled rectangle can be drawn using
drawfillRoundRect() method. This method also takes six parameters
similar to the drawRoundRect() method.
Note: All the shapes are drawn relative to the Java’s coordinate system. The
origin (0, 0) of the coordinate system is located at its upper-left corner such that
the positive x values are to its right and the positive y values are to its bottom.
Drawing and Filling Ellipses and Circles
An ellipse can be drawn using the drawOval() method. The ellipse is drawn
within an imaginary bounding rectangle. This method takes four arguments in which
the first two represent the top left corner of the bounding rectangle and the next
Self-Instructional
272 Material
two represent the width and height of the oval or the bounding rectangle (see AWT Classes and
Working with Graphics
Figure 14.6).
The general form of the drawOval() method is
void drawOval(int a1, int b1, int w, int h) NOTES
where,
a1, b1 is the coordinate of the top left corner of the bounding rectangle.
w is the width of the bounding rectangle.
h is the height of the bounding rectangle.

height

width

Fig. 14.6 An Ellipse

Similarly, a circle can be drawn using this method but the dimension of
width and height should be the same. That is, the bounding rectangle must be a
square.
Similar to rectangle methods, the drawOval() method draws the
boundary of an oval and the fillOval() method draws a solid oval.
Drawing Arcs
An arc can be drawn using the drawArc() method. This method takes six
arguments in which the first four are the same as the arguments of the
drawoval() method and the next two represent the starting angle of the arc
and the sweep angle around the arc, respectively.
The general form of the drawArc() method is
void drawArc(int a1, int b1, int w, int h, int strt_angle,
int sweep_angle)
where,
a1,b1 is the coordinate of the top left corner of the bounding rectangle.
w is the width of the bounding rectangle.
h is the height of the bounding rectangle.
strt_angle is the starting angle of the arc (in degrees).
sweep_angle is the number of degrees (angular distance) around the arc (in
degrees).
The arc shown in Figure 14.7 has the starting angle as 00 degrees and sweep angle
as 1350.
Self-Instructional
Material 273
AWT Classes and 90o
Working with Graphics Arc

180o 135o
NOTES
0o

270o

Fig. 14.7 An Arc of 1350 Sweep Angle

You can also draw filled arcs using the fillArc() method.
Drawing Polygons
A polygon is a closed geometrical figure, which can have any number of sides. A
polygon can be drawn by using the drawPolygon() method. This method
takes the three parameters.
The general form of the drawPolygon() method is
void drawPolygon(int a[], int b[], int n)
where,
a[] is the array of integers having x-coordinates.
b[] is the array of integers having y-coordinates.
n is the total number of coordinate points required to draw a polygon.
(a1, b1) (a2, b2)

(a3, b3)
(a6, b6)

(a5, b5) (a4, b4)

Fig. 14.8 A Polygon with Six Sides

Example 14.1: An applet code to demonstrate the use of various methods of


Graphics class
import java.awt.*;
import java.applet.*;
public class GraphicsExample extends Applet
{
public void paint(Graphics gra)
Self-Instructional
274 Material
{ AWT Classes and
Working with Graphics
gra.drawRect(10,40,80,40);
gra.fillRect(130,40,80,40);
gra.drawRoundRect(250,40,80,40,8,8);
NOTES
gra.fillRoundRect(370,40,80,40,8,8);

gra.drawOval(0,125,80,40);
gra.fillOval(120,125,80,40);

gra.drawArc(240,125,80,40,0,180);
gra.fillArc(370,125,80,40,0,180);

int x[]={100,150,200,170,130,100};
int y[]={250,200,250,300,300,250};
int n=x.length;
gra.drawPolygon(x,y,n);

gra.drawOval(270,200,80,80);
gra.fillOval(380,200,80,80);

gra.drawLine(480,50,480,350);
}
}
The HTML code for GraphicsExample is
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<APPLET
CODE=”GraphicsExample.class”
WIDTH =”600"
HEIGHT=”350>
</APPLET>
</CENTER>
</BODY>
</HTML>

Self-Instructional
Material 275
AWT Classes and The output of the HTML code is as follows:
Working with Graphics

NOTES

14.3.2 Using Color Class


The Color class provides various methods to use any color you want in display.
It defines various color constants, which can be directly used only by specifying
the color of your choice. In addition, the Color class allows creation of millions
of colors. The Color class contains three primitive colors, namely, red, blue
and green; all other colors are a combination of these three colors.
One of the constructors that is used to create color of your choice is
Color(int red, int green, int blue)
where,
red, green, blue can take any value between 0 and 255.
Setting Background and Foreground Color
To set the color of the background of an applet window, setBackground()
method is used.
The general form of the setBackground() method is
void setBackground(mycolor)
Similarly, to set the foreground color to a specific color, that is, the color of
text, setForeground() method is used.
The general form of the setForeground() method is
void setForeground(mycolor)
where,
mycolor is one of the color constants or the new color created by the user
Self-Instructional
276 Material
The list of color constants is given below: AWT Classes and
Working with Graphics
 Color.red
 Color.orange
 Color.gray
NOTES
 Color.darkGray
 Color.lightGray
 Color.cyan
 Color.pink
 Color.white
 Color.blue
 Color.green
 Color.black
 Color.yellow
Example 14.2: An applet code to demonstrate the use of Color class
import java.applet.*;
import java.awt.*;
public class ColorExample extends Applet
{

public void paint(Graphics gra)


{
//creating new colors
Color c1=new Color(0,0,255);
Color c2=new Color(100,220,190);
setBackground(Color.white);//setting background color

//drawing a line of color c1


gra.setColor(c1);
gra.drawLine(10,20,150,60);

//drawing a solid oval of color c2


gra.setColor(c2);
gra.fillOval(10,50,100,200);

//drawing a rectangle of red color


gra.setColor(Color.red);
gra.drawRect(150,120,60,120);
}
}

Self-Instructional
Material 277
AWT Classes and The HTML code for ColorExample is
Working with Graphics
<HTML>
<HEAD>
</HEAD>
NOTES
<BODY>
<CENTER>
<APPLET
CODE=”ColorExample.class”
WIDTH =”600"
HEIGHT=”250">
</APPLET>
</CENTER>
</BODY>
</HTML>

The output of the HTML code is as follows:

14.3.3 Using Font Class


The Font class is used to apply different font styles to the text. To select or apply
a new font, a font object is required to be constructed.
The general form of the constructor of Font class is
Font(String font_name, int font_style, int font_size)
where,
font_name is the name of the font.
font_style is font style.
font_size is the size of the font in points.

Self-Instructional
278 Material
Some other methods of Font class are listed in Table 14.1 AWT Classes and
Working with Graphics
Table 14.1 Methods of Font class

Method Description
static Font getFont() returns the currently selected font NOTES
int getSize() returns the size of the font
String getName() returns the name of the font
int getStyle() returns the style of the font
String getFamily() returns the name of the family of the font

Example 14.3: An applet code to demonstrate the use of Font class


import java.applet.*;
import java.awt.*;
public class FontExample extends Applet
{
public void paint(Graphics gra)
{
Font MyFont=new Font(“Courier New”, Font.BOLD,16);
gra.setFont(MyFont);
gra.drawString(“Hello Java”,20,100);
Font f=gra.getFont();
String fontName=f.getName();
gra.drawString(“Font name is :”+fontName,20,140);
String fontFamily=f.getFamily();
gra.drawString(“Font family is
:”+fontFamily,20,160);
int fontSize=f.getSize();
gra.drawString(“Font size is :”+fontSize,20,180);
int fontStyle=f.getStyle();
gra.drawString(“Font style is :”+fontStyle,20,200);

}
}
The HTML code for FontExample is
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<APPLET
CODE=”FontExample.class”
WIDTH =”600"
HEIGHT=”250">
Self-Instructional
Material 279
AWT Classes and </APPLET>
Working with Graphics
</CENTER>
</BODY>
</HTML>
NOTES
The output of the HTML code is as follows:

14.3.4 Using Image Class


The Image class is used to load and display images. To load an image, the
getImage() method of the Image class is used and to display the image the
drawImage() method of the Graphics class is used.
The general form of the getImage() method is
Image getImage(URL pathname, String filename)
Image getImage(URL pathname)
where,
pathname is the address of the image file on Web. When the image file and the
source file are in the same directory, getCodeBase() method is used as first
parameter to the method.
filename is the name of the image file.

The general form of the drawImage() method is


boolean drawImage(Image image, int startx, int starty,
int width, int height, ImageObserver img_obj)
where,
image is the image to be loaded in the applet.
startx is the pixels space from the left corner of the screen.
starty is the pixels space from the upper corner of the screen.
width is the width of the image.
height is the height of the image.
Self-Instructional
img_obj is object of the class that implements ImageObserver interface.
280 Material
Example 14.4: An applet code to demonstrate the use of Image class AWT Classes and
Working with Graphics
import java.applet.*;
import java.awt.*;
public class ImageExample extends Applet
NOTES
{
private Image pic;
public void init()
{
pic=getImage(getCodeBase(), “java_pic.gif”);
}
public void paint(Graphics gra)
{
gra.drawImage(pic,150,50,120,200,this);
}
}
The HTML code for ImageExample is
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<APPLET
CODE=”ImageExample.class”
WIDTH =”600"
HEIGHT=”250">
</APPLET>
</CENTER>
</BODY>
</HTML>
The output of the HTML code is as follows:

Self-Instructional
Material 281
AWT Classes and
Working with Graphics
Check Your Progress
1. What are the two important classes of AWT package?
NOTES 2. Define container class.
3. Which method is used to draw an image on an applet?

14.4 ANSWERS TO CHECK YOUR PROGRESS


QUESTIONS

1. Component class and container class are the two important classes of
AWT package.
2. Container class is the subclass of component class and its objects
inherit all the characteristics of the component class.
3. The Image class is used to load and display images. To load an image,
the getImage()method of the Image class is used and to display the
image the drawImage() method of the Graphics class is used.

14.5 SUMMARY

 Java Development Kit (JDK) provides a package called the Abstract


Window Toolkit (AWT) that enables you to design user-friendly interfaces.
The AWT package is a collection of classes and methods that allow an end
user to design and manage Graphical User Interface (GUI) based
applications.
 The java.awt package contains all the classes used for developing
graphical interfaces.
 Component class and container class are the two important classes
of AWT package.
 Container class is the subclass of component class and its objects
inherit all the characteristics of the component class.
 Java allows creating an applet that uses various classes to draw figures of
different shapes, add images, display text in different fonts and styles, use
and create various colors and so on.
 The Graphics class provides different methods to draw and fill various
shapes.
 The Color class provides various methods to use any color you want in
display.

Self-Instructional
282 Material
 The Font class is used to apply different font styles to the text. AWT Classes and
Working with Graphics
 The Image class is used to load and display images. The Graphics
class also provides methods to add images to the applet.
NOTES
14.6 KEY WORDS

 Container class: It is the subclass of component class and its objects


inherit all the characteristics of the component class.
 The Color class: It provides various methods to use any color you
want in display by defining various color constants, which can be directly
used only by specifying the color of your choice.

14.7 SELF ASSESSMENT QUESTIONS AND


EXERCISES

Short-Answer Questions
1. Discuss the features of AWT package.
2. Write a note on.
(i) Panel class
(ii) Window class
(iii) Frame class
(iv) Canvas class
Long-Answer Questions
1. Explain the hierarchy of classes in the java.awt package.
2. Explain the various methods of component and container class.
3. Write a program to display the following output:

4. How can you add an image to an applet? Explain with an example.

Self-Instructional
Material 283
AWT Classes and
Working with Graphics 14.8 FURTHER READINGS

Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
NOTES Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.

Self-Instructional
284 Material

You might also like