Sie sind auf Seite 1von 371

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS1401 – INTERNET PROGRAMMING

BRANCH – CSE SEMESTER - VII

UNIT – I: BASIC NETWORK AND WEB CONCEPTS

Internet standards – TCP and UDP protocols – URLs – MIME – CGI – Introduction to
SGML.

UNIT – II: JAVA PROGRAMMING

Java basics – I/O streaming – files – Looking up Internet address – Socket programming –
Client/Server programs – E-mail client – SMTP – POP3 programs – web page retrieval –
protocol handlers – content handlers – applets – image handling – Remove Method
Invocation.

UNIT – III: SCRIPTING LANGUAGES

HTML forms – frames – tables – web page design – Java Script introduction – control
structures – functions – arrays – objects – simple web applications

UNIT – IV: DYNAMIC HTML

Dynamic HTML – introduction – cascading style sheets (CSS) – object model and
collections – event model – filters and transition – data binding – data control – ActiveX
control – handling of multimedia data.

UNIT – V: SERVER SIDE PROGRAMMING

Servlets –deployment of simple servlets – web server (Java web server / Tomcat / Web logic)
– HTTP GET and POST requests – session tracking – cookies – JDBC – simple web
applications – multi-tier applications.
TEXT BOOKS

1. Deitel, Deitel and Nieto, “Internet and WWW – how to program”, Pearson Education
Publishers, 2000.

2. Elliotte Rusty Harold, “Java Network Programming”, O’Reilly Publishers, 2002

REFERENCES

1. R. Krishnamoorthy & S. Prabhu, “Internet and java programming”, New Age


International publishers, 2004.

2. Thomno A. Powell, “The complete reference HTML and XHTML”, Fourth Edition,
Tata McGraw Hill, 2003.

3. Naughton, “The Complete Reference – Java2”, Tata McGraw-Hill, 3rd Edition, 1999.

2
CS1401 – INTERNET PROGRAMMING

UNIT I – BASIC NETWORK AND WEB CONCEPTS

1.1 Internet Standards


1.2 TCP and UDP protocols
1.3 URLs
1.4 MIME
1.5 CGI
1.6 Introduction to SGML.

1.1INTERNET STANDARDS

The Internet is a system that allows the computers all over the world to communicate
with each other. The Internet is a network of network that connects computers all over
the world.

The computers on the Internet can talk to each other because they are networked.
All the systems in the network can share or exchange information electronically because
of the network connection only. The systems are connected through local and long
distance telephone lines, and some even use wireless satellite communications.

CHARACTERISTICS OF INTERNET

• It is a Loose Organization. Internet is not a big organization of company or club.


It is a Loose Organization. The computers on the internet are controlled by their
owners. Nobody controls the Internet.

• It is a Relaxing Place. Internet enables users to exchange information in an open


and public way. Internet provides various information about Film, TV, Medicine,
Nutrition, Astrology, Politics, Employment, Games, and Mails etc.

• It is a Business Tool Big companies relies computers in internet for business


communication. Nowadays, several organizations are running their business
through internet for various purposes like exchange of information, material
specifications, payments and billings etc.

• It is an Information Pool Internet is a pool of information. The information the


users in need, it can be easily located and retrieved from the internet.

3
• Internet satisfies the various levels of users like kids, from students to business
professionals, from small industries to multinational Companies Researchers and
Government Organizations including Military Services.

INTERNET STANDARD (STD)

• In computer network an Internet Standard (STD) is a normative specification or set


of rules or a technology or methodology applicable to the Internet.
• Internet Standards are created and published by the Internet Engineering Task Force
(IETF).
• An Internet Standard is a Special Request For Comments (RFC) or set of RFCs.
• An RFC that is to become a Standard or part of a Standard begins as an Internet Draft,
and is later (usually after several revisions) accepted and published by the RFC Editor
as a RFC and labeled a Proposed Standard.
• RFC is labelled a Draft Standard, and finally a Standard.
• Collectively, these stages are known as the standards track, and are defined in RFC
2026.
• The label Historic is applied to deprecated standards-track documents or obsolete
RFCs that were published before the standards track was established.
• Only the IETF, represented by the Internet Engineering Steering Group (IESG), can
approve standards-track RFCs.
• The definitive list of Internet Standards is maintained in Internet Standards Document
STD 1: Internet Official Protocol Standards.

EXPERIMENTAL STANDARD

A proposal after being submitted is considered as an experimental standard.

4
PROPOSED STANDARD

A Proposed Standard (PS) is Stable well-understood, has received Significant


community review, and appears to enjoy enough community interest to be considered
valuable. It is provided by IETF (Internet Engineering Task Force).

IETF include TCP/IP, MIME and SMTP. IETF standards are published as Internet
Draft and Request For Comments (RFCs). It deals from informational documents to
detailed specification of standard Internet Protocol. RFCs documents are published with the
help of Internet Engineering Steering Group (IESG).

DRAFT STANDARD

A Specification from which at least two independent and interoperable


implementations from different code bases have been developed, and for which sufficient
successful operational experience has been obtained, may be elevated to the Draft Standard
(DS) level.

A Draft Standard is normally considered to be a final specification, and changes are


likely to be made only to solve specific problems encountered. In most circumstances, it is
reasonable for vendors to deploy implementations of Draft Standards into a disruption
sensitive environment.

EDIT STANDARD

A Specification for which significant implementation and successful operational


experience has been obtained may be elevated to the Internet Standard (STD) level. An
Internet Standard, which may simply be referred to as a Standard, is characterized by a high
degree of technical maturity and by a generally held belief that the specified protocol or
service provides significant benefit to the Internet community

WHY NETWORKING IN JAVA IS ESSENTIAL?

• Java is the first programming language designed from the ground up with networking
in mind.

• As the global internet continues to grow, java is uniquely suited to build the next
generation of network applications.

5
• Java is platform independence, it also provides security. The Java programs compiled
one computer can be executed in some other computer because of the platform
independency.

• It makes network programs easy. It is easy for java applications to send and receive
data across the internet. The client-server implementation using HTTP, FTP and
POP3 is also very easy using Java programs.

• It is also possible for applets to communicate across the internet, though they are
limited by security restrictions.

WHAT CAN A NETWORK PROGRAM DO?

• Networking adds a lot of power to simple programs. With networks, a single program
can retrieve information stored in millions of computers located anywhere in the
world.

• A single program can communicate with tens of millions of people. A single program
can harness (tie together) the power of many computers to work on one problem.

• Network applications generally take one of several forms. The distinction is clients
and servers.

• In the simplest case, clients retrieve data from a server and display it. More complex
clients filter and reorganize data, repeatedly retrieve changing data, send data to other
people and computers, and interact with peers in real time for chat, multiplayer
games, or collaboration.

HOW JAVA IS USEFUL IN RETRIEVING DATA AND TO DISPLAY?

• A network client retrieves data from a server and shows it to a user.

• Web browsers are limited. They can talk to only certain kinds of servers (Generally
web, FTP, gopher, and perhaps mail and news servers.

• They can understand and display certain kinds of data (generally text, HTML, and a
few standard image formats.)

• A java program can send SQL queries in a database.

6
• A Java program can connect to a network time-server to synchronize itself with an
atomic clock. A java program can speak any custom protocols it needs to speak,
including the one to control the HAWC (High Resolution Airborne Wideband
Camera) on the Stratospheric Observatory for Infrared Astronomy (SOFIA).
• A java program can use the full power of a modern graphical user interface to show
this data to the user and get a response to it.

1.1.2 REPEATEDLY RETRIEVE DATA

• Used sending data continuously.


• File storage
• Massively parallel computing
• Smart forms – includes various controls like text box, radio button, text area control
etc.
• Peer-to-Peer Interaction – used in various client/server models.
• Games – Combine the ability to easily include networking in your programs with
java’s powerful graphics and you have the recipe for truly awesome multiplayer
games.
• Chat – Used in various chat applications.
• Whiteboards – Java programs are not limited to sending ext and data across the
network. A number of programmers have developed whiteboard software that allows
users in diverse locations to draw on their computers.
• Servers Java applications can listen for network connections and respond to them.
This makes it possible to implement servers in Java. Both Sun and W3C have written
web servers in Java designed to be as fully functional and fast as servers written in C.
• Various protocols are available in Server for communication like HTTP, FTP, and
TCP etc.

7
ELECTROIC COMMERCE (E-COMMERCE)

1. Shopping sites have proven to be one of the few real ways to make money from
consumers on the web.
2. Although many sites accept credit cards through HTML forms, the mechanism is
clunky (clubbing).

1.1.3 THE LAYERS OF A NETWORK

Application Layer Logical path Application Layer

Transport Layer (TCP, UDP) Transport Layer (TCP, UDP)

Internet layer (IP) The Host to Internet layer (IP)


Physical path Host Physical path(Ethernet, FDDI
Layer etc

THE HOST TO NETWORK LAYER

1. This layer is also referred as data link layer, or network-interface layer.

2. This layer defines how a particular network interface, such as an Ethernet card or PPP
connection, sends IP data grams over its physical connection to the local network and
the world.

3. The part of H to H layer made up of the hardware used to connect different computer
(wires, fiber-optic cables, microwave relays, or smoke signals) is sometimes called
the physical layer of the network.

THE INTERNET LAYER

1. The internet protocol is the most widely used network layer protocol in the world and
the only network layer protocol java understands.

8
2. Data is sent across the internet layer in packets called data grams. Each IP
datagram contains a header from 20 to 60 bytes along a payload that contains up to
65,515 bytes of data.

TRANSPORT LAYER

Data grams packets are generated and transported only via this layer.

APPLICATION LAYER

The layer that delivers data to the user is called the application layer. The 2 lower
layers all work together to define how data is transferred from one computer to
another.

1.1.4 IP ADDRESSES AND PORTS

1. It is very difficult to remember the IP address of each and every node.


2. It order to avoid this problem domain names are used.
3. Example google.com, rediff.com etc.
PORTS
1. Ports are used in receiving and sending data to another server or client.
2. Port number can take the value in the range of 0 to 65535.
3. Example for port numbers

Protocol Port Protocol Purpose

Echo 7 TCP/UDP Echo is a test protocol used to verify that 2 machines are
able to connect by having one echo back the other’s
input.
Discard 9 TCP/UDP Discard is a less useful test protocol in which all data
received by the server is ignored.
FTP 21 For File Transfer Protocol
SMTP 25 For Simple Mail Transfer Protocol
HTTP 80 For Hyper Text Transfer Protocol
POP3 110 For Post Office Protocol
NTP 119 Usenet news transfer is more formally known as the
Network News Transfer Protocol
RMI 1099 This is the registry service for Java Remote Objects.
Registry

9
1.1.5 INTERNET ADDRESS CLASS

1. Internet addresses are assigned to different organizations by the Internet


Assigned Numbers Authority (IANA).

2. ISP – Internet Service Providers gives block addresses.

3. Class C address block specifies the first 3 bytes of address, for example
199.1.32. This allows room for 254 individual addresses from 199.1.32.1 to
199.1.32.254

4. Class B address specifie only the first 2 bytes of the addresses.

5. There are also Class D and E addresses used for IP multicast group.

6. Each node on the Internet has a unique number and it is called as Internet
Protocol Address or IP address.

7. The format of IP address is A.B.C.D

Where A, B, C and D values will be in the range of 0 to 255 and each


one is called as an octet.

Examples are as follows:

1. 195.244.178.145 Valid IP address

2. 155.233.254 Invalid IP address because the fourth octet


is missed (should be the combination of
four octets. Example 128.156.252.250)

3. 255.0.258.158 Invalid because the third octet exceeds 255

10
1.1.6 INTERNET SERVICE PROVIDER

An ISP is an organization that provides individuals and other companies’ access to the
Internet and other related services. They are three types of connections seen in
homes/organizations. They are

1. ISDN – Integrated Services Digital Network


2. Cable Modem
3. A dial-up Telephone Modem

FIREWALLS

The hardware and software that sits between the Internet and the local network, checking all
the data that comes and goes out is called “firewalls”.

PROXY SERVERS

Proxy servers are related to firewalls prevents hosts on a network from making direct
connections to the outside world, a proxy server can act as a go-between.

Thus a machine that is prevented from connecting to the external network by a firewall
would make a request for a web page from the local proxy server instead of requesting the
web page directly from the remote web server.

1.1.7 THE CLIENT/SERVER MODEL - MODEL 1 - CLIENT/SERVER

Web Server

Request
Internet

Response
Client

1. Model 1 is the simplest of client/server model in web architecture.

11
2. The client sends Request to the Web Server through Internet.

3. The Request is acknowledged by the Web Server and it sends Responses to the Client.

4. Now the Server sends the Requested information to the Client from Web Server.

5. At the end of data transfer, the Client disconnects from the Server.

MODEL 2 – WWW Database Client/Server

Request

Internet

Response

Client
Web server Database Server

1. In Model 2 the client sends Request to the Web Server through Internet.

2. The Request is acknowledged by the Web Server and it sends Responses to the Client.

3. If the information is not available, then the Server searches data in the Database
Server also.

4. Now the Server sends the Requested information to the Client from Web Server or
from Database Server.

5. At the end of data transfer, the Client disconnects from the Server.

MODEL 3 – WEB SERVER / APPLICATION SERVER

Request

12
Internet

Response

Client
Web server Application Server

1. In Model 3 the client sends Request to the Web Server through Internet.

2. The Request is acknowledged by the Web Server and it sends Responses to the Client.

3. If the information is not available, then the Server searches data in the Application
Server also.

4. Now the Server sends the Requested information to the Client from Web Server or
from Application Server.

5. At the end of data transfer, the Client disconnects from the Server.

MODEL 4 – WEB SERVER / APPLICATION SERVER/DATABASE SERVER

Request Web server Application Server

Internet

13
Client

Response

Database Server

1. In Model 4 the client sends Request to the Web Server through Internet.

2. The Request is acknowledged by the Web Server and it sends Responses to the Client.

3. If the information is not available, then the Server searches data in the Application
Server and Database Server also.

4. Now the Server sends the Requested information to the Client from Web Server or
from Application Server or Database Server.

5. At the end of data transfer, the Client disconnects from the Server.

MODEL 5: WEB SERVER / TRANSACTION SERVER/DATABASE


SERVER

14
Request

Internet

Response

Client
Web server Transaction Server

Database Server

1. In Model 5 the client sends Request to the Web Server through Internet.

2. The Request is acknowledged by the Web Server and it sends Responses to the Client.

3. If the information is not available, then the Server searches data in the Transaction
Server and Database Server also.

4. Now the Server sends the Requested information to the Client from Web Server or
from Transaction Server or Database Server.

5. At the end of data transfer, the Client disconnects from the Server.

6. The Transaction ensures the ACID properties for several transactions with the
Databases.

MODEL 6: WEB SERVER / TRANSACTION SERVER /


DATABASE SERVER/APPLICATION SERVER

Request

Internet

15
Response

Client
Web server Transaction Server

Application Server Database Server

1. In Model 6 the client sends Request to the Web Server through Internet.

2. The Request is acknowledged by the Web Server and it sends Responses to the Client.

3. If the information is not available, then the Server searches data in the Web Server,
Transaction Server, Application Server and Database Server also.

4. Now the Server sends the Requested information to the Client from Web Server or
from Transaction Server or Database Server or Application Server.

5. At the end of data transfer, the Client disconnects from the Server.

1.1.8 W3C RECOMMENDATIONS (WWW 3 - World Wide Web Consortium)

W3C LEVELS
1. Recommendation - is the highest level of W3C standard. However, the W3C is very
careful not to actually call this a “standard” for fear of running afoul (afraid) of
antivirus statutes.

16
2. Proposed Recommendation - A proposed recommendation is mostly complete and
unlikely to undergo more than minor changes.

The main purpose of a proposed recommendation is to work out bugs in the


specification document rather than in the underlying technology documented.

3. Candidate Recommendation

A candidate Recommendation indicates that the working group has reached consensus
on all major issues and is ready for third-party comment and implementations.

1.2 TCP AND UDP PROTOCOLS

1.2.1 TCP/IP PROTOCOL ARCHITECTURE

TCP/IP Protocol architecture contains the following layers. They are

1. Application Layer
2. Transport Layer
3. Internet Layer
4. Network Layer
5. Physical Layer

COMPARISON OF OSI AND TCP/IP PROTOCOL ARCHITECTURE

Application Layer Application Layer

Presentation Layer

Session Layer
Transport (host – to – host) Layer
Transport Layer

Network Layer Internet Layer

17
Data Link Layer Network Access Layer

Physical Layer Physical Layer

TCP/IP PROTOCOL SUITE

• Socket communication takes place via protocol. Protocol is a set of rules and
regulations which should be obeyed by both server and client system.

• Internet Protocol (IP) is a low level routing protocol that breaks data into small
packets and sends them to an address across a network.

• But IP does not provide guarantee to the delivered packets at the destination side.

• Transmission Control Protocol (TCP) is a higher level protocol solves this problem
and also provides guarantee to the delivered datagram packets.

• A third protocol, User Datagram Protocol (UDP) is next to TCP and can be used
directly to support fact, connectionless, unreliable protocol.

TCP PROTOCOL FORMAT

Source Port Destination Port

Sequence Number

Acknowledgment Number

DO R C E U A P R S F Destination
W C R C S S Y I
R E G K H T N N Port

18
Checksum Urgent Pointer

Options + Padding

DO – Data Offset
R - Reserved
CWR - Congestion Window Reduced
ECE - Explicit Congestion Notification
URG - Urgent Pointer field significant
ACK - Acknowledgement field significant
PSH - Push function
RST - Reset the connection
SYN - Synchronize the sequence numbers
FIN - No more data from sender

DIFFERENCE BETWEEN CONNECTION ORIENTED AND


CONNECTION LESS PROTOCOLS
SL. Connection Oriented Connection less Protocol
NO Protocol
1 Clients sends request to the Server Making Request to the server is not necessary

2 Client has to wait until its receives Not applicable


Response from the Server
3 After receiving Response from the No need to establish a connection
Server, Client establishes
connection with the Server.

4 After establishing a connection


with the Server Clients starts Establishing a connection is not necessary.
transmitting the packets to the
Server.
5 At the end of data transfer client In connection less service the packets are
disconnect the connection with transmitted continuously with out getting
the Server. permission or without making connection with
the server.

6 Guarantee is provided to datagram Fast but unreliable, because no guarantee is


packets. provided to the data.

19
THE NETWORKING CLASSES AND INTERFACES

The classes contained in the java.net packages are shown below:

Authenticator ServerSocket

CacheRequest Socket

CacheResponse SocketAddress

ContentHandler SocketPermission

DatagramPacket URI

DatagramSocket URL

MulticastSocket URLEncoder
APPLICATION LAYER
• Application layer contains the logic needed to support the various user
applications.

• File manager, emails etc.

• Application layer provides access to OSI environment for users and also
provides distributed information services.

TRANSPORT (HOST TO HOST) LAYER

• Provides reliable data transmission and maintain that all of the data arrived in
the same order in which they were sent.

INTERNET LAYER

• Concerned with data access and routing data across a network for two end
systems attached to the same network.

20
NETWORK ACCESS LAYER

• Takes care of exchange of data between an end system and the network to
which it is attached.

PHYSICAL LAYER

• Covers the physical interface between data transmission device and a network.
It specifies the characteristics of transmission medium, nature of signals, data
rate, related informations.

1.3 URLs

• Uniform Resource Locator

• URL identifies the location of a resource on the internet. It is used to specify


the type of protocol used, name of the server, location of file on the server.

• The syntax of URL is as follows.

SYNTAX

Protocol name://username@hostname:port/path/filename#fragment?Query

1.3.1 PROTOCOL SCHEME

Protocol scheme specifies the name of the protocol used by the server. It
includes file, ftp, https, gopher, news, telnet and other strings.

USER NAME

It specifies the optional user name for the server.


PORT

It specifies optional port numbers, default port number value is 80 for HTTP
server.

PATH

21
Path points to a particular file in the directory specified.

FRAGMENT (ANCHOR / REFERENCE)


It is used to identify a particular part in the document.

QUERY STRING

It provides additional arguments for the server. It is commonly used only in http
URLs.

RELATIVE URLs

URLs that are not complete but inherit pieces of information from their parent are
called relative URLs.

• In a relative URL, any pieces that are missing are assumed to be the same as
corresponding pieces from the URL of the document in which the URL is found.

• If any hyperlink <a href = “example.html”> is to be clicked the browser cuts the
example.html from the root URL and it attaches example.html to the URL and
loads the document as

http://www.cse.com/dept/example.html

• If the relative URL begin with a /. Then it is relative to the document root
instead of relative to current file.

1.3.2 UNIFORM RESOUCE NAME (URN)


URN is a name for a particular resource but without reference to a particular location.
The use of URN is used to handle resources that are mirrored in many different locations.
URN identify the resources itself, not the place where the resource lives.

SYNTAX OF URN

Urn:name:resource-name

22
Name space - is the name of a collection of certain resources contained by some authority.

Resource-name – is the name of resource within that collection.

There are 2 types of URLs.

1. URL – Uniform Resource Locaters (is a pointer to a particular resource on the


Internet at a particular location.)

2. URNs – Uniform Resource Name (is a name for a particular resource but without
reference to a particular location)

1.3.3 URI (UNIFORM RESOURCE IDENTIFIER)

It takes tow types

1. Uniform Resource Locators (URLs)


2. Uniform Resource Name (URNs)

FORMAT OF URI

URI
URL URN

URN is a name for a particular resource but without reference to a particular


location. The main use of URN is to handle resources that are mirrored in many
different locations. They identify the resources itself, not the place where the
resources live.

1.3.4 URL

23
• Uniform Recourse Locator is a way to unambiguously identify the location of a
resource on the Interned.

URI Uniform Resource Identifier is a string of characters in a particular syntax that


identifies a resource.

• The resource identified may be a file on a server, but it may also be an email address,
a news message, b book, a person’s name, an Internet host.

SYNTAX
Scheme:scheme-specific-part

1. Tells the web browser a lot about the document

2. The protocol used to retrieve the document

3. The name of the host where the document lives and

4. The path to that document on the host.

RELATIVE URL

URL that is not complete but inherits pieces from their parent is called relative URLs.

ABSOLUTE URL

In contrast, a completely specified URL is called an absolute URL.

SYNTAX FOR URL

Protocol://username@hostname:port/path/filename#fragment?query

Where,

24
• Protocol is another word for what was called the scheme of the URL.

• Scheme is the word used in the URI RFC.

• Protocol part can be file, ftp, http, https, gopher, news, telnet, wais or various other
strings (through not urn)

• The hostname part of a URL is the name of the server that provides the resource you
want, like www.oreilly.com.

• It can also be the server’s IP address, like 128.55.47.56

• The user-name is an optional user name for the server.

• The port number is also optional.

• Path points to a particular directory on the specified server. The path is relative to the
document root of the server, not necessarily to the root of the file system on the
server.

SCHEME TYPES

1. data – base 64 encoded data included directly in a link

2. file – A file on a local disk

3. FTP – An FTP server

4. gopher– a Gopher server

5. mailto – an email address

6. news – A Usenet newsgroup

7. Telnet – A connection to a Telnet based service (only used in Remote Login System)

25
8. urn – Uniform Resource Name

1.4 MIME

HTTP is a standard protocol that defines how a web client talks to a server and how
data is transferred from the server back to the client.

HTTP relies heavily on two other standards.

 MIME (Multi purpose Internet Mail Extensions

 HTML

1. MIME is a way to encode different kinds of data, such as sound and text, to be
transmitted over a 7-bit ASCII connection.
.
2. It also lets the recipient know what kind of data has been sent, so that it can be
displayed properly.

3. MIME was originally designed to facilitate multimedia email and to provide an


encoding that could get binary data past the most train –damaged mail transfer
programs.

4. It is an open standard for sending multipart, multimedia through internet email.

5. MIME supports almost a hundred predefined types of content.

6. The MIME contents are classified into two levels. They are

• Type – It specifies what kind of data is contained (picture, text, movie)


• Subtype – It specifies the type of data (html, plain, gif, jpeg) etc.

1. MIME is an open standard for sending multipart, multimedia data through Internet
email.

2. MIME was originally intended for email, it has become a widely used technique to
describe a file’s contents so that client software can tell the difference between
different kinds of data.

26
MIME SUB TYPES

Type Subtype Description

Text Calendar Calendar control

Css A CSS used for HTML and XML

Directory Address book information such as name, phone, email


address.
Enriched Font and paragraph level formatting such as bold,
email etc
Plain Simply raw ASCII text
Html Html languages used by web browsers.
Richtext This is an HTML like markup for encoding formatting
into pure ASCII text.
Sgml Sgml standard language

1.4.1 APPLICATIONS OF MIME

1. The data returned by HTTP is sent in MIME format only.

2. Java program relies on MIME format to find an appropriate content handler


for a particular stream of data.

3. The original SMTP protocol was designed but MIME is designed for sending
multimedia data base like audio, video content types.

1.4.2 MIME MESSAGE FORMAT

Header Field Data

• MIME message consists of header field followed by data field.

• Header field indicates


1. MIME version
2. The content type
3. Data transfer encoding scheme
4. Message identification
5. Message description

27
• The message body contains the actual data being transferred which may consist of
plain text, images, WWW electronic mail

MIME SUB TYPES

1. MIME version field – indicate a version number to declare a message to be to be


conformant (conflict with this specification and allows mail processing agents to
distinguish between such ,messages and those generated by older or non-conformant
software, which is presumed to lack such a field.

2. A Content type header field, which is used to specify the type and subtype of data in
the body of a message and fully specify the native representation of such data.

2.1 A TEXT content type is used to represent textual information in a number of


character sets and formatted text description languages in a standardized manner.

2.2 A multipart content type value, which can be used to combine several body parts,
possible of differing types of data, into a single message.

2.3 An application content type can be used to transmit application data or binary
data, and hence, among other uses, to implement an electronic mail file transfer
service.

2.5 A message content type is used to encapsulate another mail message.

2.5 An image content type is used for transmitting still image or picture data.

2.6 An audio content type is used for transmitting audio or voice data.

2.7 A video content type is used for transmitting video or moving image data with
audio as part of the composite video data format.

3. A content transfer encoding header field, used to specify an auxiliary


encoding that was applied to the data in order to allow it to pass through mail
transport mechanisms which may have data or character set limitations.

4. Content-ID and Content-Description header fields can be used to describe


the data in a message body.

1.4.3 MIME MEDIA TYPES

There are 4 top lever media types they are:

28
1. Text – Textual information. The subtype “plain” in particular indicates plain text
containing no formatting commands or directives of any sort.

2. Image – Image data. “Image” requires a display device such as a graphical display, a
graphics printer, or a FAX machine) to view the information.

3. Audio – Audio data. “Audio” requires an audio output device such as speaker or a
telephone to display the contents.

4. Video – Video requires the capability to display moving images, typically including
specialized hardware and software. The two composite top level media types are

4.1 Multipart – data consisting of multiple entities of independent data


types.

4.2 Message – An encapsulated message.

1.5 CGI – COMMON GATEWAY INTERFACE

• In general a programming language is something which has its own keywords,


operators, compilers etc.

• But CGI does not own any keywords, operators, compilers etc of its own.

• Instead, CGI has got its own requirement of what a web enabled programming
language should have .

• So CGI is called as a specification. CGI is not a programming language, it is actually


the specification defined by the W3C.

29
• So CGI is an environment, which has necessary functions and interfaces for
interacting with web servers .

• CGI can be viewed as an entity which acts as the middleware between the web
servers and external databases. Thus CGI applications perform specific information
processing on the databases on behalf of web servers.

1.5.2 CGI ARCHITECTURE

Web Browser Web CGI


Server Program

File Database

• CGI allows the user to give dynamic operations to its pages.

• Traditionally, HTML program is static. CGI provides more interaction to their users.

• The CGI programs are saved with an extension of .cgi

• The CGI server can recognize any extension type, for example

1. .exe
2. .cgi
3. .asp
4. .php3
5. .shtml
6. .pl and so on.

For example named example.pl can be executed as follows.

http://www.server-name.com/cgi-bin/example.pl

30
• In the above diagram the web browser sends a request to Web Server.

• The Web server forwards this request to CGI program.

• Now the CGI server searches the output from the file or database.

• The CGI server can understand the above mentioned type of files.

1.5.3 CGI ENVIRONMENT VARIABLES

CGI environment variables are entities which are known by both web server and CGI
programs for communicating useful data between them.

CGI ENVIRONMENT VARIABLES


SL. Variable Meaning
NO
1 AUTH_TYPE Contains the authentication method used to
validate the web browser. This checks the user
name and password.

2 CONTENT_LENGTH Returns the length of the user provided content


from the web page requesting the CGI script.

3 CONTENT_TYPE Returns the type of the data. Example text/html or


image/jpeg.

4 GATEWAY_INTERFACE Returns the version of the CGI interface being


used.

5 PATH_INFO Holds the additional path information for the CGI


script.

6 PATH_TRANSLATED Holds the additional path information for the CGI


script. This value is set from the information
appended to the URL requesting the CGI script.

31
7 QUERY_STRING Returns the string in the query.

8 REMOTE_ADDR Stores the IP address pf the machine running the


Web browser requesting the CGI script.

9 REMOTE_IDENT Stores the user’s login name only if he web server


supports identification.

10 REMOTE_USER Stores the username the web browser specified for


authentication. This is only set if the server
supports authentication and the CGI script is
protected.

11 SCRIPT_NAME Stores the virtual path and name of the CGI script
being executed. This is used for self-referencing
URLs.

12 SERVER_NAME Contains the name, either domain name or IP


address, of the machine running the Web server.

13 SERVER_PORT Contains the port number on which the web


browser sent the request to the web server.

14 SERVER_PROTOCOL Displays the name and version of the protocol


being used to make the CGI script. In most cases,
this will be the HTTP protocol and will look
something like HTTP/1.0.

15 SERVER_SOFTWARE Stores the name and version of the Web server


software that executed the CGI script. Fox
example Netscape Communication Server Version
1.1.

1.5.4 HTTP REQUEST HEADER ENVIRONMENT VARIABLES

SL. Variable Meaning


NO

1 HTTP_ACCEPT Contains the list of media types separated by


comma. Fox example audio/basic, image/gif,
text/*.* and so on.

32
2 HTTP_ACCEPT_ENCODING Contains the valid encoding methods the browser
can receive in response from the web server.
Examples are x-zip, x-stuffit, x-tar.

3 HTTP_ACCEPT_LANGUAGE Contains the browser’s preferred language for a


response from the Web Server. An example
en_UK which si the English of the United
Kingdom.

4 HTTP_AUTHORIZATION Contains the authorization information from the


web browser. Example is user name and
password.

5 HTTP_CHARGE_TO Formats for this field are still undermined.

6 HTTP_FROM Contains the name of the requesting user us


supplied by the web browser in an e-mail address
format. For example username@rediff.com

7 HTTP_IF_MODIFIED_SINCE Can contain a value specified in a valid


ARPANET date standard, such as Weekday, DD-
Mon-YY HH:MM:SS TIMEZONE.

8 HTTP_USER_AGENT Contains the name of the web browser that


requested the document. An example Mozilla/2.0,
which would be the user agent for the Netscape
2.0 browser for Windows 95.

1.5.5 CGI – PARSED HEADERS

• Every CGI script must precede any data to the web server with a parsed header.

• A parsed header is the lines of code output by CGI script that get parsed by the web
server.

33
• This parsed header is in the same format as an HTTP header and can contain any of
the CGI variable names.

• Parsed headers must always be immediately followed by a blank line.

• Any lines in the parsed header that are not directives to the web server are sent back
to the web browsers as part of the HTTP response header.

SERVER DIRECTIVES FOR PARSED HEADERS

SL. Variable Meaning


NO
1 CONTENT_TYPE Specifies to the Web server the MIME type of the
data being returned by the CGI script.

2 LOCATION Contains either the virtual path or the URL of a


document that CGI script wants retuned to the
Web browser requesting your script.

3 Status Returns to the web sever an HTTP status line,


which will then be returned to the web browser.
Status code and the reason string. Examples are
404 Not Found and 403 Forbidden (not allowed).

1.5.6 HTTP RESPONSE HEADERS

SL. Variable Meaning


NO
1 ALLOWED Specifies to the requesting browser which request
methods are allowed. Examples are GET, HEAD
and PUT.

2 CONTENT_ENCODING Specifies which encoding method is used.


Examples are x-zip, x-stuffit and x-tar.

34
3 CONTENT_LANGUAGE Specifies the language the returning document is
in. An example is “en” which is English in one of
its forms.

4 CONTENT_LENGTH Specifies the size in bytes of the returning data.

5 CONTENT_TRANSFER_ENCO Specifies the encoding of the data between the web


DING server and the web browser. The default is binary.

6 CONTENT_TYPE Contains the type of the data being transferred.


Examples are text/html and image/gif.

7 COST Will contain the cost of the retrieval of the object


being requested. The format of this header has not
yet been specified.

8 DATE Contains a creation date of the requested object in


a valid ARPAET format.

9 DERIVED_FROM Can contain a version number for the requested


object, allowing for version control of editable
documents.
10 EXPIRES Contains an expiration data for the requested
information, after which the document should be
retrieved again. This header is used primarily for
caching mechanisms and is an ARPANET date
format.
11 LAST_MODIFIED Contains the date when the requested object was
last modified. This header is in an ARPANET date
format.
12 LINK Holds information about the document being
returned. You can use it to specify information
such as the inclusion of another URL within the
returned document or the creator of the returned
object.
13 MESSAGE_ID Contains a unique identifier for the HTTP
message.
14 PUBLIC Fairly similar to the ALLOW response header.
However, it specifies the required methods that
anyone can use, not just the requesting browser.
Examples for this header are GET, HEAD, and
TEXTSEARCH.

35
Contains the title of the document being returned.
15 TITLE For an HTML file, this is equivalent to the value
contained with in the <TITLE> .. </TITLE> tags.

16 URI Gives the URI where the requested object can be


found. This will not always be the URL the user
entered in the web browser requesting the returned
object. However, it will point to an object that
should be the same as the one being returned, with
some degree of variance. An example
HTTP://www.google.com , version which gives a
URI with the same document, which might vary in
language or version.

17 VERSION Defines the version of an object that can be


changed. Its format is currently undefined.

1.5.6 CGI – COMMON GATEWAY INTERFACE - EXAMPLE

• CGI is used to generate web pages dynamically.


• It is not a programming language.
• It is an environment which provides facility for executing programs and

SIMPLE CGI PROGRAM

<HTML>
<HEAD>
<TITLE> CGI EXAMPLE </TITLE>
</HEAD>
<BODY>
<FORM METHOD = GET ACTION = “/cgi/register.pl”>

Enter your Name <input type = “text” name = nname size = 25>
Enter your Mail address <input type = “text” name = nmail size = 10>

36
</FORM>

<input type = “submit” name = “nsubmit”>


<input type = “reset” name = “nreset”>
</FORM> </BODY> </HTML>

1.6.1 SGML – STANDARD GENERALIZED MARKUP LANGUAGE

• HTML is an instance of SGML.

• SGML was invented in the mid-1970s by Charles Goldfarb at IBM

• SGML is now an International Standards Organization (ISO) standard, specifically


ISO 8879:1986.

• SGML allows the user to create various user defined tags easily without any rules.

1.6.2 XML – EXTENSIBLE MARKUP LANGUAGE

• Similar to SGML

• Allows the user to create any number of user defined tags.

• The value of an attribute may be enclosed in double of single quotes like this:

• <H1 ALIGN=CENTER> THIS IS CENTERED H1 HEADING </H1>

• STYLES can be introduced for XML program like CSS using XLS file(XML Style
Sheet program)

• Here XML styles are saved with an extension of .xls (XML style sheet)

• Using .xls files various styles can be given to the data which is inside the XML
program.

1.6.3 XML DATA FILE FOR PRODUCT DETAILS

37
<PRODUCT MANUFACTURER=”ABC COMPANY”> -Assumed as record name

<NAME> KEY BOARD </NAME>


<TYPE> KEY BOARD </TYPE>
<PRICE> 1500 </PRICE>
</PRODUCT

EXAMPLE 2 – XML DATA FILE FOR EMPLOYEE DETAILS


<EMPLOYEE”> - Assumed as record name
<PRNO> 1001 </PRNO>
<NAME> JACK </NAME>
<BASIC> 10000 </BASIC>
<DA> 3000 </DA>
<HRA> 2000 </HRA>
<CCA> 500 </CCA>
<PF> 1000 </PF>
<GROSS> 15500 </GROSS>
<NET> 14500 </NET>
</EMPLOYEE>

<EMPLOYEE”> - Assumed as record name


<PRNO> 1002 </PRNO>
<NAME> JILL </NAME>
<BASIC> 20000 </BASIC>
<DA> 3000 </DA>
<HRA> 2000 </HRA>
<CCA> 500 </CCA>
<PF> 1000 </PF>
<GROSS> 25500 </GROSS>
<NET> 24500 </NET>
</EMPLOYEE>

<EMPLOYEE”> - Assumed as record name


<PRNO> 1005 </PRNO>
<NAME> BLACK </NAME>
<BASIC> 5000 </BASIC>
<DA> 1000 </DA>
<HRA> 500 </HRA>
<CCA> 500 </CCA>
<PF> 1000 </PF>
<GROSS> 7000 </GROSS>
<NET> 6000 </NET>
</EMPLOYEE>

38
HTTP

1. Standard protocol for communication between web browsers and web servers.

2. HTTP specifies how a client and server establish a connection, how the client
requests data from the server, how the server responds to that request, and finally
how the connection is closed.
3. HTTP 1.0 is the currently accepted version of the protocol. It uses MIME to encode
data. The basic protocol defines a sequence of 4 steps for each request from a client
to the server.

a) Making the connection


b) Making a request
c) Receiving the response
d) Closing the connection

1.6.4 HTTP 1.0 RESPONSE CODES

1. 2xx Successful – between 200 and 299 indicates that the request was received,
understood, and accepted.

2. 200 OK - common response code for GET/POST.

3. 201 Created – The server has created a date file at a URL, specified in the body of the
response. Now web browser attempt to load that URL.

4. 202 Accepted – request has been accepted

5. 204 No content – The server has successfully processed the request but has no
information to send back to the client.

6. 3xx Redirection – Response codes from 300 to 399 indicate that the web browser
needs to go to a different page.

Note

HTTP 1.1 doubles the number of responses. However, a response code

• From 200 to 299 always indicates success;

39
• A response code from 300 to 399 always indicates redirection;
• 400 to 499 indicate client error;
• 500 to 599 indicate a server error.

1.6.5 APPLETS AND SECURITY

• Applets are just more files that are transferred like any other.

• Applets are small windows in which the data can be given and data can be
displayed also.

WHERE DO APPLETS AND CLASSES COME FROM?

• When a browser sees an applet tag and decides to download and play the applet, it starts a
long chain of events.

• Let’s say your browser sees the following applet tag:

<applet codebase = http://javafaq/classes code = “Animation.class” width = 200 height


= 300>

1. The web browser sets aside a rectangular area on the page 200 pixels wide and
300 pixels height.

2. The browser opens a connection to the server specified in the code base
parameter, using port 80.
3. The browser requests the .class file from the web server as it requests any other
file. If a code base is present, it is prefixed to the requested filename. Otherwise,
the document base (the directory that contains the HTML page) is used.

4. The server responds by sending a MIME header followed by a blank line (\r\n)
followed by the binary data in the .class file.

5. The web browser receives the data and stores it in a byte array.

6. The byte code verifier goes over the byte codes that have been received to make
sure they don’t do anything forbidden, such as converting an integer in to pointer.

SECURITY: WHO CAN AN APPLET TALK TO AND WHAT CAN IT SAY?

40
There is much FUD (fear, uncertainty, and doubt) in the press about what Java applets
can and cannot do.

1. Applets cannot access arbitrary addresses in memory. Applet produces output in


the form of a Window. Applets are useful in writing programs using AWT
(Abstract Window Toolkit) controls.

2. Applets cannot access the local file system in any way. They cannot read from or
write to the local file system nor can they find out any information about files.

3. Applets cannot launch other programs on the client. In other words, they can not
call Sysem.exec() or Runtime.exec().

4. Applets cannot load native libraries or define native method calls.

5. Applets may not define any system properties.

Finally, most important usage of applets is

1. An applet can only open network connections to the host from which the applet
itself was downloaded.

2. An applet cannot listen on ports below 1024 (IE 5.0 does not allow applets to
listen on any ports)

3. Even if an applet can listen on a port, it can accept incoming connections only
from the host from which the applet itself was downloaded.

END OF UNIT - I

UNIT II – JAVA PROGRAMMING


2.1 Java Basics
2.2 I/O Streaming
2.3 Files
2.4 Looking up Internet Address
2.5 Socket Programming
2.6 Client/Server Programs
2.7 E-mail client
2.8 Web Page Retrieval
2.9 Protocol Handlers
2.10 Content Handlers

41
2.11 Applets
2.12 Image Handling
2.13 Remote Method Invocation

2.1 JAVA BASICS

• Java is related to C++, which is a direct descendant of C. Java derives its syntax from
C. Java’s Object oriented features were influenced by C++.

• Java is platform independent compiled language.

• Java is byte code, Byte code is a highly optimized set of instructions designed to be
executed by the Java run time system, which is called Java Virtual Machine (JVM).

• A Java program is executed by the JVM solves the major problems associated with
web based programs.

• Since java programs are executed JVM, which can run on any computer once the run-
time package exists for a given system.

CHARACTERISTICS OF JAVA PROGRAM


1. Simple
2. Secure
3. Portable
4. Object Oriented
5. Robust
6. Multithreaded
7. Architecture-neutral
8. Interpreted
9. High Performance
10. Distributed
11. Dynamic

SIMPLE:

• Java was designed to be easy for the professional programmer to learn and use
effectively.

• Object oriented programming language concepts are explained using Java very easily.

OBJECT ORIENTED

42
• Java program describes the basic principles of object oriented programming.

ROBUST

• Java is robust because it clears

1. It clears Memory management mistakes


2. It clears Mishandled exceptional conditions
3. It eliminates these problems by managing memory allocation and de-
allocation.
4. It also provides garbage collection for unused objects.
MULTITHREADED

1. To create interactive, networked programs, Java threaded programming.


2. Using multi threading concept multiple process can be executed.
3. Java also maintains smooth synchronization during multi threading process.

ARCHITECTURE NEUTRAL

1. The central issue for the Java designers was code longevity and portability.

2. The main problem is that no guarantee exists that if you write program today, it will
run tomorrow – even on the same machine.

3. Operating system upgrades, processor upgrades make a program malfunction. But


Java designers made several hard decisions in the Java language and the Java Virtual
Machine in an attempt to alter this situation.

4. The main goal of Java program is “Write once, run anywhere, any time, forever”.

INTERPRETED AND HIGH PERFORMANCE

1. Java program is compiled in JVM which in turn creates Java byte Code.

2. The Java byte code is cross platform and can run in any machine.

DISTRIBUTED

43
1. Java is designed for the distributed environment of the Internet because it handles
TCP/IP protocols.

2. Java also supports Remote Method Invocation (RMI).

3. RMI method enables a program to invoke methods across a network.

DYNAMIC

1. Java programs carry with them substantial amounts of run time information that is
used to verify and resolve accesses to objects at run time.

2. This makes it possible to dynamically link code in a safe and expedient manner.

3. This is crucial to the robustness of the Java environment, in which small fragments of
byte code may be dynamically updated on a running system.

2.2 I/O STREAMING

1. I/O in Java is built on streams.

2. Input streams are used to read data; Output streams are used to write data.

3. Different fundamental stream classes such as java.io.FileInputStream and


sun.net.TelnetOutputStream can be used to read and write particular sources of data.

4. Filter streams can be chained to an input stream or an output stream.

5. Filters can modify the data as it is read or written – for instance, by encrypting or
compressing it.

6. Java.io.DataOutputStream class provides a method that converts an integer to four


bytes and writes those bytes onto its underlying output stream.

7. Finally, readers and writers can be chained to input and output streams to allow
programs to read and write text (that is characters) rather than bytes.

OUTPUT STREAMS

Java’s basic output class is java.io.OutputStream. It takes the following methods:

44
public abstract class OutputStream

This class provides the fundamental methods needed to write data. The methods in
OutputStream classes are:

1. public abstract void write(int b) throws IOException

This method is used to write integer values.

2. public void write(byte[] data) throws IOException

This method is used to write data in the form of bytes.

3. public void write(byte[] data, int offset, int length ) throws IOException

This method is used to write data in bytes. Here while writing the data the Offset
value can also be specified. If the Offset values mentioned in write method, the write
operation will be performed starting from the Offset value.

4. public void flush() throws IOException

Flush method rescues the user form the deadlock problem by forcing the buffered
stream to send its data even if the buffer is not yet full.

5. public void close() throws IOException

This method is used to close the Output stream class.

THE FLOW OF BUFFERED STREAM & FLUSH COMMAND

Flush Method

Message is
sent from The whole
This message
server to message is
is not enough,
client sent to the
so it is waiting
client
to get some
more messages

45
WEB Buffered Output
Stream WEB
SERVER CLIENT

EXPLANATION

• The message is sent from the Server to the Client.


• If the message in buffer is not enough to send, then it automatically calls Flush
method. The Flush method forces the buffer stream to send the data to Client even if
the buffer is not yet full.

INPUT STREAMS

Java’s basic output class is java.io.InputStream

This class provides the fundamental methods needed to read data. The methods in
InputStream classes are as follows:

1. public abstract int read() throws IOException

This method is used to read the data from the buffer.

2. public int read(byte[] input) throws IOException

The method is used to read byte of information. Here byte refers an array of
valaues.

3. public int read(byte[] input, int offset, int length ) throws IOException

This method is used to read byte of information. Offset values and length can
also be included.

46
4. public long skip(long ) throws IOException

The method is used to skip value or values during read operation.

5. public int available() throws IOException

This method is used for checking whether the data is available or not for read
operation.

6. public void close() throws IOException

This method is used to close the input stream class.

EXAMPLE PROGRAM FOR READING 10 BYTES FORM INPUTSTREAM

byte[] input = new byte[10];

for (int I = 0; I < input.length; i++)


{
int b = in.read();

if (b = = -1) break;

input[i] = (byte) b;

• Here read method is used to read a character at a time.


• The value of b becomes -1 if it reaches to the end of file.
• If the value of b is -1 then the read operation is suspended, because it
reaches to the end of file
MARKING AND RESETTING

The Input Stream class also has three less commonly used methods that allow
programs to back up and reread data they’ve already read. These are:

1. public void mark(int readAheadLimit)

47
2. public void reset() throws IOException
3. public Boolean markSupported()
MARKING

1. Mark the current position in the stream with the mark() method.

2. At a later point, you can reset the stream back to the marked position using the reset()
method.

3. Subsequent reads then return data starting from the marked position.

4. If you try to reset back too far, then IOException will be thrown.

5. There can be only one mark in a stream at any given time. Marking a second location
erases the first mark.

6. Marking and resetting are usually implemented by storing every byte read from the
marked position in an internal buffer.

FILTER STREAMS

1. Input/Output stream are fairly raw classes. They allow you to read and write bytes,
either singly or in groups, but deciding what those bytes mean – whether they are
integers or IEEE 754 floating numbers or Unicode text is completely up to the
programmer and the code.

2. Many files transferred by FTP are stored in the zip format. Java provides a number of
filter classes you can attach to raw streams to translate the raw bytes to and from
these and other formats.

THE FLOW OF DATA THROUGH A CHAIN FILTERS


APPLICATION

InputStreamReader

48
GZIPInputStream

CipherInputStream

BufferedInputStream

TelnetInputStream

Network

BUFFERED STREAMS

• The BufferedOutputStream class stores written data in a buffer until the buffer is full
or the stream is flushed.

• Then it writes the data onto the underlying output stream at the time.

• BufferedInputStream class works Similar to BufferedOutputStream class for read


operation.

49
CONSTRUCTORS FOR BUFFERED IN/OUT STREAM CLASSES

1. public BufferedInputStream(InputStream in)

2. public BufferedInputStream(InputStream in, int bufferSize)

3. public BufferedInputStream(InputStream out)

4. public BufferedInputStream(InputStream out, int bufferSize)

PRINTSTREAM CLASS

The printStream class is the first filter output stream most programmers encounter’
because System.out is a PrintStream. However, other output streams can also be chained to
print streams, using these two constructors:
1. public printStream(OutputStream out)
2. public printStream(OutputStream out, Boolean autoflush)

METHODS OF PRINTSTREAM CLASS

It has 9 overloaded print() methods and 10 overloaded println() methods. They are
1. public void print(boolean b)
2. public void print(char b)
3. public void print(int b)
4. public void print(long b)
5. public void print(float b)
6. public void print(double b)
7. public void print(char[] text)
8. public void print(String s)
9. public void print(Object o)

10 overloaded println() methods.


1. public void println(boolean b)
2. public void println(char b)
3. public void println(int b)

50
4. public void println(long b)
5. public void println(float b)
6. public void println(double b)
7. public void println(char[] text)
8. public void println(String s)
9. public void println(Object o)
10. println()

PUSHBACK INPUT STREAM

• It is a subclass of FilterInputStream that provides a pushback stack so that a


program can “unread” bytes onto the input stream.

• The read() and available() methods are invoked exactly as with normal input streams.

• public void unread(int b) throws IOException – pushes an unsigned byte given as an


int between o and 255 onto the stream.

• More unread() methods that push a specified array or sub array onto the stream.

public void unread[byte[] input) throws IOException

public void unread[byte[] input, int offset, int length) throws IOException

DATA STREAMS

• The DataInputStream and DataOutputStream classes provide methods for reading and
writing java’s primitive data types and strings in a binary format.

• It has 11 methods for writing a particular java data types. They are

1. public final void writeBoolean(boolean b) throws IOException


2. public final void writeByte(int b) throws IOException

51
3. public final void writeShort(int s) throws IOException
4. public final void writeChar(int c) throws IOException
5. public final void writeInt(int i) throws IOException
6. public final void writeLong(long l) throws IOException
7. public final void writeFloat(float f) throws IOException
8. public final void writeDouble(double d) throws IOException
9. public final void writeChars(Strong s) throws IOException
10. public final void writeBytes(String s) throws IOException
11. public final void writeUTF(Sring s) throws IOException

COMPRESSING STREAMS

Java .util.zip package contsins filter streams that compress and decompress
streams in zip, gzip, and deflate(shrink or reduce) formats.

There are 6 stream classes that perform compression and


decompression.

1. public class DeflaterOutputStream extends FilterOutputStream


2. public class DeflaterInputStream extends FilterInputStream
3. public class QDeflaterOutputStream extends FilterOutputStream
4. public class DeflaterOutputStream extends FilterOutputStream
5. public class DeflaterOutputStream extends FilterOutputStream
6. public class DeflaterOutputStream extends FilterOutputStream

DIGEST (assimilate, absorb, grasp, observe) STREAMS

• The java.util.security package contains two filter streams that can


calculate a message digest for a stream.

• They are DigestInputStream and Digest-OutputStream.

• A message digest, represented in Java by the


java.util.security.MessageDigest class, is a strong hash code for the
Stream; it is a large integer (typically 20 bytes long in binary format) that

52
can easily be calculated from a stream of any length in such a fashion that
no information about the stream is available from the message digest.

• A message Digest object that uses a particular algorithm, such as the


Secure Hash Algorithm (SHA).

ENCRYPTING STREAMS

• CipherInputStream and CipherOutputStream are part of a standard


extension to java called the Java Cryptography Extension.

• public CipherInputStream(InputStream in, Cipher c)

• public CipherOutStream(InputStream in, Cipher c) – used for encryption


and decryption respectively.

READERS AND WRITERS

• Java’s native character set is the 2-byte Unicode character set.


Consequently, Java provides an almost complete mirror of the input and
output stream class hierarchy that’s designed for working with characters
instead of bytes.

• Two abstract super classes define the basic API for reading and writing
characters.

 The java.io.Reader class specifies the API by which characters are


read.

The java.io.Writer class specifies the API by which characters are


written.

• Wherever input and output streams use bytes, readers and writers use
Unicode Characters.

• The most important sub classes are InputStreamReader and the


OutputStreamWriter classes.

• In addition java.io.package also includes several raw reader and writer


classes that read characters without directly requiring an underlying input
stream. They are

53
1. FileReader
2. FileWriter
3. StringReader
4. StringWriter
5. ChararrayReader
6. CharArrayWriter
WRITERS

The Writer class mirrors the java.io.OutputStream.class. It is abstract class and has
two protected constructors. Writer class is never used directly. The various methods
of Writer classes are as follows:

1. protected Writer()
2. protected Writer(Object lock)
3. public abstract void write(char[] text, int offset, int length) throws
IOException
4. public void write(int c) throws IOException
5. public void write(char[] text) throws IOException
6. public void write(String s, int offset, int length) throws IOException
7. public abstract void flush() throws IOException
8. public abstract void close() throws IOException

READERS

• The Reader class mirrors the java.io.InputStream class.


• All the classes of writer are applicable to readers also, change read instead of
write operation.

LINENUMBERREADER

54
• The LineNumberReader class replaces the deprecated LineNumberInputStream class
from Java 1.0. It’s a subclass of BufferedReader that keeps track of the current line
number being read.

• Line number can be retrieved at any time with the getLineNumber() method.

public LineNumberReader(Reader in)


public LineNumberReader(Reader in, int bufferSize)

Similarly we have

1. PushbackReader
2. PrintWriter classes.

THREADS

• A thread with a little t is a separate independent path of execution in the virtual


machine.

• A Thread with a capital T is an instance of the java.lang.Thread class.

• There is a one-to one relationship between threads executing in the virtual


machine and Thread objects also constructed by the virtual machine.

• To start a new thread running in the virtual machine, construct an instance of


Thread class and invoke its start() method as follows:

1. For creating a Thread

Thread t = new Thread();


t.start()

2. To run a Thread
Public void run()

RACE ALGORITHM

Java Virtual Machine uses different algorithms to allot time to different threads. This is
called a race condition.

POLLING

55
The solution mostly adopt is to have the getter method return a flag value (or perhaps throw
an exception) until the result field is set. Then the main thread periodically polls the getter
method to see whether it’s returning something other than the flag value.

CALLBACKs

There are more efficient ways to handle the problem. The infinite loop that repeatedly polls
each ReturnDigest object to see whether it is finished can be eliminated.

SYNCHRONIZATION

Synchronization is the process of organizing threads in a proper way. That is if one thread is
activated another thread will be put into sleep mode. In the next cycle the thread which is in
sleep mode is activated now and the other thread is put in to sleep mode.

Synchronization process is very much essential for handling Threads properly.

SYNCHRONIZED BLOCKS

Synchronization must be considered any time multiple threads share same resources. These
threads may be instances of the same Thread subclass or use the same Run able class, or they
may be instances of completely different classes.

ALTERNATIVES TO SYNCHRONIZATION

Synchronization is not always the best possible solution to the problem of inconsistent
behavior as a result of thread scheduling. There are a number of techniques you can use
to avoid the need for synchronization.

1.1 Use local variables instead of fields wherever possible. Local variables do not have
synchronization problems.

1.2 String arguments are safe because they are immutable that is, once a string object
has been created, it cannot be changed by any thread. An immutable object never
changes its state.

1.3 A third technique is to use a thread unsafe class but only as a private field of a class
that is thread-safe. As long as the containing class accesses the unsafe class only in a

56
thread –safe fashion, and as long as it never lets a reference to the private field leak out
into another object, the class is safe.

1.4 Each separate thread its own separate log so that no resources were shared between the
individual threads.

DEADLOCK

Deadlock occurs when two threads each need exclusive access to the same set of resources,
but each thread possesses a different subset of those resources.

THREAD SCHEDULING

1. The order in which the threads are executed is called thread scheduling.
2. It is used to schedule the thread one by one without overlapping.
3. If the scheduling is not proper it may lead to errors.

PRIORITIES

1. Each thread has a priority that’s specified as an integer from 1 to 10. When multiple
threads are able to run, generally the VM will run only the highest-priority thread,
though that’s not a hard-and-fast rule.

2. public static final int MIN_PRIORITY = 1;


public static final int MIN_PRIORITY = 5;
public static final int MIN_PRIORITY = 10;

The priority which has 10, 5 and 1 will get executed in order.

Thread scheduling is divided into

Preemptive -> It is Possible to alter the sequence in the


middle

NonPreemptive -> It is not possible to alter the sequence.

THERE ARE 10 WAYS A THREAD CAN PAUSE IN FAVOR OF OTHER


THREADS OR INDICATE THAT IT IS READY TO PAUSE.

They are as follows:

57
1. It can block on I/O
2. It can block on a synchronized object
3. It can yield
4. It can go to sleep
5. It can join another thread
6. It can wait on an object
7. It can finish
8. It can be preempted by a higher-priority thread.
9. It can be suspended
10. It can be stopped

BLOCKING

• Blocking occurs at any time a thread has to stop and wait for a resource it doesn’t
have.

• The most common way a thread in a network program will voluntarily give up
control of the CPU is by blocking on I/O.

• Threads can also block when they enter a synchronized method or block.

YIELDING

• The second way for a thread to give up control is to explicit yield.

• A thread does this by invoking the static Thread.yield() method

public static void yield()

SLEEPING

• Sleeping is more powerful form of yielding. Whereas yielding indicates only that a
thread is willing to pause and let other equal-priority threads have a turn, a thread that
goes to sleep will pause whether any other thread is ready to run or not.

58
• Sometimes sleeping is useful even if you don’t need to yield to other threads. Putting
a thread to sleep for a specified period of time lets you write code that executes one
every second, every minute, every ten minutes, and so forth.

Thread.sleep() – used to put the thread in sleep mode.

JOINING THREADS – used to join two threads.

Public final void join(long milliseseconds) throws InterrupteException

Public final void join(long milliseseconds, int nanoseconds) throws InterrupteException

WAITING ON AN OBJECT

• A thread can wait on an object it has locked.

• While waiting, it releases the lock on the object and pauses until it is notified by some
other thread.

• Another thread changes the object in some way, notifies the thread waiting on that
object, and then continues.

• It remains asleep until one of three thing happens

1. The timeout expires


2. The thread is interrupted
3. The object is notified.

THREAD POOLS

1. Adding multiple threads to a program dynamically improves performance, especially


for I/O – bound programs such as most network programs.

2. Even if the threads finish quickly, this can overload the garbage collector or other
parts of the VM, and hurt performance.

2.3 FILES

• Java provides a number of classes and methods that allow the user to read and write
files.

59
• In java, all files are byte-oriented, and Java provides methods to read and write bytes
from and to a file.

• The common file stream classes are FileInputStream and FileOutputStream, which
create byte streams linked to files. The following methods are used in files.

FileInputStream(String filename) throws FilenotFoundException

FileOutputStream(String filename) throws FilenotFoundException

Here,

• filename specifies the name of the file that you want to open.

• When you create an input stream, if the file does not exist, then
FileNotFoundException is thrown.

• When the file operations are over then close it by calling close(). It is defined by both
FileInputStream and FileOutputStream classes. The close method takes the following
form.

void close() throws IOException

read() returns -1 when the end of the file is encountered.

2.4 LOOKING UP INTERNET ADDRESSES

DNS, IP ADDRESSES

60
1. Devices connected to the Internet are called nodes.

2. Nodes that are computers are called hosts.

3. Each node or host is identified by at least one unique 32-bit number called an Internet
address.

4. An IP address is normally written as four bytes of memory, each ranging from 0 to


255.

5. For example 152.255.6.9 is called the dotted quad format.

6. To avoid the complexity of IP address problem, the designers of the Internet invented
the domain Name System (DNS).

IPv6 AND 128-bit Addresses

• The current IP address standard uses 32 bits, which is enough to address more
than four billion computers, almost one for every person on earth.

• A new standard called IPv6 will begin using 16-byte, 128-bit addresses.

• This expands the available address space to 2128 or 1.6043703E32 different


addresses.

THE INETADDRESS CLASS


• The java.net.InetAddress class is Java’s encapsulation of an IP address.

• It is used by most of the other networking classes, including Socket, ServerSocket,


URL, DatagramSocket, DatagramPacket, and more.

CREATING NEW INETADDRESS OBJECTS

1. public static InetAddress InetAddress.getByname(String hostname) throws


UnknownHostException

2. public static InetAddress[] InetAddress.getAllByname(String hostname) throws


UnknownHostException

3. public static InetAddress InetAddress.getLocalHost() throws UnknownHostException

61
Byte 0 Byte 1 Byte 2 Byte 3
A 0 N/W HOST
B 1 0 N/W
C 1 1 0 N/W HOST
D 1 1 1 0 Multi cast group
E 1 1 1 1 0 Reserved for feature use
Method 1 – Used most frequently. This is a static method that takes the hostname
you’re looking for as its argument. It looks up the host’s IP address using DNS.Call
getByname() method.

Example – InetAddress address = InetAddress.getByname(www.oreilly.com);

Method 2 – Some computers have more than one Internet address. Given a hostname,
it returns an array that contains all the addresses corresponding to that name.

Method 3 – Contains one final means of getting an InetAddress object. It returns the IP
address on which it’s running.

THE COMMON LOG FILE FORMAT

Web server logs track the hosts that access a web site. By default, the log reports the IP
addresses of the sites that connect to the server.

However, you can often get more information from the names of those sites than from their
IP address.

Remotehost rfc931 authuser [date] “request” status bytes

1. remotehost – is either the hostname or IP address from which the browser connected.

2. rfc931 – username of the user on the remote system, as specified by Internet protocol
RFC 931.
3. authuser – is the authentication username as specified by RFC931.

4. [date] – the date and time of the request are given in brackets.

5. “request” – request from the client

6. status – This is a numeric HTTP status code returned to the client.

62
7. bytes – This is the number of bytes of data that was sent to the client as a result of this
request.

RETRIEVING DATA WITH URLs

1. The simplest way for a Java program to locate and retrieve data from the network
is to use the URL class.

2. User do not need to worry about the details of the protocol being used, the format
of the data being retrieved, or how to communicate with the server; you simply
tell Java the URL, and it gets the data for you.

THE URL CLASS

• The java.net.URL class is an abstraction of a Uniform Resource Locator like


ftp://ftp.redhat.com/pub.

• It extends java.lang.object, and it is final class that cannot be subclassed.

• The URL class itself forms the context through which the different strategies
are selected.

• public final class URL extends object implements Serializable

CREATING NEW URLs

The simplest URL constructor just takes an absolute URL in string form as its single
argument

Public URL(String url) throws MalformedURLException


Try
{

URL u = new URL(http://www.macfaq.com/personal.html);


}
catch (MalformedURLException e)
{
System.err.println(e)
}
METHODS OF URL

URL provides the following five public methods. They are as follows:

63
1. getFile()
2. getHost()
3. getPort()
4. getProtocol()
5. getRef()
6. getAuthority()

1. getProtocol() – method returns a String containing the scheme of the URL. For
example http,https or file.

2. getHost() – method returns a String containing the hostname of the URL.

3. getPort() – method returns the port number specified in the URL as an int. If no port
was specified in the URL, then getport() returns -1 to signify that the URL does not
specify the port explicitly, and will use the default port for the protocol.

4. getFile() – method returns a String that contains the path and file portion of a URL;
remember that java does not break a URL into separate path and file parts.

5. getRef() – method returns the named anchor part of the URL. If the URL does not
have a named anchor, the method returns null.

6. getQuery() – method returns the query of the URL,

7. getAuthority() – Between the scheme and the path of a URL, you will find the
authority. The term authority is taken from the URI specification (RFC 2396), where
this part of the URI indicates the authority that’s resolvind the resource.

RETRIEVING DATA FROM A URL

• Data can be retrieved using URL class.

• The URL class has three methods (four in java 1.3) to retrieve data from a URL.
They are

1. public final InputStream openStream() throws IOException


2. public URLConnection openConnection() throws IOException
3. public final Object getContent() throws IOException
4. public final Object getContent[class[] classes) throws IOException

64
OpenStream() – method connects to the resource referenced by the URL, performs
any necessary handshaking between the client and the server, and then returns an
InputStream from which data can be read.

Openconnection() – method opens a socket to the specified URL and returns a


URLConnection object.

An URLConnection represents an open connection to a network resource. If the call


fails, openConnection() throws an IOException.

getContent() – method is the third and final way to download data referenced by a
URL. The getContent() method retrieves the data referenced by the URL and tries to
make it into some type of object.

Object getContent[class[] classes – Starting with JDK1.3, it is possible for a


content handler to provide different views of an object. This overloaded variant of
the getContent() method lets you choose what class you’d like the content returned as.

UTILITY METHODS

1. The URL class contains a couple of utility methods that perform common
operations on URLs.

2. The samefile() method tests whether two URL objects point to the same file.
If they do, the sameFile() returns true, otherwise, it returns false.

3. equals(Object o) – An object is equal to a URL only if it is also a URL, both


URLs point to the same file as determined by the sameFile() method, and both
URLs have the same ref(or both URLs have null refs).

4. hashCode() – method returns an int that is used when URL objects are used
as keys in hash tables. Thus, it is called by the various methods of
java.util.Hashtable.

THE URLEncoder and URLDecoder Classes

• One of the problems that the designers of the web faced was differences between
local operating systems.

• To solve these problems, characters used in URLs must come from a fixed subset of
ASCII, in particular:

65
1. The capital letters A-Z
2. The lowercase letters a-z
3. The digits 0-9
4. The punctuation characters -,!, @, #, $, * ‘ (and ,)

URLEncoder

• The java.net.URLEncoder class contains a single static method called encode() that
encodes a String according to these rules.

• The java.net.URLDecoder class contains a single static method called encode() that
decodes a String according to these rules:

• Public static String encode(String s) and static String decode(String s) methods can be
used to encoding and decoding strings respectively.

COMMUNICATING WITH CGIs AND Servlets through GET METHOD

1. The URL class makes it easy for Java applets and applications to communicate with
server-side CGI programs and servlets that use the GET method.

2. CGI programs and servlets that use the POST method require the URLConnection class.

3. Study the coding for creating textbox, checkbox, label, radio button and checkbox
elements.

ACCESSING PASSWORD-PROTECTED SITES

• Java.net package includes an Authenticator class that can be used to provide a


username and password for sites that provide themselves using HTTP authentication.

• Since Authenticator is an abstract class, you must subclass it.

• To make the URL class use your subclass, you install it as the default authenticator by
passing it to the static Authenticator.setDefault() method.

• Authenticator.setDefault(new DialogAuthenticator())

2.5 SOCKET PROGRAMMING

66
SOCKETS FOR CLIENTS

DATAGRAMS

• Data is transmitted across the Internet in packets of finite size called datagrams.

• Each datagram contains a header and payload.

• The header contains the address and port to which the packet is going, the address and
port from which the packet came, and various other house keeping information used
to ensure reliable transmission.

• Sockets are an innovation of Berkely Unix that allow the programmer to treat a
network connection as just another stream onto which bytes can be written and from
which bytes can be read.

• Sockets shield the programmer from low-level details of the network, such as media
types, packet sizes, packet transmission, network address, and more.

SOCKET BASICS

• A socket is a connection between two hosts. It can perform 7 basic operations:

1. Connect to a remote machine


2. Send data
3. Receive data
4. Close a connection
5. Bind a port
6. Listen for incoming data
7. Accept connections from remote machine on the bound port

Java programs normally use client sockets in the following fashion

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

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

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

67
4. This connection is full-duplex; both hosts can send and receive data
simultaneously.

5. There will normally be some agreed-upon hand-shaking followed by the


transmission of data from one to the other.

6. When the transmission of data is complete, one or both sides close the
connection. Some protocols, such as HTTP 1.0, require the connection to be closed
after each is serviced.

7. FTP, allows multiple requests to be processed in a single connection.

THE SOCKET CLASS

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


TCP operations.

2. Each lets you specify the host and the port you want to connect to.

3. Hosts may be specified as an InetAddress or a String.

4. Ports are always specified as integer values from 0 to 65,535.

CONSTRUCTERS USED FOR CREATING SOCKETS

1. public Socket(String host, int port) throws UnknownHostException, IOException

Creates a TCP socket to the specified port on the specified host and attempts to
connect to the remote host.

2. public Socket(InetAddress host, int port) throws IOException

This constructor creates a TCP socket to the specified port on the specified
host and tries to connect. It differs by using an InetAddress object.

3. public Socket(String host, int port, InetAddress interface, int localPort) throws
IOException

This constructor creates a socket to the specified port on the specified host and
tries to connect. It connects to the host and port specified in the first two arguments.

4. public Socket(InetAddress host, int port, InetAddress interface, int localPort) throws
IOException

68
Identical to the previous one except that the host to connect to is passed as an
InetAddress, not a String. It creates a TCP socket to the specified port on the specified
host from the specified interface and local port, and tries to connect.

GETTING INFORMATION FROM SOCKET

1. public InetAddress getInetAddress() – Tells which remote host the Socket is


connected, if the connection is closed or not.

2. public int getPort – Tells the port number in which the socket is connected.

3. public int getLoalPort() - There are two ends to a connection: the remote host and the
local host. It is used for getting the local port number.

4. public InetAddress getLocalAddress() – returns the address of the local host.


CLOSING THE SOCKET

Public synchronized void close() throws IOException – is used to close the socket.

SETTING SOCKET OPTIONS

Socket options specify how the native sockets on which the Java Socket class relies to
send and receive data. The following options can be used to set sockets.

• TCP_NODELAY – ensures that packets are sent as quickly as possible regardless of


their size.

• SO_BINDADDR

• SO_TIMEOUT – ensure that the call will not block for more than a fixed number of
milliseconds.

• SO_LINGER – option specifies what to do with datagrams that have not yet been sent
when a socket is closed.

• SO_SNDBUF – used to get and set the suggested send buffer used for network
output.

69
• SO_RCVBUF – Most TCP stacks use buffers to improve network performance, say
10 Mbps and up.

• SO_KEEPALIVE – is turned on, then the client will occasionally send a data packet
over an idle connection, off terminates the data transfer.

FINGER
• Finger is a straightforward protocol described in RFC 1288.

• The client makes a TCP connection to the server on port 79 and sends a one line
query.

• The server responds to the query and closes the connection.

• The format of the query precisely, defied, the format of the response somewhat less
so.

• The data transferred is pure printable and ASCII text.

WHOIS

• Whois is a simple directory service protocol defined in RFC 954.

• It was originally designed to keep track of administrators responsible for Internet


hosts and domains.

• A whois client connects to one of several central servers and requests directory
information for a person or persons; it can usually give you a phone number, and
email address, and a U.S. mail address (not necessarily current ones though).

THE STRUCTURE OF WHOIS PROTOCOL

The client opens a TCP socket to port 43 on the server whois.internic.net.

When you are using whois, you almost always connect to this server; there are a few other
servers, but these are relatively rare.

But there is a separate whois server for the U.S. department of Defencse.

1. The client sends a search string terminated by a carriage return/linefeed pair (/r/n).
You can also search for domain names, like oreilly.com or netscape.com, which give
you information about a network.

70
2. The server sends an unspecified amount of human-readable information in response
to the command and closes the connection.

3. The client displays this information to the user.

THE FOLLOWING TABLE SHOWS PREFIX SHOULD BE PLACED BEFORE


SEARCH STRIND ON THE COMMAND LINE.

Prefix Meaning
Domain Find only domain records
Gateway Find only gateway records
Group Find only group records
Host Find only host records
Network Find only network records
Organization Find only organization records
ASN Find only Autonomous System Number records
Full or = Show complete record for each match
Person Find only person records
SUBdisplay % Show the users of the specified host, the hosts on the specified network etc.

SOCKETS FOR SERVERS

The ServerSocket() class contains everything you need to write servers in Java. It has
constructors that create new ServerSocket objects, methods that listen for connection on a
specified port, and methods that return a Socket object when a connection is made so that
you can send and receive data.

THE SERVERSOCKET CLASS

The basic life cycle of a server is

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


constructor.

2. The ServerSocket listens for incoming connection attempts on that port using its
accept() method. Accept() blocks until a client attempts to make a connection, at
which point accept() returns a socket object connecting the client and server.

71
3. Depending on the type of server, either the socket’s getInputStream() method,
getOutputStream() method, or both are called to get input and output streams that
communicate with the client.

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

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

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

THE CONSTRUCTORS FOR SERVERSOCKET

There are 3 public ServerSocket constructors

1. public ServerSocket(int port) throws IOException

2. public ServerSocket(int port, int quuelength) throws IOException, BindException

3. public ServerSocket(int port, int quuelength, InetAddress bindaddress) throws


IOException

Method 1 This constructor creates a server socket on the port specified by the argument.
If you pass 0 for the port number, the system selects an available port for you. A port
chosen for you by the system is called an anonymous port since you don’t know it
number.

Method 2 This constructor creates a ServerSocket on the specified port with a queue
length of you choosing.

Method 3 Along with method 2 it also binds the specified IP address.

HTTP SERVERS

1. HTTP is a large protocol.

2. A full featured HTTP server must respond to requests for files, convert URLs into
file-names on the local system.

72
3. It also respond to POST and GET requests, handle requests for files that don’t
exist, interpret MIME types, launch CGI programs.

4. Our investigation of HTTP servers begins with a server that always sends out the
same file, no matter who or what the request.

A FULL-FLEDGED HTTP SERVER

1. HTTP server can serve an entire document tree, including images, applets, HTML
files, and more.

2. This server is called full fledged server.

SECURE SOCKETS

1. Confidential communication through an open channel such as the public Internet that
nonetheless resists eavesdropping absolutely requires that the data be encrypted.

2. In traditional secret key (or symmetric) encryption, the same key is used both to
encrypt and decrypt the data.

3. In public key (or asymmetric) encryption, different keys are used to encrypt and
decrypt the data. One key, called the public key, is used to encrypt the data. This key
can be given to anyone.

METHODS OF THE SSL Socket Class (Secure Socket Layer socket class)

The SSLSocket class has a number of methods for configuring exactly how much and
what kind of authentication and encryption is performed.

EVENT HANDLERS

• Network communications are slow compared to the speed of most computers.


Authenticated network communications are even slower

• JSSE(Java Secure Socket Extension) uses the standard event model to notify
programs when the handshaking between client and server is completes.

• It can be implemented using HandshakeCompletedListener interface.

• Public interface HandshakecompledListener extends java.util.EventListner

73
SESSION MANAGEMENT
• SSL is most commonly used on web servers.
• Web connections tend to be transitory(fleeting or temporary)
• Using JSSE, you don’t need to do anything extra to take advantage of sessions.
• Using session various informations can be retrieved using the following methods.
1. public byte[] getId()
2. public SSLSessionContext getSessionContext()
3. public long getCreateation()
4. public long getLastAccessdTime()
5. public void invalidate()
6. public void removeValue(String name)
UDP DATAGRAMS AND SOCKETS
UDP PROTOCOL
• UDP – User Datagram protocol is an alternative protocol for sending data over IP
that is very quick, but not reliable.

• That is, when you send UDP data, you have no way of knowing whether it arrived,
much less whether different pieces of data arrived in the order in which you sent
them.

THE STRUCTURE OF UDP DATAGRAM

0 4 8 12 16 20 24 28 31
Version Header Type of service Datagram length
Length
Identification Flags Fragment
offset
Time-to-live(TTL) protocol Header checksum
Source address
Destination address
options
Source (0 – 65535) Destination port (0 – 65535)
Combined length of data and UDP header(8 Destination port (0 – 65535)
– 65535)

Data

74
CONSTRUCTORS FOR RECEIVING DATAGRAMS

The following constructors create a new DatagramPacket objects for receiving data from the
network.

1. public DatagramPacket(byte[] buffer, int length)

2. public DatagramPacket(byte[] buffer, int offset, int length)

CONSTRUCTORS FOR SENDING DATAGRAMS

The following constructors create a new DatagramPacket objects for sending data across the
network.

1. public DatagramPacket(byte[] data, int length, InetAddress destination, int port)

2. DatagramPacket(byte[] data, int offset, int length, InetAddress destination, int port)

DATA GRAM METHODS It has 5 methods that retrieve different parts of a


datagram. The actual data plus several fields from its header. These methods are mostly
used for datagrams you receive from the network.

1. public InetAddress getAddress(): Returns InetAddress object containing the address


of the remote host.

2. public int port(): Returns an integer specifying the remote port.

3. public byte[] getData[]: Method returns a byte array containing the data from the
datagram.

4. public int getLength() – method returns the number of bytes of data in the datagram.

5. public int getOffset() – returns the point in the array returned by getData() where the
data from the datagram begins.

DATA GRAM SET METHODS

1. public void setData(byte[] data) – changes the payload of the UDP datagram.

2. public void setData(byte[] data, int offset, int length) – alternative method for sending
large amount of data.

75
3. public void setAddress(InetAddress remote) – lets you change the address a datagram
packet is sent to.

4. public void setPort(int port) – changes the port a datagram is addressed to.

5. public void setLength(int length) – changes the number of bytes of data in the internal
buffer that are considered to be part of the datagram’s data as opposed to merely
unfilled space.

SENDING AND RECEIVING DATA GRAMS

public void send(DatagramPacket dp) throws IOException – for sending datagram


packet.

ublic void receive(DatagramPacket dp) throws IOException – for receiving datagram


packet.

MULTICAST SOCKETS/UNICAST SOCKETS

• Unicast socket provides point-to-point communication.

• Unicast sockets create a connection with two well-defined endpoints.

• There is one sender and one receiver, and although they may switch roles, at any
given time it is easy to tell which is which.
UNICAST SOCKETS

• Multicasting sends data from one host to many different hosts, but not to everyone.

• The data goes only to clients that have expressed an interest in the data by joining a
particular multicast group.

• Protocols require broadcasts only when there is no alternative, and routers limit
broadcast to the local network or subnet, preventing broadcasts from reaching the
Internet at large.

• Inicast is useful during Real Audio, Video broadcasting.

76
COVERAGE OF PACKET WITH A TTL OF 5

0
CAMPUS
WORLD
1

3 2
4

0
1
5 4 3 2

1
3 2
4 3

Packet dies
2
1
2

COMMON PERMANENT MULTICAST ADDRESS

Domain name IP address Purpose


BASE-ADDRESS.MCAST.NET 224.0.0.0 The reserved base address. This is never
assigned to ay multicast group

ALL-SYSTEMS.MCAST.NET 224.0.0.1 All systems on the local subnet

ALL-ROUTERS.MCAST.NET 224.0.0.2 All routers on the local subnet

AVMRP.MCAST.NET 224.0.0.4 All distance vector multicast routing


protocol (ADVMRP) routers on this
subnet.

MOBILE-AGENT.MCAST.NET 224.0.0.11 Mobile agents on the local subnet.

77
CLIETNS AND SERVERS IN NULTICAST GROUP

1. When a host wants to send data to a multicast group, it puts that data in multicast
datagrams, which are nothing more than UDP datagrams addressed to a multicast
group.

2. Most multicast data is either audio or video, or both.

3. If few pixels or even a whole frame of video is lost in transit, the signal isn’t
blurred beyond recognition.

4. Therefore, multicast data is sent via UDP, which, though unreliable, can be as much
as three times faster than data sent via connection-oriented TCP.

ESTIMATED TTL VALUES FOR DATAGRAMS ORIGINATING IN CONTIENTAL US

DESTINATION TTL VALUE TO USE


The local host 0
The local subnet 1
The local campus – that is, the same side of the nearest 16
Internet router – but on possible different LANs
High band width sites 32
The United States 48
North America 64
High bandwidth sites worldwide 128
All sites worldwide 255

ROUTERS AND ROUTING

• A multicast socket sends one stream of data over the Internet to the clients’ router.
• The router duplicates the stream and sends it to each of the clients.
• Without multicast sockets, the server would have to send four separate but identical
streams of data to the router, which would route each stream to a client.

78
• Using the same stream to send the same data to multiple clients significantly reduces
the bandwidth required on the Internet backbone.

With Multicast Socket With out Multicast Sockets

Clients clients

-----------------------------------------------------------------------------------------------------------

Router

-----------------------------------------------------------------------------------------------------------
--
THE INTERNET

Router
-----------------------------------------------------------------------------------------------------------
----
Server

Just create a Multisocket, have the socket join a multicast group, and stuff the address
of the multicast group in the DatagramPacket you want to send.

• The routers and the MulticastSocket class take care of the rest.

• The biggest restriction on multicasting is the availability of special multicast


routers (mrouters).

• Mrouters are reconfigured internet routers or workstations that support the IP


multicast extension.

79
• Multicasting is supported in the built-in TCP stack of Microsoft Windows 95, 98
and NT.

• On Macs, multicasting is supported by Open Transport but not by MacTCP.

• Pinging in multicasting can be done using all-routers.mcast.net.

CONSTRUCTORS IN MULTICASTING

1. public MulticastSocket() throws SocketException

2. public MulticastSocket(int port) throws SocketException – receives datagram on


a well known port.

COMMUNICATING WITH A MULTICAST GROUP

Once a Multicast Socket has been created, it can perform four key operations. These
are

1. Join a multicast group


2. Send date to the members of the group
3. Receive data from the group
4. Leave the multicast group

THE URL CONNECTION CLASS

• URLConnection is an abstract class that represents an active connection to a resource


specified by a URL.

• The URLConnection class has two different but related purposes.

• First it provides more control over the interaction with a server than the URL class.

• With a URLConnection, you can inspect the MIME headers sent by an HTTP server
and respond accordingly.

• Second, the URLConnection class is part of Java’s protocol handler mechanism,


which also includes the URLStreamHandler class.
• OPENING URLCONNECTION: A program that uses the URLConnection class
directly follows this basic sequence of steps.

80
1. Construct a URL object

2. Invoke the URL object’s openconnection() method to retrieve a URLConnection


object for that URL.

3. Configure the URLConnection

4. Read the header fields.

5. Get an input stream and read data.

6. Get an output stream and write data.

7. Close the connection.

SYNTAX

try
{

URL u = new URL(http://www.gogle.com);

URLConection uc = u.openConnection();
}

catch (IOException e)
{

System.err.println(e);
}

EXAMPLE FOR URL CONNECTION IMPLEMENTATION

JAVA PROGRAM TO DISPLAY THE CONTENTS OF THE HOME PAGE

UrlConnection.java

// Demonstrate URLConnection

import java.net.*;

81
import java.io.*;
import java.util.Date;

class UrlConnection
{
public static void main(String args[]) throws Exception
{
int c;
URL hp = new URL("http://www.google.com");
URLConnection hpCon = hp.openConnection();

System.out.println("Date : " + new Date(hpCon.getDate()));

System.out.println("Content-Type : " + hpCon.getContentType());

System.out.println("Expires : " + hpCon.getExpiration());

System.out.println("Last-Modified : " + new Date(hpCon.getLastModified()));

int len = hpCon.getContentLength();

System.out.println("Content-Length : " + len);

if(len > 0)
{
System.out.println("=========Content =========");
InputStream input = hpCon.getInputStream();
int i = len;

while (((c = input.read()) != -1) && (--i > 0))

System.out.print((char) c);
}

input.close();
}

else
{
System.out.println("No content Available ");
}
}

82
}

EXPLANATION

1. getDate()- Returns the date.

2. getContentType()- Returns the type of Content, for example


whether text/html document.

3. getExpiration()- Returns 0 if the web site is not expired.

4. getLastModified()- Returns the date in which the web site is


modified.(Latest date of modification)

RETRIEVING SPECIFIC MIME HEADER FIELDS

1. public String getContentType() – returns the MIME content type of the data.

2. public String getContentLength() – returns the MIME content length in bytes.

3. public String getContentEncoding() – returns a String that tells you how the content is
encoded.

4. public long getDate() – methods returns a long that tells you when the document was
sent, in milliseconds since midnight, GMT.

5. public long getExpiration – Some documents have server-based expiration dates that
indicate when the document should be deleted from the cache and reloaded from the
server.

6. public long getLastModified() – returns the date on which the document was last
modified.

83
2.6 CLIENT SERVER PROGRAMS

2.6.1 HTTP SERVER PROGRAM

import java.net.*;
import java.io.*;
class WebServer
{
public static void main(String args[])
{
ServerSocket serversocket= null;
Socket clientSocket = null;
int connects=0;
try
{ //Create the serverSocket
serversocket = new ServerSocket(80,5);
while(connects<5)
{
clientSocket = serversocket.accept();
ServiceClient(clientSocket);
connects++;
}
serversocket.close();
}
catch(IOException ioe)
{
System.out.println("Error in Simple Webserver:" + ioe);
}
}
public static void ServiceClient(Socket client) throws IOException
{
DataInputStream inbound =null;
DataOutputStream outbound=null;
try
{
//Accquire the streams for IO

inbound = new DataInputStream(client.getInputStream());

84
outbound=new DataOutputStream(client.getOutputStream());
//Format the output(response header and tiny HTML Document
StringBuffer buffer=new StringBuffer("<html> <body> <p>Welcome to Sample
WebServer </body> </html>");
String inputLine;
while((inputLine=inbound.readLine())!=null)
{
if(inputLine.equals(""))
{
outbound.writeBytes(buffer.toString());
break;
}
}
}
finally
{
//cleanup

System.out.println("Cleaning up connectiojn:"+client);
outbound.close();
inbound.close();
client.close();
client.close();
}
}
}

HTTP CLIENT PROGRAM

import java.io.*;
import java.net.*;
public class WebClient
{
public static void main(String args[])
{
try
{
Socket clientSocket1=new Socket("localhost",80);
System.out.println("Client1:"+clientSocket1);
getPage(clientSocket1);
}
catch(UnknownHostException uhe)
{

85
System.out.println("UnknownHostException:"+uhe);
}
catch(IOException ioe)
{
System.out.println("IOxception"+ioe);
}
}
public static void getPage(Socket clientSocket)
{
try
{
DataOutputStream outbound=new
DataOutputStream(clientSocket.getOutputStream());
DataInputStream inbound=new
DataInputStream(clientSocket.getInputStream());
outbound.writeBytes("GET/HTTP/1.0\r\n\r\n");
String responseLine;
while((responseLine=inbound.readLine())!=null)
{
System.out.println(responseLine);
if(responseLine.indexOf("</HTML>")!=1)
break;
}
outbound.close();
inbound.close();
clientSocket.close();
}
catch(IOException ioe)
{
System.out.println("IOException:"+ioe);
}
}
}

2.6.2 FTP SERVER PROGRAM

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

class server
{

86
public static void main(String args[])throws IOException
{
String str=new String();
String str1=new String();
int c;
int l;
str="\0";

ServerSocket ss=new ServerSocket(2555);


Socket s=ss.accept();
InputStream in=s.getInputStream();
OutputStream out=s.getOutputStream();
int i=in.read();
for(int j=0;j<i;j++)
{
c=in.read();
str1=str1+((char)c);
}
System.out.println(str1);
System.out.println("\n\tContents of
file are:\n");
FileInputStream fin=new
FileInputStream(str1);

do
{
l=fin.read();
if(l!=-1)
{

System.out.println((char)l);

}
}while(l!=-1);
fin.close();
s.close();
ss.close();

}
}

87
FTP CLIENT PROGRAM

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

class client
{
public static void main(String args[])throws IOException
{
String str=new String();
int c;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
InetAddress a=InetAddress.getLocalHost();
Socket s=new Socket(a,2555);
InputStream in=s.getInputStream();
OutputStream out=s.getOutputStream();
System.out.println("Enter the filename to be read");
str=br.readLine();
int i=str.length();
out.write(i);
byte buf[]=str.getBytes();
out.write(buf);
s.close();
System.out.println("FILE SENT");

}
}

2.7 E-MAIL CLIENT

What is E-mail?

88
Email is an electronic message sent form one computer to another. User can
send or receive email information at any time. Email can be personal or business
related information. Email may be sent or receive with or without an attachment.
Attachment can be any file pictures or photographs text file memo etc. If email
contains any attachments, attachments can be viewed using word or additional tools
like notepad or Internet Explorer.

Using email we can send even music and computer programs.

Using email the following tasks can be done. They are

1. Send messages or memos or greetings for any special occasions.


2. Receive or read messages
3. Reply to messages
4. Forward messages
5. Send the same message to multiple persons at the same time
6. Attach a text file or images
7. Save mail to a file and print the mail messages

EMAIL ADDRESS

• Email can be sent using a specified channel called an email address.

• The format of email address organization-name@domain-name

• For example google.com

Where goggle is name of the company or an organization name

Some of the domain names and its descriptions are given below.

Domain Example Description


.com Yahoo.com Commercial organization as well as individuals
.net Microsoft.net ISP & Network related companies
.org Microsof.org Non commercial organization
.gov Senate.gov Government agencies
.mil Army.mil Military
.edu Annauniv.edu Educational institution
.web Web based companies
.tv Television channel
.info Information site

89
Two letters after period (.) can be used to segregate between the countries. Examples
are as given below:

.au yahoo.co.au Australia


.us yahoo.co.us US
.uk yahoo.co.uk United Kingdom
.in yahoo.co.in India
.ca yahoo.co.ca Canada

RETRIEVING ARBITARY MIME HEADER FIELDS

The previous 6 methods specific commands from a MIME header. But the following
methods inspect arbitrary fields in a MIME header.

1. public String getHeaderFieldKey(String name) – returns the key value of a named


MIME header field.

2. public String getHeaderField(int n) – This method returns the key of the nth MIME
header field

3. public String getHeaderField(int n) – returns the value of the nth MIME header field.
The request method is header field zero, and the first actual header is one.

4. public long getHeaderFieldDate(String name, long default) – This method retrieves


the value of the MIME header field name and tries to convert it to an int. If fails,
either because it can’t find the requested header field or because that field does not
contain a recognizable integer, then getHeaderFileInt() returns the default argument.

PROTOCTED URL

1. The url field specifies the URL that the URLConnection connects to.

2. It is set by the constructor when the URLConnection is created and should not
change.

3. url returns “true” if it connected properly, also referred as protected, otherwise it


returns “false”, referred as unprotected.

DOINPUT

• Most URLConnection objects provide input to a client program.

90
• Fox example, a connection to a web server with the GET method would produce
input for the client, but a connection to a web server with the POST method might
not.

DOOUTPUT

• Programs can use a URLConnection to send output back to the server. For example,
a program that needs to send data to the server using the POST method could do so
by getting an output stream from URLConnection.

• useCaches - The useCaches variable determines whether a cache will be used if it is


available. The default value is true, meaning that the cache will be used; false means
the cache won’t be used.

CONTENT HANDLERS

• The URLConnection class is intimately tied to Java’s protocol and content handler
mechanism.

• The protocol handler is responsible for making connections, exchanging headers,


requesting particular documents, and so fourth.

• Protocol handler is used to identify what type of protocol is used in network.

GETTING CONTENT

1. public Object getContent() throws IOException -> used to identify the content which
is to be received.

2. public Object getContent(Class[] classes) throws IOException -> used to get the
content if it is in the form of an array.

CONTENT HANDLER FACTORY

The URLConnection class contains a static Hashtable of ContentHandler objects. Whenever


the getContent() method of URLConnection is invoked, java looks in this Hashtable to find
the right content handler for the current URL, as indicated by the URL’s content type.

91
PROTOOL HANDLERS

Protocol Handler is used to identify what type of protocol is being used between servers and
clients.

VARIOUS METHODS

1. Protected void setURL(URL u, String protocol, String host, int port, String file, String
ref)

2. Procted InetAddress getHostAddress(URL u)

3. Protected boolean hostEqual(URL ul, URL u2) -> determines two URLs refer to the
same server.

4. Protected boolean samefile(URL ul, URL u2) -> determines two URLs refer to the
same file.

5. Protected Boolean equals(URL u1, URL u2) - > determines protocol, host, file, path,
and ref is equal or not.

CONTENT HANDLERS

1. Content handlers are one of the ideas that got developers excited about Java in the
first place.

2. At the time that HotJava was created, netscape, NCSA, Spyglass,and a few other
combatants were fighting a battle over who would control the standard for the
web browsing.

3. A content handler is an instance of a subclass of java.net.contentHandler.

THE CONTENT HANDLER CLASS

The contentHandler class has only a simple constructor.

TO SUMMERARIZE, HERE’S THE SEQUENCE OF EVENTS

1. A URL object is created which points at some Internet resource.

2. The URL’s getContent() method is called to return an object representing the


contents of the resource.

92
3. The getContent() method of the URL calls the getContent() method of its
underlying URLConnection.

4. The URLConnectiongetContent() method calls the nonpublic method


getContentHandler() to find a content handler for the MIME type and sub type.

5. getContentHandler() checks to see whether it already has a handler for this type in
its cache.

6. If there wasn’t an appropriate ContentHandler in the cache and the


ContentHandlerFactory isn’t null, getContentHandler() calls the
contentHandlerFactory’s createContentHandler() method to instantiate a new
ContentHandler. If this is successful, the ContentHandler object is returned to
getContent().

7. If the contentHandlerFactory is null or createContentHandler() fails to instantiate


a new ContentHandler, then Java looks for a content handler class named type.
subtype, where type is the MIME type of the content and subtype, where type
is the MIME subtype in one of the packages named in the
java.content.handler.pkgs ststen orioerty.

8. Java looks for a content handler class named sun.net.www.content.type.subtype.


If it’s found, it is returned, otherwise returns null.

9. If the ContentHanler object is not null, then this contentHanler’s getContent()


method is called.

10. Either the returned object or the exception is passed up the call chain, eventually
reaching the method that invoked getContent.

2.7.1 SMTP

SMTP CLIENT

import java.io.*;
import java.net.*;
public class smtpclient
{

93
public static void main(String args[]) throws Exception
{
Socket s=new Socket("localhost",8080);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
DataInputStream in=new DataInputStream(System.in);
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println("ready");
String resp=dis.readLine();
System.out.println("Enter the from address");
String strf=in.readLine();
ps.println(strf);
System.out.println("Enter the to address");
String strt=in.readLine();
ps.println(strt);
System.out.println("Enter the message");
while(true)
{
String cmd=in.readLine();
ps.println(cmd);
if(cmd.equals("quit"))
{
System.out.println("Client quit");
break;
}
}
}
}

94
SMTP SERVER

import java.io.*;
import java.net.*;
import java.util.*;
public class smtpserver
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(8080);
Socket s= ss.accept();
ServiceClient(s);
}
public static void ServiceClient(Socket s) throws Exception
{
DataInputStream dis=null;
PrintStream ps=null;
dis=new DataInputStream(s.getInputStream());
ps=new PrintStream(s.getOutputStream());
FileWriter fw=new FileWriter("abc.eml");
FileInputStream fi;
String tel=dis.readLine();
if(tel=="ready")
System.out.println("ready signal received: Client accepted");
ps.println("Enter the address");
String from=dis.readLine();
fw.write("from:"+from+"\n");
ps.println("Enter the address");

95
String to=dis.readLine();
fw.write("to:"+to+"\n");
ps.println("Enter message:");
String cmd=dis.readLine();
fw.write("\n");
System.out.println(cmd);
fw.write("Message:"+cmd+"\n");
fw.close();
}
}

Output SMTP

96
2.7.2 POP3 PROGRAMS (CLIENT)

IMPORT JAVA.LANG.*;
IMPORT JAVA.NET.*;
IMPORT JAVA.IO.*;
CLASS CLIE
{
PUBLIC STATIC VOID MAIN(STRING ARGS[]) THROWS EXCEPTION
{
INT C;
STRING STR;
BUFFEREDREADER BR= NEW BUFFEREDREADER(NEW
INPUTSTREAMREADER(SYSTEM.IN));
INETADDRESS A= INETADDRESS.GETLOCALHOST();
SOCKET S=NEW SOCKET(A,2555);
INPUTSTREAM IN=S.GETINPUTSTREAM();
OUTPUTSTREAM OUT=S.GETOUTPUTSTREAM();
SYSTEM.OUT.PRINTLN("ENTER USERNAME:");
STR=BR.READLINE();
INT I=STR.LENGTH();
OUT.WRITE(I);
BYTE BUF[]=STR.GETBYTES();
OUT.WRITE(BUF);
WHILE((C=IN.READ())!=-1)
{
SYSTEM.OUT.PRINT((CHAR)C);
}
S.CLOSE();
}
}

POP3 PROGRAMS (SERVER):

import java.lang.*;
import java.net.*;
import java.io.*;
class serv1
{

97
public static void main(String args[]) throws IOException
{
String str=new String();
String str1=new String();
int c;
while(true)
{
str="\0";
str1="\0";
ServerSocket ss=new ServerSocket(2555);
Socket s=ss.accept();
InputStream in=s.getInputStream();
OutputStream out=s.getOutputStream();
int i=in.read();
for(int j=0;j<i;j++)
{
c=in.read();
str1=str1+((char)c);
}
System.out.println(str1);
str="\n\nhello "+str1;

if(str1.equals("\0xyz"))
{
str=str+"\nU ve 2 msgs\n\n";
}
else if(str1.equals("\0abc"))
{
str=str+"\nU ve 5 msgs\n\n";
}
else
{
str=str+"\nInvalid username\n\n";
}
byte buf[]=str.getBytes();
out.write(buf);
s.close();
ss.close();
}
}
}

98
2.8 WEB PAGE RETRIEVAL

// DEMONSTRATE URLCONNECTION

IMPORT JAVA.NET.*;
IMPORT JAVA.IO.*;
IMPORT JAVA.UTIL.DATE;

CLASS URLCONNECTION
{
PUBLIC STATIC VOID MAIN(STRING ARGS[]) THROWS EXCEPTION
{
INT C;
URL HP = NEW URL("HTTP://WWW.GOOGLE.COM");
URLCONNECTION HPCON = HP.OPENCONNECTION();

SYSTEM.OUT.PRINTLN("DATE : " + NEW DATE(HPCON.GETDATE()));

SYSTEM.OUT.PRINTLN("CONTENT-TYPE : " +
HPCON.GETCONTENTTYPE());

SYSTEM.OUT.PRINTLN("EXPIRES : " + HPCON.GETEXPIRATION());

SYSTEM.OUT.PRINTLN("LAST-MODIFIED : " + NEW


DATE(HPCON.GETLASTMODIFIED()));

INT LEN = HPCON.GETCONTENTLENGTH();

SYSTEM.OUT.PRINTLN("CONTENT-LENGTH : " + LEN);

IF(LEN > 0)
{
SYSTEM.OUT.PRINTLN("=========CONTENT =========");
INPUTSTREAM INPUT = HPCON.GETINPUTSTREAM();
INT I = LEN;

WHILE (((C = INPUT.READ()) != -1) && (--I > 0))

SYSTEM.OUT.PRINT((CHAR) C);

99
}

INPUT.CLOSE();
}

ELSE
{
SYSTEM.OUT.PRINTLN("NO CONTENT AVAILABLE ");
}
}
}

OUTPUT:

Write programs in Java to do the following:

4.1 Set the URL of another server


4.2 Download the Homepage of the server
4.3 Display the contents of Home page with Date, Content type, and Expiration Date, Last
Modified and Length of the Home Page.

Date : Tue Jun 19 10:16:08 GMT+05:30 2007

Content-Type : text/html; charset=ISO-8859-1

Expires : 0

Last-Modified : Wed Jun 13 19:21:13 GMT+05:30 2008

Content-Length : 20737

=========Content =========

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<html>
<head>
<title>Welcome to Sathyabama University</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

100
<link href="mystyle.css" rel="stylesheet" type="text/css">
<script language="JavaScript" type="text/JavaScript">
<!--
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
//-->
</script>
<script language="JavaScript" type="text/JavaScript">
<!--
function reopen() {
TheNewWin =
window.open("reopen.htm","help","height=360,width=530,toolbar=no,directories=no,status=
no,menubar=no,scrollbars=yes,resizable=no");
}
function reopen3() {
TheNewWin =
window.open("reopen3.htm","help","height=300,width=530,toolbar=no,directories=no,status
=no,menubar=no,scrollbars=yes,resizable=no");
}
function pra_exam() {
TheNewWin =
window.open("practical_examination.htm","help","height=600,width=820,toolbar=no,directo
ries=no,status=no,menubar=no,scrollbars=yes,resizable=no");
}
function placements() {
TheNewWin =
window.open("placement.htm","help","height=430,width=630,toolbar=no,directories=no,stat
us=no,menubar=no,scrollbars=yes,resizable=yes");
}
function finalyear() {
TheNewWin =
window.open("kind_notice_final_year.htm","help","height=410,width=530,toolbar=no,direct
ories=no,status=no,menubar=no,scrollbars=yes,resizable=no");
}
function secondandthirdyear() {
TheNewWin =
window.open("kind_notice_2_3_year.htm","help","height=260,width=530,toolbar=no,directo
ries=no,status=no,menubar=no,scrollbars=yes,resizable=no");
}
//-->
</script>

101
2.9 PROTOCOL HANDLERS

2.10 CONTENT HANDLERS

2.11 APPLETS

Applet program for implementing various colors, font style and size

PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class colfont extends Applet implements ItemListener
{
Choice c1,c2,c3,c4;
Label l1,l2,l3,l4;
Panel p1,p2;
static int f;
public void init()
{
c1=new Choice();
c2=new Choice();
c3=new Choice();
c4=new Choice();
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
l1=new Label("Font");
l2=new Label("Font Style");
l3=new Label("Font Color");
l4=new Label("Font Size");
p1=new Panel();
p2=new Panel();
}
public void start()
{
GraphicsEnvironment g=GraphicsEnvironment.getLocalGraphicsEnvironment();
Font f2[]=g.getAllFonts();
for(int i=0;i<f2.length;i++)

102
c1.addItem(f2[i].getFontName());
c2.addItem("Plain");
c2.addItem("Bold");
c2.addItem("Italic");
c2.addItem("Bold+Italic");
c3.addItem("red");
c3.addItem("blue");
c3.addItem("green");
c3.addItem("cyan");
c3.addItem("yellow");
for(int i=10;i<=100;i++)
c4.addItem(String.valueOf(i));
p1.add(l1);
p1.add(c1);
p1.add(l2);
p1.add(c2);
p1.add(l3);
p1.add(c3);
p1.add(l4);
p1.add(c4);
p2.setLayout(new BorderLayout());
add("NORTH",p1);
add("CENTER",p2);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
if(c2.getSelectedItem().equals("Plain"))
f=Font.PLAIN;
if(c2.getSelectedItem().equals("Bold"))
f=Font.BOLD;
if(c2.getSelectedItem().equals("Italic"))
f=Font.ITALIC;
if(c2.getSelectedItem().equals("Bold+Italic"))
f=Font.BOLD+Font.ITALIC;
g.setFont(new Font(c1.getSelectedItem(),f,Integer.parseInt(c4.getSelectedItem())));
if(c3.getSelectedItem().equals("red"))
g.setColor(Color.red);
if(c3.getSelectedItem().equals("blue"))
g.setColor(Color.blue);
if(c3.getSelectedItem().equals("green"))

103
g.setColor(Color.green);
if(c3.getSelectedItem().equals("cyan"))
g.setColor(Color.cyan);
if(c3.getSelectedItem().equals("yellow"))
g.setColor(Color.yellow);
g.drawString("COLORS AND FONTS USING APLLET",200,200);
}
}

HTML CODING:

//<applet code=colfont width=300 height=400></applet>

OUTPUT WINDOW:

104
2.12 IMAGE HANDLING

2.13 REMOTE METHOD OF INVOCATION

RMI PROGRAM FOR POWER COMPUTATION

• RMI method Invocation (RMI) allows a Java object that executes on one machine to
invoke a method of a Java object that executes on another machine.

• RMI is a Java approach to designing object oriented distributed applications.

• CORBA (Common Object Request Broker Architecture ),

DATAGRAMS

Datagrams are bundles of information passed between machines. In other words


datagram packets are container which holds the data to be transmitted across the stream.

Java implements datagrams on top of the UDP protocol by using two classes.

1. Datagram Packet – Datagram object is the object container for holding data.

2. Datagram Socket – object is the mechanism used to send or receive the


Datagram Packets.

LIST OF CONSTRUCTURS USED FOR CREATING DATAGRAM PACKET

There are four constructors used in creation of Datagram Packet. They are

1. DatagramPacket(byte data[], int size)

2. DatagramPacket(byte data[], int offset, int size)

105
3. DatagramPacket(byte data[], InetAddress ip-address, int port)

4. DatagramPacket(byte data[], int offset, int size, InetAddress ip-address, int port)

METHODS USING DATAGRAM PACKETS

SL Datagram Method Description


NO
1 InetAddress getaddress() Returns the address of the source (for datagrams being
received) or destination (for datagrams being sent).

2 Byte[] getData() Returns the byte array of data contained in the


datagram. Mostly used to retrieve data from the
datagram after it has been received.

3 Int getLength() Returns the length of the valid data contained in byte
array that would be returned from the getData()
method. This may not equal the length of the whole
byte array.

4 Int getOffset() Returns the starting index of the data.

5 Int getPort() Returns the port number.

6 Void Sets the address to which a packet will be sent. The


setAddress(InetAddress address is specified by ipAdress.
ipaddress)
7 Void setData(byte[] data) Sets the data tp data. The offset to zero, and the length
to number of bytes in data.

8 Void setLength(int size) Sets the length of the packet to size

9 Void setPort(int port) Sets the port to port

STEPS FOR SIMPLE CLIENT/SERVER APPLICATION USING RMI

Step One: Enter and compile the source code


Step Two: Generate a Stub
Step Three: Install Files on the client and server machines
Step Four: Start the RMI Registry on the Server Machine

106
Step Five: Start the Server
Step Six: Start the Client
RMI PROGRAM FOR POWER COMPUTATION

STEP 1: INTERFACE PROGRAM

import java.rmi.*;
public interface Number extends Remote
{
public double power(double x, double y)throws RemoteException
}

Step2: Create and compute client application to access remote object

import java.io.*;
import java.rmi.*;

public class Numberclient


{
public static void main(String a[]) throws IOException
{
double x,y;
try
{
String s1="numberserver";
Number e=(Number)Naming.lookup(s1);
System.out.println("X power y computation");
System.out.println("Enter x : ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
x=Double.parseDouble(br.readLine());
System.out.println("Enter y : ");
y=Double.parseDouble(br.readLine());

double z1=e.power(x,y);
System.out.println(x+" power "+y+ " = " + z1 );

}
catch(Exception e)
{
System.out.println("Exception From Client");
}
}

107
Step3: Create and compile server application to create remote objects

import java.rmi.*;
import java.rmi.server.*;
import java.io.*;
public class Numberserver extends UnicastRemoteObject implements Number
{
public Numberserver() throws RemoteException{}
public double power(double x,double y) throws RemoteException
{
double r=1.0;
for(double l=1;l<=y;l++)
r=r*x;
return r;
}
public static void main(String a[])
{
try
{
Numberserver e=new Numberserver();
Naming.rebind("numberserver",e);
System.out.println("System is ready");
}
catch (Exception e)
{
System.out.println("Error from the Server Side"+ e);
}
}
}

Step 4: Compile the interface, server and client programs


C:\jdk1.3\bin>javac Number.java
C:\jdk1.3\bin>javac Numberserver.java
C:\jdk1.3\bin>javac Numberclient.java

Step 5: Create the stub and skeleton classes and register the server.
C:\jdk1.3\bin>rmic Numberserver
C:\jdk1.3\bin>rmiregistry

Step 6: Open a new command window1 and run the Server Program

108
C:\jdk1.3\bin>java Numberserver
System is ready

Step 7: Open a Command window2 new DOS Prompt, Run the Client
C:\jdk1.3\bin>java Numberclient
Enter x :
3
Enter y :
3
3.0 power 3.0 = 27.0

RMI PROGRAM FOR ADDING TWO NUMBERS, PRINTING THE SUM

PROGRAM 1 – INTERFACE PROGRAM

import java.rmi.*;
public interface AddServerIntf extends Remote
{
double add(double d1,double d2) throws RemoteException;
}

PROGRAM 2 – PROGRAM FOR IMPLEMENTING INTERFACE

import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf
{
public AddServerImpl()throws Exception
{
}
public double add(double d1,double d2) throws RemoteException
{
return d1+d2;
}

109
}

PROGRAM 3 – SERVER PROGRAM

import java.net.*;
import java.rmi.*;
public class AddServer
{
public static void main(String args[])
{
try
{
AddServerImpl addServerImpl=new AddServerImpl();
Naming.rebind("AddServer",addServerImpl);
}
catch(Exception e)
{
System.out.println("exception: " +e);
}
}
}

PROGRAM 4 – CLIENT PROGRAM

import java.rmi.*;
public class AddClient
{
public static void main(String args[])
{
try
{
String addServerURL="rmi://"+args[0]+"/AddServer";
AddServerIntf
addServerIntf=(AddServerIntf)Naming.lookup(addServerURL);
System.out.println("the first number is:" +args[1]);
double d1=Double.valueOf(args[1]).doubleValue();
System.out.println("the second number is:"+args[2]);
double d2=Double.valueOf(args[2]).doubleValue();
System.out.println("the sum is:" +addServerIntf.add(d1,d2));
}
catch(Exception e)
{

110
System.out.println("expression:"+e);
} } }

EXECUTION STEPS

1. javac AddServerIntf.java
2. javac AddServerImpl.java
3. javac AddServer.java
4. javac AddClient.java

5. start rmiregistry
6. rmic AddServerImpl
7. java AddServer
8. java AddClient ip-address input1 input2

END OF UNIT II

111
UNIT III – SCRIPTING LANGUAGES

3.1 HTML Introduction


3.2 HTML forms
3.3 Frames
3.4 Tables
3.5 Web page design
3.6 Java Script Introduction
3.7 Control Structures
3.8 Functions
3.9 Arrays
3.10 Objects
3.11 Simple Web Applications

3.1 HTML – INTRODUCTION - BASIC CONCEPTS


3.1.1 INTRODUCTION

NETWORK – Network is interconnection of computers, used to share or exchange


information from one system to another system.

INTERNET – Internet is a worldwide network of networks.

DOMAIN – Domain is a place where information is available or it specifies the range of


value for each entity.

3.1.2 DOMAIN NAME EXTENSION

There are different domain names. Each domain represents a group. For example the
following represents different domains and its uses.

Sl Domain Description Example


No Name
1 .edu Servers that provide Annauniv.edu
Educational services
2 .gov Provides information Senate.gov
about the government of a
country
3 .mil Servers that provide Army.mil
military information.

112
4 .org Provide information about Microsoft.org.
the organizations in the
world.
5 .com Servers providing Google.com
commercial services on
the Internet.
6 .web Web based company http://www.emailaddresses.com/email_web.htm
7 .net ISP & Network related Microsoft.net
Companies
8 .tv For Television Channel http://www.brendaborri.com/tv.html

Normally two letters are used to segregate between the countries. Fox example

SL NO Letters Example Country

1 .au yahoo.co.au Australia


2 .us yahoo.co.us US
3 .ca yahoo.co.ca Canada
4 .in yahoo.co.in India
5 .uk yahoo.co.uk United Kingdom

3.1.3 FORMAT OF HTML PROGRAM

<HTML>
<HEAD>
<TITLE> This is the Title </TITLE>
</HEAD>

<BODY>
…………..

HTML body program


…………….
</BODY>
</HTML>

Note: All the tags in HTML program is optional, however the file should be saved
with .html extension.

113
HTML tags in the document Head
Tag Type Purpose

<BASE> Stand-alone Defines document baseline information


<HEAD> Container Denotes the start of the document head
<LINK> Stand-alone Establishes linking relationships with another documents
or programs
<META> Stand-alone Supplies document meta-information
<STYLE> Container Supplies style sheet information
<TITLE> Container Gives the document a descriptive title
<SCRIPT> Container Gives facility for JAVA SCRIPT or VBSCRIPT program

HTML tags in the document Body

Tag Type Purpose

<A> Container Establishes an anchor or link


<ADDRESS> Container Denotes an address tag
<APPLET> Container Embeds a Java applet in a document
<AREA> Stand-alone Defines clickable regions in a client-side image map
<B> Container Produces boldface text
<BIG> Container Produces text in a larger font size
<BODY> Container Denotes the start of the document body
<BR> Stand-alone Inserts a blank line
Tag Type Purpose
<CENTER> Container Centers contained items on the body
<DD> Container Denotes a term definition
<DT> Container Denotes a term to be defined

3.1.4 HTML MORE EXAMPLES

INTRODUCING TILES AND FOOTERS IN HTML PROGRAM

<HTML>
<HEAD>
<TITLE> This is the Title </TITLE>
</HEAD>
<BODY>

…. Type the body of the program here

114
<ADDRESS> This is Footer </ADDRESS>
</BODY>
</HTML>

EXAMPLE
<html>

<head>
<title> Example for Title and Footer</title>
</head>
<body>
Welcome to HTML page

<Address> This is the footer </Address>


</body> </html>

OUTPUT

3.1.5 TEXT FORMATTING TAGS

1. <p> </p> - is used for introducing various paragraphs.

2. <br> - Gives blank line.

3. HEADING TAGS - <h1> </h1> .. <h6> </h6> is used to introduce various headings.
<h1> is the biggest and h6 is the smallest heading tag.

4. <HR> TAG – is used to draw horizontal line

115
EXAMPLE FOR TEXT FORMATTING TAGS

<html>
<body>
<CENTER> <H4> EXAMPLE FOR TEXT FORMATTING TAGS </H4>
</CENTER>
<CENTER> <B> Bold Format </B> <br> </CENTER>
<CENTER> <I> Italic Format </I> <br> </CENTER>
<CENTER> <U> Underline Format </U> </CENTER>
</body>
</html>

OUTPUT

ATTRIBUTES OF HR TAG
1. ALIGN – Aligns the line on the browser. ALIGN = LEFT or ALIGN = RITHT
or ALIGN = CENTER

2. SIZE – Changes the size of the rule

3. WIDTH – Sets the width of the rule.

116
ATTRIBUTES OF <HR> TAG.

<html>
<body>
Example for HR Tag
<hr Align=left width=100 size=20>
</body>
</html>

OUTPUT

FONT TAG

Font tag is used to set different fonts and colors to a text in the web page.

SYNTAX

<FONT face = “font name” SIZE = size in number COLOR = “color name” >

………………..
Type the text or content here
………………..

</FONT>

EXAMPLE

<html>
<body>
<font face=”Comic Sans MS” Size=6 color=RED>
Text is Displayed in Red Color <br>
</font>

117
<font face=”Comic Sans MS” Size=6 color=blue>
Text is Displayed in blue Color<br>

</font>

<font face=”Modern” Size=6 color=green>


Text is Displayed in Green Color <br>
</font>
</body>
</html>

OUTPUT

3.1.6 LISTS

TYPES OF LISTS

1. Unordered lists
2. Ordered lists

UNORDERED LISTS

Unordered lists starts with <ul> and ends with </ul>

ATTRIBUTES OF UNORDERED LISTS

TYPE = DISC or TYPE = SQUARE

Here DISC provides a shaded circle format and SQUARE provides square shapes
respectively.

118
SYNTAX

<UL TYPE = DISC>


<LI> List Item </LI>
<LI> List Item </LI>
<LI> List Item </LI>
</UL>

EXAMPLE

<html>
<body>
<b><br><br>
<ul type = DISC>
<li> RED
<li> GREEN
<li> BLUE
<ul>
</b>
</body>
</html>

OUTPUT

EXAMPLE

<html>
<body>
<b><br><br>
<ul type = SQUARE>
<li> RED
<li> GREEN

119
<li> BLUE
<ul>
</b>
</body>
</html>

OUTPUT

ORDERED LISTS (NUMBERING)

TYPE: Controls the numbering scheme to be used. The following TYPE schemes can be
used with respect to ordered lists.

TYPE = “1” generates numbers (1,2,…)


“A” generates A, B, C..
“a” generates a, b, c
“I” generates Capital roman letters I, II, II…
“i” generates small case roman letters i, ii, iii …..

START: Alters the numbering sequence, can be set to any numeric value

VALUE: Change the numbering sequence in the middle of an ordered list

EXAMPLE

<html>
<body>
<ol type= "1">
<li> Floppies
<li> Hard Disks
<li>Monitors
</ul>

</body>
</html>

120
OUTPUT

EXAMPLE

<html>
<body>
<ol type=”1” START=100>
<li> Floppies
<li> Hard Disks
<li> Monitors
</ol>

</body>
</html>

OUTPUT

EXAMPLE

<html>
<body>
<ol type= "A">
<li> Floppies
<li> Hard Disks
<li>Monitors
</ul>

</body>
</html>

121
OUTPUT

EXAMPLE

<html>
<body>
<ol type= "a">
<li> Floppies
<li> Hard Disks
<li>Monitors
</ul>

</body>
</html>

OUTPUT

EXAMPLE

<html>
<body>
<ol type= "I">
<li> Floppies
<li> Hard Disks
<li>Monitors
</ul>
</body>

122
</html>

OUTPUT

EXAMPLE

<html>
<body>
<ol type= "i">
<li> Floppies
<li> Hard Disks
<li>Monitors
</ul>
</body> </html>

OUTPUT

USE OF DL, DT AND DD TAGS

<html>
<body>
<dl>
<dt> Keyboard
<dd>An input device
<dd>It is very useful
<dd>Used to give Input Values

<dt> printer
<dd> An output device
<dd> Output can be produced using printer
</dl>

123
</body> </html>

OUTPUT

Explanation:

1. Here, <dl> specifies definition list. The <dl> is used for creating main items and
sub items as shown above.

2. <dt> specifies definition term. It is used to specify the main heading.

3. <dd> specifies definition description. It specifies sub heading or sub title.

4. <dt>, <dd> tags should be given within <dl> tags.

3.1.7ADDING GRAPHICS TO HTML PROGRAM

<img> tag is used to insert or call a picture inside the Web page:

SYNTAX

<IMG SRC = ”picture name” height = “size in number” width =” size in number” ALT
“MESSAGE” > </IMG>

• Where, SRC specifies path of the picture. Height and width specifies height, width of
the picture during display.

124
• The message given in alt attribute will be printed when the particular picture is not
available.

EXAMPLE

<html>
<head>
<title> Working with Images </title>
</head>
<body>
<center> <h2> Controlling Image Border </h2> </center>
<center>
<i> Image WITHOUT a BORDER </i> <br><br>
<img src="fly away.jpg" width = "100" height = "100"> <br><br>
<i> Image With BORDER = 3 </I><br><br>
<img border=10 src="fly away.jpg" width = "100" height = "100" ></img>
</center>
</body>
</html>

OUTPUT

125
Note HTML accepts two picture format namely .gif and .jpg.

Image can be called in web page using <IMG> tag.

ATTRIBUTES OF IMG TAG

1. ALIGN: ALIGN = TOP, MIDDLE,BOTTOM


2. BORDER: Specifies the size of the border to place around
the image.
3. WIDTH: Specifies the width of the image in pixels.
4. HEIGHT: Specifies the height of the image in pixels
5. HSPACE: Indicates the amount of space to the left and
right of the image
6. VSPACE: Indicates the amount of apace to the top and
bottom of the image.
7. ALT: Indicates the text to be displayed in case the browser
is unable to display the image specified in the SRC
attribute.

3.1.8 LINKING DOCUMENTS

LINKS

HTML allows linking to other HTML documents as well as images. There are 3 attributes
that can be introduced in BODY tag.

1. LINK – Changes the default color of a Hyperlink to


whatever color is specified with this tag.

126
2. ALINK – Changes the default color of a hyperlink that is
activated to whatever color is specified with this tag.

3. VLINK – Changes the default color of a hyperlink that is


already visited to whatever color is specified with this tag.

NOTE: User can specify the color name of a hyperlink or an


equivalent hexadecimal number.

EXAMPLE FOR VARIOUS LINKS

LINKS.HTML

<html>
<head>
<title> EXAMPLE FOR DIFFERENT LINKS </title>
</head>

<body link = "red" alink = "green" vlink = "yellow">

<br> <br> <br> <a href = "link.html"> <li> EXAMPLE FOR LINK </a>
<br> <br> <br> <a href = "alink.html"> <li> EXAMPLE FOR ALINK </a>
<br> <br> <br> <a href = "vlink.html"> <li> EXAMPLE FOR VLINK </a>

</body>
</html>

LINK.HTML
<html>
<head>
<title> Example for LINK attribute </title>
</head>
<body>

<h1> <center> Example for LINK attribute </center> </h1>

</body>
</html>

127
ALINK.HTML

<html>
<head>
<title> Example for ALINK attribute </title>
</head>
<body>

<h1> <center> Example for ALINK attribute </center> </h1>

</body>
</html>

VLINK.HTML

<html>
<head>
<title> Example for VLINK attribute </title>
</head>
<body>

<h1> <center> Example for VLINK attribute </center> </h1>

</body>
</html>

EXTERNAL LINKS

SYNTAX

<A HREF = “File name to be linked”> Hyperlink Message </A>

EXAMPLE

<A HREF = “page1.html”> Click Here to Continue </A>

3.1.9 IMAGE MAPS

USING IMAGES AS HYPERLINKS

<A HREF = <IMG SRC = “photo.gif”> </A>

128
When a hyperlink is created on an image, clicking on any part of the image will lead to
opening of the document specified in the <A HREF TAG>.

Linked regions of an image map are called hot spots and each hot spot is associated with
html html filename.

Syntax

<MAP NAME = “fish.jpg”>

<AREA SHAPE = “rect” COORDS = “52,65,122,89” HREF = “sct.html”>


</MAP>

ATTRIBUTES OF IMAGE MAPS

1. COORDS: Each of the above shapes takes different coordinates as parameters.


a. Rectangle – 4 coordinates (x1,y2,x3,y2)
2. POLYGON: 3 or more coordinates.

3. HREF – Takes the name of the .html file that s linked to the particular area on the
image.

<MAP NAME = “fish.jpg”>

<AREA SHAPE = “rect” COORDS = “52,65,122,89” HREF = “sct.html”>


</MAP>

3.2 HTML FORMS

HTML form provides several mechanisms to collect information from people viewing your
site. The syntax of the form is

<FORM METHOD = “POST/GET” ACTION = “/cgi-bin/formail”>

• The METHOD attribute indicates the way the web server will
organize and send you the form output.

• Use METHOD = “post” in a form that causes changes to server


data, for example when updating a database.

129
• The ACTION attribute in the FORM tag is the path to the script; in
this case, it is a common script which sends form data to
destination address. Most Internet Service Providers will have a
script like this on their site.

STRUCTURE OF FORM TAG IN HTML PROGRAM

<HTML>

<HEAD>

<TITLE>THIS IS MY TITLE </TITLE>

<BODY>

<FORM>

Create the necessary form elements (text box, radio, label etc.)
</FORM>
</BODY>
</HEAD>
</HTML>

3.2.1 FORM ELEMENTS EXAMPLES

CREATION OF LABEL AND TEXT BOX

<html>
<head>

<title> form1-example FORM1.HTML </title>


</head>
<body>

<form>
<center> <h1> Student Details </h1> </center>
Student Name: <input type = "text" name = "name1" value = "">
</form>
</body>

</html>

130
INTRODUCING PASSWORD

<html>
<head>
<title> form2-using password FORM2.HTML </title>
</head>

<body>

<form>
<center> <h1> Student Details </h1> </center>
<h1> Student Password: <input type = "password" name = "pass"> </h1>
</form>
</body>

</html>

OUTPUT

131
INTRODUCING CHECKBOX

<html>
<head>
<title> form2-Creating Checkbox FORM3.HTML </title>
</head>

<body>

<form>

<h1> Loan Status <input type = "checkbox" name = "loan"> </h1>


</form>
</body>
</html>

CREATION OF RESET, SUBMIT, RADIO BUTTONS

<html>
<head>
<title> form2-Creating Reset and Submit Buttons </title>
</head>

<body>

<form>

<h1> Sex <input type = "radio" name = "sex1"> Male </h1>


<h1> Sex <input type = "radio" name = "sex1"> Female </h1>

<input type = "reset">


<input type = "Submit">
</form>
</body>
</html>

132
CREATION OF LIST BOX

<html>
<head>
<title> Using List box Object </title>
</head>

<body>

<form>

<select dept = "deptnames" size = 2>

<option selected> MECH


<option> IT
<option> CSE
<option> MECH
</select>
</form>
</body>
</html>

OUTPUT

133
3.3 FRAMES

Frames are used to call many html files at the same time. This can be done using
<FRAMESET> </FRAMESET> tags.

3.3.1 ATTRIBUTES OF FRAMES

ROWS – This attribute is used to divide the screen into multiple rows. It can be set equal to
a list of values. Depending on the required size of each row, the values can be

• A number of pixels
• Expressed as a percentage of the screen resolution
• The symbol *, which indicates the remaining space.

COLS – This attribute is used to divide the screen into multiple columns.

SYNTAX

<FRAMESET ROWS = “30%, *”> => Divides the screen into 2 rows,
* indicates the remaining space
<FRAMESET COLS = “50%, 50%”> => Divides the first row into 2 equal
columns
<FRAME SRC = “file1.html”>
<FRAME SRC = “file2.html”>
<FRAMESET COLS = “50%,50%”> => Divides the second row into 2 equal
columns

<FRAME SRC = file3.html”>


<FRAME SRC = file4.html”>
</FRAMESET>
</FRAMESET>

134
EXAMPLE

FRAME.HTML

<html>
<frameset rows="30%,30%">
<frameset cols="10%,10%">
<frame src="file1.html">
<frame src="file2.html">
</frameset>

<frameset cols="20%,20%">
<frame src="file3.html">
<frame src="file4.html">
</frameset>
</frameset>
</html>

FILE1.HTML

html>
<body>
<h4> Output of File1</h4>
</body>
</html>

FILE2.HTML

<html>
<body>

<h4> Output of File2</h4>


</body>
</html>
FILE3.HTML
html>
<body>

<h4> Output of File3</h4>


</body>
</html>

135
FILE4.HTML

<html>
<body>

<h4> Output of File4</h4>


</body>
</html>

OUTPUT

Output of File2
Output of File1

Output of File3 Output of File4

3.4 TABLES

A table is a two dimensional matrix, consisting of rows and columns. All table related tags
are included between <TABLE> </TABLE> tags.

SYNTAX

<TABLE>
<TR> Heading </TR>
<TH> Row elements </TH>
<TD> Table data values </TD>
</TABLE>

136
3.4.1 ATTRIBUTES OF TABLE TAG

ALIGN Horizontal alignment is controlled by the ALIGN attribute. It can be set


to LEFT, CENTER, or RIGHT
VALIGN Controls the vertical alignment of cell contents. It accepts the values TOP,
MIDDLE or BOTTOM
WIDTH Sets the WIDTH of a specific number of pixels or to a percentage of the
available screen width.
BORDER Controls the border to be placed around the table.
CELLPADING This attribute controls the distance between the data in a cell and the
boundaries of the cell
CELLSPACING Controls the spacing between adjacent cells
COLSPAN Used to merge two or more columns
ROWSPAN Used to merge two or more rows.

EXAMPLE

<html>
<head>
<title> Table Attributes </title>
</head>

<body bgcolor=lightgrey>
<center> <h3> Specifing the BORDER and WIDTH of the Table! </h3></center>

<br><br>
<center>
<table border=5width=50%>
<caption align=bottom>

</caption>

<tr>
<th> Name </th>
<th> Branch </th>
<th> Total Marks </th>
<th> Grade </th>
</tr>

<td>Shilpa </td>

137
<td>CSE </td>
<td>950 </td>
<td>Distinction </td>
</tr>

<td>Beena </td>
<td>IT </td>
<td>800 </td>
<td>First Class </td>
</tr>

<td>Hanifa </td>
<td>ECE </td>
<td>645 </td>
<td>Second Class </td>
</tr>

<td>Monisha </td>
<td>EEE </td>
<td>245 </td>
<td>Fail </td>
</tr>

</table>
</center>
<center> <h3> Personal Information </h3> </center>
</body>
</html>

138
OUTPUT

3.4.2 SPECIFYING CELL SPACING AND CELL PADDING TABLE


ATTRIBUTES

<html>
<head>
<title> Working with Table </title>
</head>

<body bgcolor=lightgrey>
<b> Specifing CELL SPACING </b>
<br>
<HR>
<center>
<table border=5 width=25% ALIGN=center cell spacing = 25>

<tr>
<th> Name </th>
<th> Age </th>
</tr>

<tr align=center>
<td>Shilpa </td>
<td> 21 </td>
</tr>

139
<tr align=center>
<td>vaishali</td>
<td> 22 </td>
</tr>
</table>
</center>

<hr>
<b><i> With Cellpadding of 10</i></b>

<center>
<table border=1 width=25% cellpadding=10 ALIGN=center>
<tr>
<th> Name </th>
<th> Age </th>
</tr>

<tr align=center>
<td>Shilpa </td>
<td> 21 </td>
</tr>

<tr align=center>
<td>vaishali</td>
<td> 22 </td>
</tr>
</table>
</center>
</body>
</html>

140
OUTPUT

3.4.3 ROWSPAN AND COLSPAN ATTRIBUTES

<html>
<head>
<title> Working with Tables </title>
</head>

<body bgcolor=lightgrey>
<center> <H3> Specifing ROWSPAN and COLSAPN Attributes! </H3> </center>

<br><br><br><br>
<center>
<table border=1 width=50% ALIGN=center>

<tr>
<th rowspan=2> NAME </th>
<th colspan=3> MARKS</th>
</tr>

<tr>
<th>PowerBuilder
<th>Visual Basic
<th>Developer2000

141
</tr>

<tr align=center>
<td>Shilpa</td>
<td> 21 </td>
<td> 45 </td>
<td> 30 </td>
</tr>

<tr align=center>
<td>vaishali</td>
<td> 26 </td>
<td> 30 </td>
<td> 40 </td>
</tr>
<caption Align=bottom> <b> <br> Mark Sheet </b> </caption>

</table>
</center>
</body>
</html>

OUTPUT

142
3.4.4 SPECIFYING COLORS IN TABLE CELLS

<html>
<head>
<title> Working with Tables </title>
</head>

<body bgcolor= white>


<h3> <center> Specifing Colour in Table Cells </center> </h3>

<br><br><br><br>
<center>
<table border=5 width=50% ALIGN=center>

<tr>
<th bgcolor= red> Name </th>
<th bgcolor= red > Age </th>
</tr>

<tr align=center>
<td bgcolor=green>Shilpa </td>
<td bgcolor= green> 21 </td>
</tr>

<tr align=center>
<td bgcolor= blue>vaishali</td>
<td bgcolor= blue> 22 </td>
</tr>
</table>
</center>
</body>
</html>

143
OUTPUT

3.5 WEB PAGE DESIGN

Create a web page to do the following:

1. Set the background with grey color.


2. Show different font with different sizes.
3. Show the usage of text formatting tags.

Main.html
<html>
<head>
<title> Web Page Design Example </title>
</head>
<body>
<h2>
<br> <a href ="grey.html"> 1.Set the Background With Grey Color </a> <br>
<br> <a href ="diffont.html"> 2.Different Fonts With Different Sizes </a> <br>
<br><a href ="format.html"> 3.Text Formatting Tags</a> <br>
<h2>
</body>
</head>

144
yellow.html

<html>
<head>
<title> Displaying web page with Grey color </title>
</title>
</head>

<body bgcolor = "grey">

<p>
<h2> This Web Page is Displayed in Yellow Color </h2>
<br>
<br>

<h2> <a href = "main.html"> Back to Main Menu </a> </h2>


</p>
</body>
</html>

DIFFERENT FONTS WITH COLORS

DIFFONT.HTML

<html>
<head>
<title>Create Web Page for using Different fonts with different sizes - EX No. 1>
</title>
</head>

<body>

<p>
<font face = "arial" size = "6" color = "black">
Text is in Arial, size = 6, color = "black"
</font>

<br><br>

<font face = "Times New Roman" size = "5" color = "black">


Text is in Times New Roman, size = 5, color = "black"
</font>

145
<br><br>

<font face = "Lucida Handwriting" size = "4" color = "black">


Text is in Lucida Handwriting, size =4, color = "black"
</font><br><br>

<font face = "Century Gothic" size = "5" color = "black">


Text is in Century Gothic, size =5, color = "black"
</font>

<br> <br>

<center> <h2> <a href = "main.html"> Back to Main Menu </a> </h2> </center>

</p>
</body>
</html>

FORMAT.HTML

<html>
<head>
<title>Various text formatting tags <title>
</title>
</head>

<body>

<p>
<br><br> <b> Example for Bold Format </b>
<br><br><i> Example for Italic Format </i>
<br><br><u> Example for Underline Format </u>

<br><br><center> Example for Bold Format </center>


</body>
</html>

146
OUTPUT

147
3.6 JAVA SCRIPT INTRODUCTION

SCRIPTING LANGUAGES

• JavaScript is a Scripting language (web site development environment) created by


Netscape.

• Hence JavaScript works best with the Netscape suite of Client and Server products.

• JavaScript is the native scripting language of Netscape Navigator.

• VBScript is the native Scripting language of HTML.

SERVER SIDE SCRIPTING

• In Server side scripting the script program is executed at Server Side the required
html program is sent to the client.

• The job of the server is more in server side scripting

CLIENT SIDE SCRIPTING

• Here the script program is processed and executed in the client side itself.

• So that it reduces the burden of the server.

JAVA SCRIPT

1. JavaScript is an object-oriented language that allows creation of interactive Web


pages

2. JavaScript allows user entries, which are loaded into an HTML form to be processed
as required

3.6.1 JAVASCRIPT INTRODUCTION

Objectives
1. To be able to write simple java script programs
2. To be able to use input and output statements

148
3. To understand basic memory concepts
4. To be able to use arithmetic operators
5. To understand the precedence of arithmetic operators
6. To be able to write decision making statements
7. To be able to use relational and equality operators
ADVANTAGES

1. It is an interpreted language, which requires no compilation steps.

2. Embedded within HTML.

3. Minimal Syntax – easy to learn

4. Quick Development

5. Designed for simple, small programs

6. High performance

7. Procedural Capabilities – support facilities such as condition checking, looping and


branching.

8. Designed for programming user events – like VB Java Script is also based on Events.

9. Easy Debugging and Testing

10. Platform Independent/ Architecture Neutral

SYNTAX OF JAVASCRIPT PROGRAM


<HTML>
<HEAD>
<SCRIPT language = “JavaScript”>

… body of the script program


</SCRIPT>
</HEAD>

<BODY>
<SCRIPT language = “JavaScript”>
body of the program.

149
</SCRIPT>
</BODY>
</HTML>

EXAMPLE

<HTML>
<HEAD>
<SCRIPT language = “JavaScript”>

var name = prompt(“Enter your name”,”name”);

</SCRIPT>
</HEAD>
<BODY>
<SCRIPT language = “JavaScript”>
document.write(“<H2> Hai” + “</H2”);
</SCRIPT>
</BODY>
</HTML>

OUTPUT
Assume the input is anbu then the output will be

Hai anbu

3.7 JAVA SCRIPT CONTROL STRUCTURES

SCRIPT PROGRAM USING FOR.. LOOP

SYNTAX

for(int i=initial-value;i<condition;i++)
{
body program
}

150
where i is the control variable and assign with the initial value. The body of the
program is executed till the condition is true. For each iteration i value is incremented by 1.

EXAMPLE

Java script program for adding values from first number to second number using for
loop.

<HTML>
<HEAD>
<SCRIPT language = JavaScript>
var tot1 = 0;
var num1=0,num2=0;i=0;

var num1 = prompt("Enter the First Number", "Number1");


var num2 = prompt("Enter the Second Number","number2");
num1 = parseInt(num1);
num2 = parseInt(num2);

for(i=num1;i<=num2;i++)
{
tot1 = tot1 + i;
}
</SCRIPT>
</HEAD>

<BODY>

<h1> WELCOME TO JAVA SCRIPT PROGRAM </h1>


<SCRIPT language = "JavaScript">

document. write ("<H2>" + "SUM FROM " + num1 +" to " + num2 + " = " + tot1);

</SCRIPT>

</BODY>
</HTML>

151
OUTPUT

SCRIPT PROGRAM USING WHILE LOOP

SYNTAX

i = 0;
while(condition)
{
body program
}

152
Where i is the initial value and assign with zero. The body program is executed till the
condition remains true. If the condition is false then the loop is terminated. The body of
program will get executed only when the condition is true.

EXAMPLE

Java script program for adding values from first number to second number using while loop.

<HTML>
<HEAD>
<SCRIPT language = JavaScript>

var tot1 = 0;
var num1=0,num2=0;i=0;
var num1 = prompt("Enter the First Number", "Number1");
var num2 = prompt("Enter the Second Number","number2");

num1 = parseInt(num1);
num2 = parseInt(num2);

i = num1;
while(i<=num2)
{

tot1 = tot1 + i;
i++;
}
document.writeln("sum = " + tot1);

</SCRIPT>
</HEAD>

<BODY>

<h1> WELCOME TO JAVA SCRIPT PROGRAM - WHILE LOOP </h1>


<SCRIPT language = "JavaScript">
document.write("<H2>" + "SUM FROM " + num1 +" to " + num2 + " = " + tot1);
</SCRIPT>
</BODY>
</HTML>

153
OUTPUT

3.8 JAVA SCRIPT FUNCTIONS

SCRIPT PROGRAM USING FUNCTION

SYNTAX
function function-name(input parameter1, …input
parameter-n)
{
body of the function program
}

154
SYNTAX FOR CALLING THE FUNCTION

variable name = function-name(input parameter1, …input parameter-n)

EXAMPLE

Java script program for adding values from first number to second number using function
loop.

<HTML>
<HEAD>
<SCRIPT language = "JavaScript">

function sum1()
{

var tot1 = 0;
var num1=0,num2=0;i=0;

var num1 = prompt("Enter the First Number", "Number1");

var num2 = prompt("Enter the Second Number","number2");

num1 = parseInt(num1);
num2 = parseInt(num2);
i = num1;
while(i<=num2)
{

tot1 = tot1 + i;
i++;
}

document.write("<H2>" + "SUM FROM " + num1 +" to " + num2 + " = " + tot1);

</SCRIPT>

155
</HEAD>

<BODY>

<h3> JAVA SCRIPT USING FUNCTION </h3>


<SCRIPT language = "JavaScript">

var sum2 = sum1();

</SCRIPT>

</BODY>
</HTML>

OUTPUT

156
3.9 THE JAVASCRIPT ARRAYS

Arrays are JavaScript objects that are capable of storing a sequence of values. These values
are stored in indexed locations within the array. The length of an array is the number of
elements of an array accessed by using the name of the array followed by the index value of
the array element enclosed in square brackets.

The length of an array starts from 0 to n-1.

The array can be created in the following methods

1. arrayName = new Array(Array length) => array size is explicitly specified, array
size is predefined.

2. arrayName = new Array() =>The second example creates an array of


the size 0.

DENSE ARRAYS

• A dense array is an array that has been created with each of its elements being
assigned a specific value.

• Dense arrays are used exactly in the same manner as other arrays.

• Dense arrays are declared and initialized at the same time.

ARRAY METHODS

Join() – returns all elements of the array joined together as a single string.

Reverse() – reverses the order of the elements in the array.

EXAMPLE

3.9.1 JAVA SCRIPT PROGRAM FOR ARRAYS

157
<SCRIPT language = "JavaScript">
var sum,i;
var n = prompt("Enter the no. elements in the array","");
var elements= new Array(n);
for(i=0;i<n;i++)
{
elements[i]=prompt("Enter the array elements","");
elements[i]=parseInt(elements[i]);
}
sum=0;
for(i=0;i<n;i++)
{
sum=sum+elements[i];
}
document.write ("Sum of array elements is " +sum); </SCRIPT>

158
159
3.9.2 OPERATORS AND EXPRESSIONS IN JAVASCRIPT

• +-*/

• % - Modulus – remainder

• ++ - Return the value then Increment

• -- Return the value then Decrement

LOGICAL OPERATORS

&& - Logical and

|| - Logical or

! Logical not

COMPARISION OPERATORS

• = = equal (perform type conversion before testing for equality.

• = = = strictly equal (do not perform type conversion before testing for equality)

STRING OPERATORS

Currently Java Script supports only one string concatenation (+) operator.

EXAMPLE
“ab” + “cd” produces “abcd”

ASSIGNMENT OPERATORS

1. =
2. += increments and assigns the value
3. -=
4. *=
5. /=
6. %= Takes the modulus of the variable on the left the %= operator using the value of
the expression on its right

160
CONDITIONAL EXPRESSION - TERNARY OPERATOR & CONTROL
STRUCTURES

SYNTAX

condition? value1:value2

If the condition is true, value1 is the result of the expression, Otherwise value2 is the
result of the expression.

THE DELETE OPERATOR

delete marks[20]  deletes the 21st element of an array.

3.9.3 CONDITIONAL CHECKING

If(condition)
{
java script code
}

BUILT-IN FUNCTIONS IN JAVASCRIPT

1. eval()  converts a string expression to a numeric value

USER DEFINED FUNCTIONS IN JAVASCRIPT

function function_name(parameter1,parameter2…)
{
block of java script
}

161
3.9.4 DIALOG BOXES

Dialog boxes are used to display small windows. This is also used to get input from user.

SYNTAX

alert(“message”);

alert(“Click here to continue”)

prompt(“Enter your name”, name)

1. alert is only used to display some information

2. prompt is used to display information along with some input value

3. Confirm dialog box, causes program execution to halt until user action takes place.
The user action can be either OK or CANCEL.

OK – returns true
CANCEL – returns false.

Simple example

<HTML>
<HEAD>

<TITLE> This is a simple program </TITLE>

<SCRIPT LANGUAGE = “JavaScript”>

document.writeln(<“H1”> Welcome to Javascript programming “<H1>”);

</SCRIPT>
</HEAD> </BODY> /BODY>
</HTML>

ARITHMETIC OPERATORS

+ - * / % (modulus)

162
3.9.5 JAVASCRIPT KEYWORDS

break case continue delete do


else false for function if
in new null return switch
this true typeof var void
while with

KEYWORDS THAT ARE RESERVED BUT NOT USED BY JAVASCRIPT

catch class const debugger default


enum export extends finally import
super try

3.9.6 INCREMENT AND DECREMENT OPERATORS

SL Assignment Initial variable Sample Explanation Assigns


NO operator value expression

1 += c=3 c+=7 c=c+7 10 to c


2 -= d=5 d- = 4 d=d–4 1 to d
3 *= e=4 e*=5 e=e*5 20 to e
4 /= f=6 f /= = 3 f=f/3 2 to f
5 %= g = 12 g %= 9 g = g %9 3 to g
6 ++ Pre increment ++a Increment a y 1, then use the
new value in the expression
7 ++ Post increment a++ Use the current value of a in the
expression in which a resides,
then increment a by 1
8 -- Pre decrement --b decrement a y 1, then use the
new value in the expression
9 -- Post decrement b-- Use the current value of a in the
expression in which a resides,
then decrement a by 1

163
3.9.7 MORE JAVA SCRIPT PROGRAMS

PROGRAM 1 – Java Script program to read and printing the Text

164
JAVA SCRIPT PROGRAM FOR ADDING TWO NUMBERS

<HTML>
<HEAD>
<SCRIPT language = JavaScript>

var tot1 = 0;
var num1=0,num2=0;

var num1 = parseInt(prompt("Enter the First Number", "Number1"));

var num2 = parseInt(prompt("Enter the Second Number","number2"));


document.write(num1);

tot1 = num1 + num2;

</SCRIPT>
</HEAD>

<BODY>

<h1> WELCOME TO JAVA SCRIPT PROGRAM </h1>


<SCRIPT language = "JavaScript">

document.write("<H2> SUM " + tot1 +"</H2>");

</SCRIPT>

</BODY>
</HTML>

165
OUTPUT

JAVA SCRIPT PROGRAM USING FOR LOOP TO PRINT SUM FROM


STARTING NUMBER TO ENDING NUMBER

<HTML>
<HEAD>
<SCRIPT language = JavaScript>

166
var tot1 = 0;
var num1=0,num2=0;i=0;

var num1 = prompt("Enter the First Number", "Number1");

var num2 = prompt("Enter the Second Number","number2");

num1 = parseInt(num1);
num2 = parseInt(num2);

for(i=num1;i<=num2;i++)
{
tot1 = tot1 + i;
}

</SCRIPT>
</HEAD>

<BODY>

<h1> WELCOME TO JAVA SCRIPT PROGRAM </h1>


<SCRIPT language = "JavaScript">

document.write("<H2>" + "SUM FROM " + num1 +" to " + num2 + " = " + tot1);

</SCRIPT>

</BODY>
</HTML>

167
OUTPUT

JAVA SCRIPT PROGRAM USING WHILE FOR LOOP TO PRINT SUM


FROM STARTING NUMBER TO ENDING NUMBER

168
<HTML>
<HEAD>
<SCRIPT language = JavaScript>

var tot1 = 0;
var num1=0,num2=0;i=0;

var num1 = prompt("Enter the First Number", "Number1");

var num2 = prompt("Enter the Second Number","number2");

num1 = parseInt(num1);
num2 = parseInt(num2);

i = num1;
while(i<=num2)
{

tot1 = tot1 + i;
i++;
}
document.writeln("sum = " + tot1);

</SCRIPT>
</HEAD>

<BODY>

<h1> WELCOME TO JAVA SCRIPT PROGRAM </h1>


<SCRIPT language = "JavaScript">

document.write("<H2>" + "SUM FROM " + num1 +" to " + num2 + " = " + tot1);

</SCRIPT>

</BODY>
</HTML>

OUTPUT

169
JAVA SCRIPT PROGRAM USING ARRAY

<SCRIPT language = "JavaScript">


var sum,i;
var n = prompt("Enter the no. elements in the array","");
var elements= new Array(n);

for(i=0;i<n;i++)
{

170
elements[i]=prompt("Enter the array elements","");
elements[i]=parseInt(elements[i]);
}
sum=0;
for(i=0;i<n;i++)
{
sum=sum+elements[i];
}
document.write ("Sum of array elements is " +sum);
</SCRIPT>

3.10 OBJECTS

Java script communicates with web browser using object model. There are many
number of objects available in Java Script that can be used to control and interact with the
web browser.

OBJECT HIERARCHY

Window Navigator

Document History Location

Anchor Link Images Form

Button Checkbox Radio Text Area Submit Hidden Text Password Reset Select

SCOPE

Scope or life refers to the range over which a variable, function or an object. A
variable in java script will have value only with in the scope. It can not be referenced outside
the function.

PROPERTIES OF WINDOW OBJECT

Properties Meaning
Closed Returns true if the window is closed else returns Boolean value false.

171
Length Returns the number of frames in the current window
Name Returns the name of a window
Opener Returns the name of the window from which it was created. The
return value is String.
Parent Refers a window that contains a frameset

METHODS OF WINDOW OBJECT

Methods Meaning
onBlur() Triggers when focus is removed from the window
onFocus() Triggers when focus is applied to the window
onError() Triggers when error occurs in the window
onLoad() Triggers when browser finishes loading a document into the window
onUnload() Triggers when user exists from the document within the window

PROPERTIES OF WINDOW OBJECT

The properties of window objects are

1. href 2. protocol 3. host 4. hostname


5. port 6. path 7. hash 8. search.

METHODS OF HISTORY OBJECT


Methods Meaning
Length() Returns the number of entries in the history entity
Back() Helps the web browser to load the previous entry in history object.
Forward() Helps the web browser to load the next entry in history object.

PROPERTIES OF HISTORY OBJECT


Properties Meaning
Current Contains the URL of the current history entity
Length Contains the number of entities in history list
Previous Contains the URL of the previous history stack entity
Next Contains the URL of the next history stack entity

3.11 SIMPLE WEB APPLICATIONS

SIMPLE WEB APPLICATION FOR STUDENT MARK LIST


SIMPLE WEB APPLICATION FOR PAYSLIP GENERATION

172
Refer Class Note book and assignmet

END OF UNIT III

UNIT – IV: DYNAMIC HTML


4.1 Dynamic HTML – Introduction
4.2 Cascading Style Sheets (CSS)

173
4.3 Object Model and Collections
4.4 Event Model
4.5 Filters and Transition
4.6 Data Binding
4.7 Data Control
4.8 ActiveX Control
4.9 Handling of Multimedia Data

4.1 DHTML – DYNAMIC HYPER MARKUP LANGUAGE

• DHTML is a new and emerging technology that has evolved to meet the increasing
demand for eye-catching and mind-catching web sites.

• DHTML combines HTML with Cascading Style Sheets (CSS) and Scripting
Languages. HTML specifies a web page’s elements like table, frame, paragraph,
bulleted list, etc. CSS can be used to determine an element’s size, color, position and a
number of other features.
• Scripting Languages (JavaScript and VBScript) can be used to manipulate the web
page’s elements so that styles assigned to them can change in response to a user’s input.
• The combined technology of HTML and CSS becomes DHTML.
• Similarly the comined technology of HTML and Scripting Languages also becomes
DHTML.

4.2 CASDING STYLE SHEETS (CSS)


• CSS are powerful mechanism for adding styles (e.g. Fonts, Colors, and Spacing) to
web documents.
• They enforce standards and uniformity throughout a web site and provide numerous
attributes to create dynamic effects.
• The advantage of a style sheet includes the ability to make global changes to all
documents from a single location. Style sheets are said to cascade when they combine
to specify the appearance of a page.
The style assignment process is accomplished with the <STYLE>…</STYLE> tags.

174
SYNTAX:
The attributes that can be specified to the <STYLE> tag are
1. Font Attributes
2. Color and Background attributes
3. Text Attributes
4. Border Attributes
5. Margin Attributes and
6. List Attributes.

HOW TO INTRODUCE STYLE IN HTML PROGRAM?

<HTML>
<HEAD>
<STYLE Type = “text/css”>

Predefined tag name {attribute name1:attribute value1; attribute name2:attribute


value2; ……attribute name-n:attribute value-n}

<STYLE>
</HEAD>
<BODY>
write the body of program
</BODY>
</HTML>

EXAMPLE

<HTML>
<HEAD>

175
<STYLE Type = “text/css”>

h1{text-align:center}

<STYLE>
</HEAD>
<BODY>
<b> <h1> Example for CSS program </h1> </b>
</BODY>
</HTML>
Here the text “Example for CSS program” will be printed in center with bold effect.

Note
1. Here the previous properties of <h1> will be over written, and it takes center effect.
2. Along with user defined tags the predefined tags can also be used.

ATTRIBUTES OF STYLE TAG


Style tag attributes are divided into 6 categories. They are

1. Font Attributes
2. Color and Background attributes
3. Text attributes
4. Border attributes
5. Margin attributes
6. List Attributes (Contains only one attribute)

FONT ATTRIBUTES

Attribute Values
Name
Font-family A comma-delimited sequence of font family names (Serif, sanserif, cursive)

176
Font-style Normal, italic or oblique.
Font-size A term that denotes absolute size (xx-small, x-small, small, medium, large,
x-large, xx-large), relative size (larger, smaller), a number (of pixels),
percentage (of the parent element’s size.
Font-weight Normal, bold, lighter, or one of the nine numerical values (100,200 to 900)

COLOR AND BACKGROUND ATTRIBUTES

Attributes Values
Color Sets an element’s text-color- a color name or a color code
Background- Specifies the color in an element’s background. A color name or a color
color code.
Background- Sets the background image. A URL or none.
image
Background- Within the background image specified, sets up how the image repeats
repeat throughout the page. Repeat-x (repeats horizontally), repeat-y(repeats
vertically), repeat(both), no-repeat.
TEXT ATTRIBUTES
Attributes Values
text-decoration Adds decoration to an element’s text- none, underline, overline, line-
through, blink
vertical-align Determines an element’s vertical position. Baseline, sub, super, top, text-
top, middle, bottom, text-bottom, also percentage of the element’s length.
text-transform Applies a transformation to the text. Capitalize (puts the text into initial
caps), uppercase, lowercase or none.
text-align Aligns text with an element. Left, right, center, or justify can be given.
text-indent Indents the first line of text. A percentage of the element’s width or a
length.

BORDER ATTRIBUTES

Attributes Values

177
Border-style Solid, double, groove, ridge, inset, outset

Border-color A color name or color code


Border-width Thin, medium thick or length
Border-top- Thin, medium thick or length
width
Border-bottom- Thin, medium thick or length
width
Border-left-width Thin, medium thick or length
Border-right- Thin, medium thick or length
width
Border-top Specifies width, color and style
Border-bottom Specifies width, color and style
Border-left Specifies width, color and style
Border-right Specifies width, color and style
Border Sets all the properties at once

MARGIN RELATED ATTRIBUTES


Attributes Values
Margin-top Percent, length or auto
Margin-bottom Percent, length or auto
Margin-left Percent, length or auto
Margin-right Percent, length or auto
Margin Percent, length or auto
LIST ATTRIBUTES
Attributes Values
List-style-type Disc, circle, square, decimal, lower-case, upper-roman, lower-roman,
lower-alpha, upper-alpha, none

THE UNITS OF MEASUREMENTS


The attribute values related to number values can have the following measurements.

178
Unit name Abbreviation Explanation Relative
Em Em The height of a font Yes

Ex Ex Height letter x in a font Yes


Pica Pc 1 pica is 12 points No
Point Pt 1/72 of an inch No
Pixel Px One dot on a screen Yes
Millimeter Mm Printing unit No
Centimeter Cm Printing unit No
Inch In Printing unit No

EXTERNAL STYLE SHEETS


• External style sheets are composed of standard text, which consists of a series of
entries, each composed of a selector and a declaration.
• The selector indicates the HTML element(s) affected by the properties in the
declaration.
• These external styles are saved as a file with extension .css which can be linked, to
a web page via the <LINK> tag.
Syntax
<LINK REL = “style sheet HREF = “style sheet file name”>

NOTE: Like <STYLE> tag <LINK> also should be given with in <HEAD>… </HEAD>
tags.

INLINE STYLE SHEETS


1. Inline styles are created and should be used immediately before creating a new
STYLE; otherwise the style will not have any effect.

179
2. The style information can be added to individual HTML elements using the STYLE
attribute, which is available for several HTML elements. The STYLE attribute is
common to almost all tags.
3. Introduce STYLE attribute as given below,

<h1 STYLE =”font-family: arial; font-size: 16mm; color: green>


<center><h1>This is example for Inline Style Sheet
</h1></center>

EXAMPLE FOR STYLE SHEETS

MAIN PROGRAM

<! exmain4.html - exercise no 4 - main program -- >

<html>
<head>
<title>Create Web Page for Different Types of Style Sheets>
</title>
</head>
<body bgcolor = "magenda">
<p>
<font face = "arial" size = "5" color = "blue">
<br>
<center> <h1> Main Menu </h1> </center>
<hr>
<br>
<a href = "ex41.html"> 1. Embeded Style Sheet(Cascading)</a>
<br> <br>
<a href = "ex42.html"> 2. Linked Style Sheet </a>
<br> <br>
<a href = "ex43.html"> 3. Inline Style Sheet </a> <br>
<br>
<hr>

180
</font>
</p>
</body>
</html>

<! ex41.html - exercise no 4 - Embedded Style sheet program -- >

<html>
<head>
<title>Embedded Style Sheet> </title>
<style type = "text/css">

h1 {color:red; font-size:3em; font-family:Arial}


h2 {color:blue; font-size:2em; font-family:Helvetica}
h3 {font-style:Italic; font-weight:bold; color:green; font-size:2em}
h4 {text-align:center}
ul {list-style-type:disc; font-size:1em; color:brown; font-weight:bold}

</style>
</head>

<body bgcolor = "pink">


<p>
<h1> Panimalar Engineering College </h1>
<h4> <h2> Nasarethpet, Poonamallee </h2> </h4>
<h4> <h3> Chennai - 602 103 </h3> </h4>
<hr>
<h3> No. of Courses Offered </h3>
<ul>
<li> IT </li>
<li> CSE </li>
<li> ECE </li>
</ul>
<hr>

<h4> <h3> <a href = "EXMAIN4.html" > Back to Main Menu </a> </h3> </h4>
</p> </body> </html>

<! ex42.html - exercise no 4 - Linked Style sheet program -- >

style4.css

h1{color:red; font-size:3em; font-family:Arial}


h2 {color:blue; font-size:2em; font-family:Helvetica}
h3 {font-style:Italic; font-weight:bold; color:green; font-size:2em}
h4 {text-align:center}
ul {list-style-type:disc; font-size:1em; color:brown; font-weight:bold}
181
------------------Main program-----------------------------------------
<html>
<head>
<title>Linked Style Sheet>
</title>
<link rel = stylesheet href = "style42.css" type = "text/css">
</head>

<body bgcolor = "cyan">


<p>
<h4> <h5> Panimalar Engineering College </h5> </h4>
<h4> <h2> Nasarethpet, Poonamallee </h2> </h4>
<h4> <h3> Chennai - 602 103 </h3> </h4>
<hr>
<h3> No. of Courses Offered </h3>

<ul>
<li> IT </li>
<li> CSE </li>
<li> ECE </li>
</ul>
<hr>

<h4> <h3> <a href = "EXMAIN4.html" > Back to Main Menu </a> </h3> </h4>
</p>
</body>
</html>
<! ex43.html - exercise no 4 - Inline Style sheet program -- >
<html>
<head>

182
<title>Inline Style Sheet>
</title>
</head>

<body bgcolor = "yellow" >


<p>

<h2 style = "color:red; font-size:3em; font-family:Arial">


<center> <h2> Panimalar Engineering College </h2> </center>

<h3 style = "color:blue; font-size:2em; font-family:Helvetica">


<center> <h3> Nasarethpet, Poonamallee </h3> </center>

<h4 style = "font-style:normal; font-weight:bold; color:brown; font-size:2em">


<center> <h4> Chennai - 602 103 </h4> </center>
<hr>
</p>
<p>
<font face = "arial" size = "5" color = "blue" >
<h1> No. of courses offered <h1>

<ul type = disc>


<li> IT
<li> CSE
<li> ECE
<li> EEE
</ul>
<center> <a href = "EXMAIN4.html" > Back to Main Menu </a> </center>
</font>
</p>
</body>
</html>

Note: In Inline style sheet STYLE should be used before creating a new style, otherwise style
will not have any effect.

In any type of CSS program user can use predefined styles along with the user defined
styles.

183
OUTPUT
MAIN PROGRAM

184
EMBEDDED OR CASCADING STYLE SHEET

185
EXTERNAL OR LINKED STYLE STHEET

186
INLINE STYLE SHEET

4.3 OBJECT MODEL AND COLLECTIONS

187
• The object model allows web authors to control the presentation of their pages and
gives them access to all the elements on their web page.

• The whole web page – elements, forms, frames, tables, etc – is represented in an
object hierarchy.

• Using scripting, an author is able to retrieve and modify any properties or attributes of
the web page dynamically.

JAVA SCRIPT – OBJECTS

• Java script uses objects to perform many tasks and therefore is referred to as an object
based programming language.

• There are different objects in Java script

1. MATH OBJECT

Method Description Example


Abs( x ) Absolute value of x abs ( 7.2 ) is 7.2, abs(-5.6) is 5.6
Ceil( x ) Rounds x to the smallest integer not less ceil( 9.2 ) is 10.0
than x
Cos( x ) Trigonometric cosine of x (x in radians) cos ( 0.0 ) is 1.0
Exp( x ) Exponential method exp( 1.0 ) is 2.71828
floor( x ) Rounds x to the largest integer not greater floor( 9.2 ) is 9.0
than x
log (x) Natural logarithm of x (base e) log ( 2.7182 ) is 1.0
max( x, y ) Largest value of x and y Max(10,40)
Min( x, y ) Smaller value of x and y Min(10,40)
Pow( x, y ) X raised to power y Pow(2,3)
round ( x ) Rounds x to the closest integer Round(20.456)
sin ( x ) Trigonometric sine of x (x in radians) Sin(2)
Sqrt ( x ) Square root of x Sqrt(25)
tan ( x) Trigonometric tangent of (x in radians) Tan(1)

2. STRING OBJECT

String can be assigned to a variable in a declaration. The declaration is

188
var color = “blue” or var name = “peter”

Method Description

charAt( index ) Returns a string containing the character at the specified index
charCodeAt( index) Returns the Unicode value of the character at the specified index. If there is
no character at the index, returns NaN (Not a number)
concat ( string ) Concatenates its argument to the end of the string that invokes the method.
slice( start, end ) Returns a string containing the portion of the string from index start through
index end. If the end is not specified, the method returns a string from the
end of the string.
split ( string ) Splits the source string into an array of strings or tokens.
substr( start, end ) Returns a string containing the characters from index start up to but not
including index end in the source string.
toLowerCase(), Converts uppercase into lowercase
toUpperCase() Converts lowercase into uppercase.
Blink, strike, sub, sup Gives blinking, strike through, subscript and superscript respectively
tan ( x) Trigonometric tangent of (x in radians)

3. DATE OBJECT

UTC – Coordinated Universal Time


GMT – Greenwich Mean Time

Method Description

getdate() Returns a number from 1 to 31 representing the day of the month in local
getUTCDate() time or UTC.
getDay() Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of
getUTCDay() the week in local time or UTC
getFullYear() Returns the year as a four digit number in ocal time of UTC.
getUTCFullYear()
getHours() Returns a number from 0 to 23 representing hours since midnight in local
getUTCHours() time or UTC.
roUTCString() Returns a string representation of the date and time in the form 19 sep 2001
valueOf() The time in number of milliseconds since midnight, January 1, 1970

BOOLEAN AND NUMBER OBJECTS

189
Method Description
toString( radix ) Returns the string representation of the number. The
optional radix argument (a number from 2 to 36) specifies
the number’s base. For example, radix 2 results in the
binary representation of the number, 8 represents the octal
representation.
valueof() Returns the numeric value
number.MAX_VALUE This property represents the largest value that can be
stored I a javascript program – approximately 1.79E+308
number.MIN-VALUE This property represents the smallest value that can be
stored I a java script program – approximately 2.22E-308
number.Nan This property represents not a number
number.NEGATIVE_INFINITY This property represents a value less than –
Number.MAX_VALUE
number.POSITIVE_INFINITY This property represents a value greater than –
Number.MAX_VALUE

DOCUMENT OBJECT

Method Description

write( string ) Writes the string to the HTML document as XHTML code
writeln( string ) Writes the string to the HTML document to a new line
document.cookie This property is a string containing the values of all the
cookies stored on the user’s computer for the current
document.
Document.lastmodified This property is the date and time that this document was
last modified.

WINDOW OBJECT

Method Description

open( url, name, options ) Creates a new window with the URL of the window set to
url, the name set to name, and the visible features set by the

190
string passed in as option.
prompt( prompt, default ) Displays dialog box.
close() Closes the current window and deletes its object from
memory
Blur() This method takes focus away from the window
window.document This property contains the document object representing
the document currently inside the window
window.closed Set to true/false if window is closed or not respectively
window.opener Open the current window, if such a window exists.

COOKIES

Cookies provide web developers with a tool for personalizing web pages.

A cookie is a piece of data that is stored on the user’s computer to maintain information about
the client during and between browser sessions.

OBJECT REFERENCING

• The simplest way to reference an element is by using the element’s id attribute.

• The element is represented as an object, and its various XHTML attributes become
properties that ca be manipulated by scripting.

EXAMPLE PROGRAM

<!-- SCRIPT PROGRAM - FOR OBJECT REFERENCING>

<html>
<head>
<title> Object reference program </title>

<Script Language = "JavaScript">

function start()
{
alert( pText.innerText );
pText.innerText = "Thanks for comming";
}

191
</script>
</head>

<body onload = "start()">

<p id = "pText"> Welcome to our web page</p>

</body>
</html>

OUTPUT

Thanks for coming

192
COLLECTIONS ALL AND CHILDREN

Collections, which basically arrays of related objects on a page. There are several special
collections in the object model.

DHTML OBJECT MODEL

Window

All

Document
Anchors
Frames Document

History Applets

Body
Navigator Plugins
Embeds
Location
Filters
Event

Forms
193

Images
Screen

Object or Description
Collection
Window Represents the browsers window and provides access to the document
Document Provides access to DHTML
Body history Keeps track of the sites visited by the browser user.
Navigator Contains information about the web browser, such as the name of the
browser, the version etc.
Location Contains the URL of the rendered document.
Event Can be used in an event handler to obtain information about the event
that occurred.
All Many objects have an all collection that provides access to every
element contained in the object. For example body element provides
access to every element in the form.
Anchors Collection contains all the anchor element that have a name or id
attribute
Frames Contains window objects that represent each frame in the browser
window. Each frame is treated as its own sub window.
Scripts Contains all the script elements in the HTML window
StyleSheets Contains style sheet object that represent each style element in the
XHTML document and each style sheet included in the XHTML
document via link.

<!-- COLLECTION ALL AND CHILDREN


<!--------------------------------------------------->

<html>
<head>
<title> COLLECTIONS ALL AND CHILDREN </title>

<Script Language = "JavaScript">

194
var elements = "";

function start()
{

for (var i = 0; i < document.all.length; i++)

elements += "<br />" + document.all[ i ] . tagName;

pText.innerHTML += elements;
alert( elements );
}

</script>
</head>

<body onload = "start()">

<p id = "pText"> Elements on this web page: </p>

</body>
</html>

OUTPUT

DYNAMIC HTML - OBJECT MODEL AND COLLECTIONS

195
1. The Dynamic HTML Object Model gives web authors great control over the
presentation of their pages by giving them access to all the elements on their web
page. The whole web page –elements, forms, frames, tables, etc – represented in an
object hierarchy.

2. The simplest way to reference an element is by its id attributes. The element is


represented as an object, and its various XHTML attributes become properties that
can be manipulated by scripting.

3. The innerText property of the object refers to the text contained in the element.

4. Changing the text displayed on screen is a Dynamic HTML ability called dynamic
content.

5. Every element has its own all collection consisting of all the elements contained in
the element.

4.4 DYNAMIC HTML – EVENT MODEL

Dynamic HTML with the event model exists so that scripts can respond to user interactions
and change the page accordingly. This makes web applications more responsive and user
friendly and can reduce server load.

MORE DHTML EVENTS

Event Description

onbeforecut Fires before a selection is cut to the clipboard


onbeforecopy Fires before a selection is copy to the clipboard
onbeforepaste Fires before a selection is paste to the clipboard

onbeforeupdate Fires before a data source is updated


onafterupdate Fires after a data source is updated

onrowenter,onrowexit, Related to rows.

196
onrowsdelete,onrowsinserted

onhelp, onkeydown, Fires help, keydown and keyup respectively


onkeyup
ondbclick, ondrag, ondrop
onchange Fires when a new change occurred

<!-- EVENT MODEL FOR ONCLICK EVENT – PROGRAM 1


<!----------------------------------------------------->

<?xml version = "1.0"?>


<!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">

<head>

<title> EVENT MODEL - ON CLICK EVENT </title>

<script type = "text/javascript" for = "para" event = "onclick">

alert("Hai Clik performed");

</script>
</head>

<body>
<p id = "para"> Click on this button </p>

<input type = "button" value = "Click Here" onclick = "alert( 'Try agin' )" />

</body>
</html>

<!-------------------------------------------------------------------------------->
<! NOTE>
<! ------>

<! para represents p element>

<! Attribute id specifies a unique identifier foran XHTML element.>

197
<!--------------------------------------------------------------------------------->

OUTPUT

EVENT BUBBLING

1. Event bubbling is the process whereby events fired in child elements "bubble” Up
their parser elements.
2. When a child event is fired, the event is first delivered to the child’s event handler,
then to the parent's event handler.

3. If you intend to handle an event in a child element, you might need to cancel the
bubbling of the event in the child element's event-handling code by using the
cacelBubble property of the event object.

EXAMPLE FOR EVENT BUBBLING

<?xml version = "1.0"?>


<!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">

198
<head>

<title> EVENT BUBBLING </title>

<script type = "text/javascript">

function documentClick()
{
alert( "You clicked in the document" );
}

function paragraphClick( value )


{

alert( "You clicked the text" );

if ( value )
event.cancelBubble = true;
}

document.onclick = documentClick;

</script>
</head>

<body>

<p onclick = "paragraphClick( false )"> Click here </p>

<p onclick = "paragraphClick( true )"> Click here too!</p>

</body>
</html>

OUTPUT

199
DYNAMIC STYLES – EXAMPLE PROGRAM

Dynamic styles are used to change effect during run time.

<!-- DYNAMIC STYLES EXAMPLE PROGRAM - FOR CHANGING THE


BACKGROUND COLOR ACCORDING TO THE GIVEN INPUT COLOR
<!----------------------------------------------------------------------------------------->

<?xml version = "1.0"?>


<!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">

<head>

200
<title> Object model - Dynamic styles </title>

<script type = "text/javascript">

function start()
{
var inputColor = prompt("Enter a color for the " + "background of this page", "");

document.body.style.backgroundColor = inputColor;
}

</script>
</head>
<body onload = "start()">
<p> <h1> Welcome to our web site </h1> </p>
</body>
</html>

OUTPUT

Since the background color is given as white the output is displayed as follows:

DYNAMIC STYLES – EXAMPLE 2 – for printing text in Big or normal font size

<!-- DYNAMIC STYLES - USER DEFINED


<!------------------------------------------>

<?xml version = "1.0"?>

201
<!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">


<head>

<title> Object model - Dynamic styles - using style tag </title>

<style type = "text/css">

.bigText { font-size: 3em; font-weight: bold }

.mediumText { font-size: 1.5em; font-weight: bold }

.smallText { font-size: .75em }

</style>

<script type = "text/javascript">


function start()
{
var inputClass = prompt( "Enter a className for the text " + "(bigText or smallText)", "");

pText.className = inputClass;
}
</script>
</head>

<body onload = "start()">

<p id = "pText"> Welcome to our web site </p>


</body>
</html>

OUTPUT

The input value can be either (bigText or smallText)

If the input value is bigText, then the output is

202
If the input value is smallText, then the output is

OUTPUT

4.5 DYNAMIC HTML – FILTERS TRANSITIONS (Changeover, conversion,


shift)

• Filters and transitions are specified with the CSS filter property.

• Applying filters to text and images causes changes that are persistent.

• Transitions are temporary: applying a transition allows you to transfer from one
page to another with a pleasant visual effect, such as a random dissolve.

• Filters and transitions do not add content to your pages – rather, they present
existing content in an engaging manner to capture the user’s attention.

• Each of the visual effects achievable with filters and transitions if programmable, so
these effects can be adjusted dynamically by programs that respond to user-initiated
events, such as mouse clicks and keystrokes.

FLIP - FILTERS – FLIPv AND FLIPh

• The flipv and fliph filters mirror text or images vertically and horizontally.

<!-- EVENT MODEL FOR ONCLICK - FILTERS1.HTML


<!------------------------------------------>

203
<?xml version = "1.0"?>
<!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">

<head>

<title> THE FLIP FILTER - FILTERS1.HTML </title>

<style type = "text/css">

body { background-color: cyan } table { font-size: 3em; font-family:arial,


sans-serif; background-color:pink; border-style: ridge}

td { border-style: groove; padding: lex }

</style
</head>

<body>

<table>

<tr>

<!-- Filters are applied in style declarations ---->


<! ------------------------------------------------>

<td style = "filter: fliph"> Text </td>

<td> Text
</tr>

<!-- More than one filter can be applied at once---->


<! ------------------------------------------------>

<tr>

<td style = "filter: flipv fliph"> Text </td>


<td style = "filter: flipv"> Text </td>

204
</tr>

</table>

</body>
</html>

OUTPUT

fliph filter applied

filpv filter applied

Both

4.6 DATA BINDING

• With data binding, data need to longer reside exclusively on the server.

• Data can be maintained on the client, in a manner that distinguishes it from the
XHTML markup on the page.

205
• Typically, data is sent to the client. All subsequent manipulations than take place on
the data directly on the client, thus eliminating server activity and network delays.
• Once it is available on the client, the data can be sorted and filtered in various
ways.

• In data binding technology, data made on the client do not propagate (spread,
broadcast) back to the server.

• Once it is available on the client, the data can be sorted and filtered in various
ways.

• To bind external data to XHTML elements, Internet Explorer employs software


capable of connecting the browser to live data sources. These are known as Data
Source Objects (DSOs).

• The most popular DSO is – the Tabular Data Control (TDC).

RECORDSET
A recordset is simply a set of data or rows to be accessed by the program. It contains the
following recordset object methods.

1. MoveNext – used to move the recordset to the next row.


2. MovePrevious – used to move the recordset to the previous row.
3. MoveFirst – used to move the recordset to the first record immediately.
4. MoveLast – used to move the recordset to the last record immediately.

Note move previous and move next methods should be used before checking BOF(),
EOF() methods respectively.

4.7DATA CONTROL
4.8ACTIVX CONTROL

SAMPLE PROGRAM:

<html>
<head>
<object id="colors"
classid = "CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83">

206
<param name="DataURL" value="color.txt">
<param name="UseHeader" value="TRUE">
<param name="TextQualifier" value="@">
<param name="FieldDelim" value="|">
</object>
<script>
var rs=colors.recordset;

function display()
{
recno.innerText="Record Number =" + rs.absolutePosition;
test.style.color=rgbval.innerText;

function forward()
{
rs.moveNext();
if(rs.EOF)
rs.moveFirst();
display();

}
</script>

</head>
<body onload="display()" onclick="forward()">
Color Name :<span id="rgbtext" datasrc="#colors" datafld="colorName"></span> <br>
Color Hex Value :<span id="rgbval" datasrc="#colors"
datafld="ColorHexVal"></span><br>
datafld="ColorHexVal"></span><br>
<span id="recno" ></span><br>

<h1 id ="test" style="color:blue"> testing </h1>


</body>
</html>

COLOR.TXT:

@colorName@|@ColorHexVal@
@red@|@#FF0000@
@green@|@#00FF00@
@blue@|@#0000FF@
@black@|@#000000@

207
@white@|@#FFFFFF@

OUTPUT WINDOW:

208
COLOR MOVING

SAMPLE PROGRAM:

<html>
<head>
<object id="colors"
classid = "CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83">
<param name="DataURL" value="color.txt">
<param name="UseHeader" value="TRUE">
<param name="TextQualifier" value="@">
<param name="FieldDelim" value="|">
</object>

<script>
var rs=colors.recordset;

function display()
{
recno.innerText="Record Number =" + rs.absolutePosition;
test.style.color=rgbval.innerText;
}

function move(loc)
{
switch(loc)
{
case "first":
rs.moveFirst();
break;

case "last":
rs.moveLast();
break;

case "next":
rs.moveNext();
if(rs.EOF)
rs.moveFirst();
break;

case "prev":

209
rs.movePrevious();
if(rs.BOF)
rs.moveLast();
break;

}
display();
}
</script>

</head>
<body onload="display()" >
Color Name :<span id="rgbtext" datasrc="#colors" datafld="colorName"></span> <br>
Color Hex Value :<span id="rgbval" datasrc="#colors"
datafld="ColorHexVal"></span><br>
<span id="recno" ></span><br> <br>

<input type="button" value="movefirst" onclick="move('first')">


<input type="button" value="moveLast" onclick="move('last')">
<input type="button" value="movenext" onclick="move('next')">
<input type="button" value="moveprevious" onclick="move('prev')">
<h1 id ="test" style="color:blue"> testing </h1>
</body>
</html>

OUTPUT WINDOW

210
COLOR SORT

SAMPLE PROGRAM:

<html>
<head>
<object id="colors"
classid = "CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83">
<param name="DataURL" value="color.txt">
<param name="UseHeader" value="TRUE">
<param name="TextQualifier" value="@">
<param name="FieldDelim" value="|">

211
</object>

</head>
<body >
<h1> Binding to an Table </h1>

<Table datasrc="#colors" border=5>

<caption>
Sort by :
<select onchange="colors.Sort=this.value;colors.Reset();">
<option value="colorName"> Color Name (Asce) </option>
<option value="-colorName"> Color Name (Desc) </option>
<option value="colorHexVal"> Color Hex (Asce) </option>
<option value="-colorHexVal"> Color Hex (Desc) </option>
</select>

</caption>
<thead>
<tr>
<th> Color Name </th>
<th> Color RGB </th>
</tr>
</thead>

<tbody>
<tr>
<td><span datafld="colorName"> </span> </td>
<td><span datafld="ColorHexVal"> </span> </td>
</tr>
</tbody></table></body></html>

OUTPUT WINDOW:

212
BINDING TO AN TABLE EXAMPLE (USING COLOR.TXT FILE

SAMPLE PROGRAM:

<html>
<head>
<object id="colors"
classid = "CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83">
<param name="DataURL" value="color.txt">
<param name="UseHeader" value="TRUE">
<param name="TextQualifier" value="@">
<param name="FieldDelim" value="|">
</object>

</head>
<body >
<h1> Binding to an Table </h1>

213
<Table datasrc="#colors" border=5>

<thead>
<tr>
<th> Color Name </th>
<th> Color RGB </th>
</tr>
</thead>

<tbody>
<tr>
<td><span datafld="colorName"> </span> </td>
<td><span datafld="ColorHexVal"> </span> </td>
</tr>
</tbody>

</table>
</body>
</html>

OUTPUT WINDOW:

214
4.9 HANDLING OF MULTIMEDIA DATA

IMAGE MOVE - SAMPLE PROGRAM:

215
<html>
<head>

<object id="images"
classid = "CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83">
<param name="DataURL" value="img.txt">
<param name="UseHeader" value="TRUE">
</object>

<script>
var rs=images.recordset;

function display()
{
recno.innerText="Record Number =" + rs.absolutePosition;

function move(loc)
{
switch(loc)
{
case "first":
rs.moveFirst();
break;

case "last":
rs.moveLast();
break;

case "next":
rs.moveNext();
if(rs.EOF)
rs.moveFirst();
break;

case "prev":
rs.movePrevious();
if(rs.BOF)
rs.moveLast();
break;

216
display();
}
</script>

</head>
<body onload="display()" >
<span id="recno" ></span><br> <br>

<img datasrc="#images" datafld="image" style="position:relative ;left:100; " width=300


height=300> <br>

<input type="button" value="movefirst" onclick="move('first')">


<input type="button" value="moveLast" onclick="move('last')">
<input type="button" value="movenext" onclick="move('next')">
<input type="button" value="moveprevious" onclick="move('prev')">

</body>
</html>

IMG.TXT:

image
E:\images\image1.bmp
E:\images\image2.bmp
E:\images\image3.bmp
E:\images\image4.bmp
E:\images\image5.bmp
E:\images\image6.bmp
E:\images\image7.bmp
E:\images\image8.bmp
E:\images\image9.bmp

OUTPUT WINDOW:

217
END OF UNIT - IV

218
UNIT – V: SERVER SIDE PROGRAMMING

5.1 Servlets
5.2 Deployment of simple servlets
5.3 Web server (Java web server / Tomcat / Web logic)
5.4 HTTP GET and POST requests
5.5 Session tracking
5.6 Cookies
5.7 JDBC
5.8 Simple web applications
5.9 Multi-tier applications.

5.1 SERVLETS

• Sun Microsystems, through the Java Community Process, is responsible for the
development of the Servlet and JavaServer Pages specifications.

• The reference implementation of both these standards is under development by the


Apache Software Foundation (www.apache.org) as part of the Jakarta Project
(jakarta.apache.org)

Study Lab exercise for Servlet example program

5.2 DEPLOYMENT OF SIMPLE SERVLETS (DEPLOYING A


SERVLET):

A web application has a well known directory structure which all the files that are part
of web application reside.

The web application directory structure contains a context root –the top level directory
for an entire application.

Context root This is the root directory for the web application.all the jsps,html
documents ,servlets and supporting files such as images,and class files

219
reside in this directory or its subdirectories.

WEB-INF This directory contains the web application deployment descriptor

WEB- This directory contains the servlets class files and other supporting class
INF/classes used in the application.

WEB-INF/lib This directory contains java archive files .the jar files can contain
servlet class files and other supporting class files.

Configuring the context root for a web application in tomcat requires creating a sub
directory in the web apps directory.

After configuring the context root ,we must configure our web application to handle
requests.this configuration occurs in web.xml as follows:

<web-app>

<display-name>

internet world wide web and how to program

</display-name>

<description>

this is the web application in which we demonstrate our jsp and

servlet examples

</description>

<servlet>

<servletname> welcome1</servletname>

<description>a simple servlet that handles an http get

request</description>

220
<servlet-class>Welcomeservlet</servlet-class>

<servlet>

<servlet-mapping>

<servletname>welcome1</servletname>

<url-pattern>/welcome1</url-pattern>

</servlet-mapping>

</web-app>

• Element web-app defines the configuration of each servlet in the web


application and the servlet mapping for each servlet..

• Element display-name specifies a name that can be displayed to the


administrator of the server.

• Element servlet desribes a servlet.

• Element servlet-name specifies the name of the servlet

• Element description defines a description of the servlet.

• Servlet-mapping element specifies the servlet name and its url name.

We can run our servlet by using the url:

http://localhost:8080/iw3htp3/welcome1

Finally we are ready to place our files into the appropriate directories .create a directory
structure as follows:

Iw3htp3

Servlets

221
Welcomeservlet.html

WEB-INF

Web.xml

Classes

Welcomeservlet.class

After creating this structure we can run our application by opening a web browser and
type:

http://localhost:8080/iw3htp3/servlets/welcome.html

5.3 INTRODUCTION TO JAVA WEB SERVER

THE TERM WEB SERVER CAN MEAN ONE OF TWO THINGS:

1. A computer program that is responsible for accepting HTTP requests from clients,
which are known as web browsers, and serving them HTTP responses along with
optional data contents, which usually are web pages such as HTML documents and
linked objects (images, etc.).

2. A computer that runs a computer program which provides the functionality described
in the first sense of the term.

In other words, Web server is an application that responds to HTTP requests by returning
‘web’ resources (e.g., HTML files, images, applets,CGI output, …) over the Internet.

5.3.1 THE JAVA WEB SERVER

For the developer that dabbles in Java programming, servlets can be used to turn the
Java Web Server into their own personal Web application server.

One of the slickest pieces of software to come from JavaSoft recently is the Java Web Server
(formerly known as Jeeves).

While the Java Web Server can be used for serving up Web sites just like any other Web
server (using SSL, CGI scripts, authentication and more), its ability to use Java servlets is
what makes it stand out from other Web servers.

222
For the developer that dabbles in Java programming, servlets can be used to turn the Java
Web Server into their own personal Web processor.

Servlets, (server-side applets), are very similar to applets in that they can both be
included in Web pages and they both run on any Java-enabled platform-but servlets have no
graphical front end. Servlets can be used to insert, sort and delete data from a database, create
roaming Web agent servlets, interactive HTML editors…or perform just about any Web-
related function.

Not only can you use servlets with the Java Web Server, but you can also use them
with Netscape FastTrack and Enterprise servers, the JigSaw Web server, and the Acme Serve
Web server. As the development and acceptance of Java continues to escalate, more and more
Web servers will conform to the Java Server API.

To create servlets you'll need to download the Servlet Development Kit from the
JavaSoft site and you'll also need to already have the Java Development Kit 1.1 installed.

You can also get the JDK 1.1. from JavaSoft's site, but keep in mind that applets
produced with the JDK 1.1 are not yet supported by the release versions of Netscape
Navigator or Microsoft Internet Explorer (they should be supported in the next release of
both browsers).

The Java Web Server was created using the Java Server API. The Java Server API is a
"cross-platform, extensible framework for the creation of network-centric server solutions."

The Java Web Server is one of the first applications that Sun developed using the Java
Server API. It is administered (locally or remotely) through any Java-capable browser.

While the Java Web Server is already a very full-featured Web server, it ships with
several Core servlets that further enhance its functionality.

THE CORE SERVLETS INCLUDE:

1. File Servlet - provides the standard document serving capabilities of the Java Server,
including caching and parsing for SSIs.

2. Invoker Servlet - invokes other servlets which are explicitly requested by name

3. Server Side Include Servlet - any file with a .shtml extension is parsed and written out to
the client, and the embedded servlet is loaded .

4. Admin Servlet - provides administration of the Java Web Server through a browser front
end.

223
5. CGI Servlet - acts as a gateway for the CGI 1.1 interface; any standard CGI 1.1 program
will run in this platform..

6. Imagemap Servlet - enables the use of standard NCSA server-side imagemaps

AMONG THE SERVLETS THAT ARE INCLUDED, BUT NOT


DOCUMENTED, ARE:

1. BBoardServlet - a bulletin board servlet

2. ChatServlet - a real time chat servlet

3. DBDataEncoder - encodes data into a database

4. MailServlet - take the input from a form and emails it

5. RedirectServlet - a servlet to redirect the client

6. SimpleFormServlet - a servlet that takes form input and redirects it into an HTML page

HOW JAVA WEB SERVERS WORK

A web server is also called a Hypertext Transfer Protocol (HTTP) server because it
uses HTTP to communicate with its clients, which are usually web browsers. A Java-based
web server uses two important classes, java.net.Socket and java.net.ServerSocket, and
communicates through HTTP messages. Therefore, this article starts by discussing of HTTP
and the two classes.

HTTP is the protocol that allows web servers and browsers to send and receive data
over the Internet. It is a request and response protocol--the client makes a request and the
server responds to the request. HTTP uses reliable TCP connections, by default on TCP port
80. The first version of HTTP was HTTP/0.9, which was then overridden by HTTP/1.0. The
current version is HTTP/1.1

In HTTP, the client always initiates a transaction by establishing a connection and


sending an HTTP request. The server is in no position to contact a client or to make a
callback connection to the client. Either the client or the server can prematurely terminate a
connection. For example, when using a web browser, you can click the Stop button on your
browser to stop the download process of a file, effectively closing the HTTP connection with
the web server.

224
5.3.2 TOMCAT

TOPICS COVERED IN TOMCAT:

• DEFINITIONS OF TOMCAT.
• JBOSS.
• JAKARTA.
• INSTALLING AND CONFIGURING TOMCAT.
• EMBEDDING TOMCAT INTO JAVA APPLICATIONS .
• CONFIGURING TOMCAT AND APACHE WITH JK 1.2
• USING TOMCAT FOR SECURITY REALMS.

DEFINITION FOR TOMCAT:


• The Tomcat server is a Java based Web Application container that was created to run
Servlets and JavaServer Pages (JSP) in Web applications.

• A popular Java servlet container from the Apache Jakarta project. Tomcat uses the
Jasper converter to turn JSPs into servlets for execution. Tomcat is widely used with
the JBoss application server.

JAKARTA:

A project of the Apache Software Foundation that manages numerous open source
products for the Java platform. Examples are the Tomcat servlet container, Cactus test
framework, Tapestry application framework and Ant compilation utility.

JBOSS:

A popular open source application server that supports Enterprise JavaBeans(EJBs).


In order to run servlets and JSPs, a servlet container, such as Apache's Tomcat, is used in
conjunction with JBoss

JAVASERVER PAGES:
• Tomcat is a free, open-source implementation of Java Servlet and JavaServer Pages
technologies developed under the Jakarta project at the Apache Software Foundation.

225
• Tomcat is available for commercial use under the ASF license from the Apache web
site in both binary and source versions.

• Sun adapts and integrates the Tomcat code base into the J2EE SDK and owns and
evolves the JavaServer Pages and Java Servlets specifications under the Java
Community Process.

PRODUCT FEATURES:
• Tomcat 3.x (inital release)
• Tomcat 4.x
• Tomcat 5.x
• Tomcat 6.x

INSTALLING AND CONFIGURING TOMCAT:


STEPS:
• the requirements for installing and configuring Tomcat,
• the process of installing and configuring Tomcat, and
• deploying Tomcat web applications. Requirements for Installing and Configuring
Tomcat
Before performing the tasks outlined by this article you will
need to download the items listed in the Table 1.

Table 1. Requirements

Name Location

Tomcat 4.0 beta 1 http://jakarta.apache.org/

JDK 1.3 Standard Edition

INSTALLING TO WINDOWS NT/2000

The first thing you need to do is install the JDK, following its installation instructions.

• For this article we are installing the JDK to drive D:, therefore my JAVA_HOME
directory is D:\jdk1.3.

226
• Now you need to extract the Tomcat server. Again, we are installing to drive D:,
which will make my TOMCAT_HOME directory D:\jakarta-tomcat-4.0-b1.
• After you have extracted Tomcat, the next step is putting your JDK into Tomcat's
CLASSPATH and setting the TOMCAT_HOME environment variable.
• To do this under NT/2000, you must

1. Open the NT/2000 Control Panel. You should see an image similar to Figure 1.

2. Start the NT/2000 System Application and select the


Advanced tab. You should see a screen similar to
Figure 2.

227
3. Select the Environment Variables button. You will
see a screen similar toFigure3

4. Select the New button on the System Variables section of the Environment Variables
dialog. Add a JAVA_HOME variable and set its value to the location of your JDK
installation. Figure 4 shows the settings associated with my installation.

228
1. Repeat Step 4 using TOMCAT_HOME for the variable name and the location of your
Tomcat installation as the value. For my installation I am setting the value to
D:\jakarta-tomcat-4.0-b1

EMBEDDING TOMCAT INTO JAVA APPLICATIONS


Java Web Applications :
This article is the first in a series of articles on Apache's Jakarta-Tomcat server.

The Tomcat server is a Java-based Web Application container that was created to run
Servlet and JavaServer Page web applications. It has become the reference implementation
for both the Servlet and JSP specifications.

 The purpose of this first article is to give you a basic understanding of web applications.
STEPS:

• The Definition of a Web Application,


• The Directory Structure of a Web Application,
• The Web Application Deployment Descriptor, and Packaging a Web Application

THE DEFINITION OF A WEB APPLICATION

• A "Web Application is a collection of servlets, html pages, classes, and other


resources that can be bundled and run on multiple containers from multiple
vendors." To you and me, a web application is anything that resides in the web
layer of an application.

• One of the main characteristics of a web application is its relationship to the


ServletContext. Each web application has one and only one ServletContext.

• The following items can exist in a web application:

229
• Servlets

• JavaServer Pages

• Utility Classes

• Static Documents including, XHTML, images, etc.

• Client side classes

• Meta information that describes the web application

• Note: For this series we will be using the proposed Servlet SDK 2.3.

THE DIRECTORY STRUCT OF A WEB APPLICATION:

• The container that holds the components of a web application is the directory structure in
which it exists.

• The first step in creating a web application is creating this structure. The following table
contains a sample web application, named onjava.

• Each one of these directories should be created from the <SERVER_ROOT> of the
servlet container.

• An example of a <SERVER_ROOT> , using Tomcat, would be /jakarta-tomcat-


4.0/webapps.

THE WEB APPLICATION DIRECTORY STRUCTURE

/onjavaThis is the root directory of the web application. All JSP and XHTML files are
stored here.

/onjava/WEB-INFThis directory contains all resources related to the application that are
not in the document root of the application.

/onjava/WEB-INF/classesThis directory is where servlet and utility classes are located.

230
/onjava/WEB-INF/libThis directory contains Java Archive files that the web
application depends upon.

THE WEB APPLICATION DEPLOYMENT DESCRIPTOR AND


PACKAGING A WEB APPLICATION:

• At the heart of all web applications is a deployment descriptor. The deployment


descriptor is an XML file named web.xml located in the
/<SERVER_ROOT>/applicationname/WEB-INF/ directory.

• It describes configuration information for the entire web application. For our
application the location of the web.xml file is in the /<SERVER_ROOT>/onjava
/WEB-INF/ directory.

• Deployment Descriptor Includes the Following Elements:

• ServletContext Init Parameters

• Localized Content

• Session Configuration

• Servlet / JSP Definitions

• Servlet / JSP Mappings

• Mime Type Mappings

• Welcome File list

• Error Pages

• Security

231
WEB.XML

<web-app>
<display-name>The OnJava App</display-name> <session-timeout>30</session-
timeout>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.onjava.TestServlet</servlet-class> <load-on-startup> 1 </load-
on-startup>
<init-param>
<param-name>name</param-name>
<param-value>value</param-value>
</init-param>
</servlet>
</web-app>

In this example we are setting three application level elements.

• The first of the application level elements is the <display-name>. This element simply
describes the name of the web application. It is functionally inoperative.

• The second web application level element is the <session-timeout> element. This
element controls the lifetime of the application's HttpSession object.

• The <session-timeout> value that we have used above tells the JSP/Servlet container
that the HttpSession object will become invalid after 30 minutes of inactivity.

• The last application level element that we have defined is the <servlet> element.
This element defines a servlet and its properties. We will further define the <servlet>
elements when we discuss deploying Servlets and JSPs to Tomcat in a subsequent
article.

CONFIGURING TOMCAT AND APACHE WITH JK 1.2:

1. Configuring Tomcat and Apache using JK v1.2

2. Configuring Tomcat and IIS using JK v1.2

3. Configuring Tomcat and Apache using JK v2

4. Configuring Tomcat and IIS using JK v2

232
WHAT IS JK V1.2?

• In the simplest terms, the JK modules, or mod_jk, are conduits between a Web server and
the Tomcat JSP/servlet container. They replace the previous Web server module,
mod_jserv, which had many shortcomings.

• The new JK modules include support for a wider variety of Web servers, better SSL
support, support of the AJP13 protocol, and support for the entire Tomcat series from
3.2.x to 5.x.

COMPONENTS REQUIRED TO CNFIGURE TOMCAT AND APACHE:

1) Install Apache as described in its packaged documentation.

2) Test the Apache installation, by starting Apache and opening your browser to
http://localhost. You should now see an image similar to Figure

1.

Figure 1 The Apache Installation Test Page

233
3) Install Tomcat as described by its documentation.

4) Set the environment variable JAVA_HOME equal to the root directory of your JDK
installation.

5) Set the environment variable CATALINA_HOME equal to the root directory of you Tomcat
installation.

6) Test the Tomcat installation by starting Tomcat and opening your browser to
http://localhost:8080. You should now see an image similar to Figure 2.

Figurev2. The Tomcat Default Homepage

7) Now shut down both Apache and Tomcat, before moving on to the next sections.
Configuring Tomcat and Apache With the JK 1.2 Connector:

It is now time to begin the actual integration between Apache and Tomcat. This process can
be broken down into two sections:

 Configuring Tomcat and


 Configuring Apache.

234
CONFIGURING TOMCAT:

• To begin our Tomcat and Apache integration, we need to first tell Tomcat that it
should start listening for AJP13 requests; both JK and JK2 use AJP13 to
communicate with Tomcat.

• To do this, we need to add an additional <Connector> element to Tomcat's


server.xml file. Add the following entry to server.xml, making sure that it is inside
of the <Service> element and immediately follows any previously-defined
<Connector> elements.

<Connector className="org.apache.ajp.tomcat4.Ajp13Connector"
port="8009" minProcessors="5" maxProcessors="75"
acceptCount="10" debug="0"/>

• The only two attributes in this <Connector> worth noting are the port and
className attributes.

• The port attribute tells Tomcat that it needs to open a new Connector that listens to
port 8009 for incoming requests.

• The className attribute tells Tomcat that all of the requests coming in on this port
should be serviced by the Tomcat Connector class
org.apache.ajp.tomcat4.Ajp13Connector, which also uses the AJP 1.3 protocol.

CONFIGURING APACHE:

• Now that Tomcat is configured to listen to port 8009 for incoming AJP13 request,
let's tell Apache to actually talk to Tomcat using that port and protocol.

• This part is complicated than Tomcat's equivalent configuration, so I have broken it


down into several sections.

CREATE A TOMCAT WORKER

• A Tomcat worker is a process that defines a communications link between Apache


and a Tomcat container.

235
• Tomcat Workers refers to the actual Jakarta documentation. The Tomcat worker file,
in this example, should be named workers.properties and should be copied into the
<CATALINA_HOME>/conf directory of the Tomcat instance that you will be
integrating with Apache.

EXAMPLE:

worker.list=testWorker
worker.testWorker.port=8009
worker.testWorker.host=localhost
worker.testWorker.type=ajp13
• We can then modify the attributes of that worker explicitly using the following
syntax:

worker.testWorker + name of property being modified

PROPERTY:

<workername>.portThe port property defines the port number of this Tomcat worker. This
value must match the port attribute of the previously defined Tomcat <Connector> element.

<workername>.hostThe host property defines the hostname of this Tomcat worker.


Because we are configuring both Apache and Tomcat on the same host, this value is currently
set to localhost.
<workername>.typeThe type property defines the protocol of this Tomcat worker, which in
our case is ajp13.

USING TOMCAT FOR SECURITY REALMS:

In this article, we will


• Define security realms
• Describe Memory Realms
Security Realms:

 A security realm is a mechanism used for protecting Web application resource.

 It gives you the ability to protect a resource with a defined security constraint and

then define the user roles that can access the protected resource.

236
 Tomcat has this type of realm functionality built in.

 The component that provides this functionality is the org.apache.catalina.Realm

interface.

 It provides a mechanism by which a collection of usernames, passwords, and their

associated roles can be integrated into Tomcat.

 If you download the Tomcat source, you will find this interface in the following

location:

<tomcat_home>/src/catalina/src/share/org/apache/catalina/Realm.java

MEMORY REALMS:

 The first Realm implementation provided with Tomcat is a memory realm.


 The class that defines the memory realm is
org.apache.cataline.realm.MemoryRealm.

 The MemoryRealm class uses a simple XML file as a container of users. The
following code snippet contains a sample memory realm XML file:

<tomcat-users>
<user name="tomcat" password="tomcat" roles="tomcat" />
<user name="role1" password="tomcat" roles="role1" />
<user name="both" password="tomcat" roles="tomcat,role1" />
</tomcat-users>

Note: The default location of the MemoryRealms XML file is the


<tomcat_home>/conf/tomcat-users.xml.

.Table 1 contains a description of each of the attributes required in the <user> sub-element.

Table 1. The Attributes of the <user> Sub-Element


Attribute Description

237
Name The name attribute contains a string representing the username that will be
used in the login form.

password The password attribute contains a string representing the password that will be
used in the login form.

Roles The roles attribute contains the role or roles assigned to the named user. This is
the value that must match the <role-name> sub-element of the security
constraint defined in the web applications web.xml file. If more than one role is
assigned to the user, then the value of the roles attribute must contain a comma-
separated list of roles.

PROTECTING A RESOURCE WITH A MEMORYREALM:

 To actually see how a MemoryRealm works, let's create a realm that protects a
sample web application named /onjava. At this point, if you have not already done
so, take a look at my previous OnJava article, Deploying Web Applications to
Tomcat. We will be using the /onjava web application from it.

 The steps involved in setting up a new MemoryRealm are described in the following
list.
1) Open <tomcat_home>/conf/server.xml and uncomment the following line.
<Realm className="org.apache.catalina.realm.MemoryRealm" />

2) By un-commenting this <realm> entry, you are making the MemoryRealm the default
realm implementation for the entire default container. If you cannot find this entry, add it
directly under the Engine sub-element.

3) Open <tomcat_home>/webapps/onjava/WEB-INF/web.xml and add the following security


constraint:

<security-constraint>
<web-resource-collection>
<web-resource-name>OnJava Application</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>onjavauser</role-name>
</auth-constraint>
</security-constraint>

238
 There are only two sub-elements that you need to focus upon. The first is the <url-
pattern> sub-element.

 This sub-element defines the URL pattern that will be protected by the resource. The
entry you included protects the entire /onjava Web application.

 The second sub-element, <role-name>, defines the user role that can access the
resource protected by the previously defined <url-pattern>.

4) Add the following <login-config> sub-element directly following the


<security-constraint>.

<login-config>
<auth-method>BASIC</auth-method>
<realm-name>OnJava Application</realm-name>
</login-config>

 The <login-config> sub-element defines the authentication method for the defined
realm. The possible values are BASIC, DIGEST, and FORM.

 And the <realm-name> sub-element names the Web resource that this <login-
config> maps to.

5) Open <tomcat_root>/conf/tomcat-users.xml and add the following <user> sub-element:


<user name="bob" password="password" roles="onjavauser" />
 The <user> sub-element you are adding will create a new user in the MemoryRealm
database with a name of bob, a password of password, and a role of onjavauser.
 You should notice that the value of the roles attribute matches the value of the <role-
name> sub-element of the previously-defined <security-contstraint>.

6) To complete this configuration, stop and restart the Tomcat server.


Now let's actually look at how your newly defined realm affects the /onjava web application.
Point your browser at the following URL:
http://localhost:8080/onjava/login.jsp

If everything went according to plan you should see a dialog box similar to the one in Figure
1.

239
Figure 1. The BASIC Authentication Dialog

5.3.3 WebLogic

WebLogic server is based on Java 2 Platform, Enterprise Edition (J2EE), the standard
platform used to create Java-based multi-tier enterprise applications. J2EE platform
technologies were developed through the efforts of BEA Systems and other vendors in
collaboration with the main developer, Sun Microsystems. Because J2EE applications are
standardized modules, WebLogic can automate many system-level tasks that would
otherwise have demanded programming time. he main features of WebLogic server include
connectors that make it possible for any legacy application on any client to interoperate with
server applications, Enterprise JavaBean (EJB) components, resource pooling, and
connection sharing that make applications very scalable. An administration console with a
user interface makes management tasks more efficient and features such as Secure Sockets
Layer (SSL) support for the encryption of data transmissions, as well as authentication and
authorization mechanisms, make applications and transactions secure.

THE WEBLOGIC SERVER SOLUTION

Today's business environment demands Web and e-commerce applications that


accelerate your entry into new markets, help you find new ways to reach and retain
customers, and allow you to introduce new products and services quickly. To build and
deploy these new solutions, you need a proven, reliable e-commerce platform that can
connect and empower all types of users while integrating your corporate data, mainframe
applications, and other enterprise applications in a powerful, flexible, end-to-end e-
commerce solution. Your solution must provide the performance, scalability, and high
availability needed to handle your most critical enterprise-scale computing.

As the industry-leading e-commerce transaction platform, WebLogic Server allows


you to quickly develop and deploy reliable, secure, scalable and manageable applications. It
manages system-level details so you can concentrate on business logic and presentation.

240
J2EE PLATFORM

WebLogic Server contains Java 2 Platform, Enterprise Edition (J2EE) technologies.


J2EE is the standard platform for developing multitier enterprise applications based on the
Java programming language. The technologies that make up J2EE were developed
collaboratively by Sun Microsystems and other software vendors, including BEA Systems.

J2EE applications are based on standardized, modular components. WebLogic Server


provides a complete set of services for those components and handles many details of
application behavior automatically, without requiring programming.

WEBLOGIC SERVER 6.1 WITH J2EE 1.2 AND J2EE 1.3


FUNCTIONALITY

BEA WebLogic Server 6.1 is the first e-commerce transaction platform to implement
advanced J2EE 1.3 features. To comply with the rules governing J2EE, BEA Systems
provides two separate downloads: one with J2EE 1.3 features enabled, and one that is limited
to J2EE 1.2 features only. Both downloads offer the same container and differ only in the
APIs that are available.

WEBLOGIC SERVER 6.1 WITH J2EE 1.2 PLUS ADDITIONAL J2EE 1.3
FEATURES

With this download, WebLogic Server defaults to running with J2EE 1.3 features
enabled. These features include EJB 2.0, JSP 1.2, Servlet 2.3, and J2EE Connector
Architecture 1.0. When you run WebLogic Server 6.1 with J2EE 1.3 features enabled, J2EE
1.2 applications are still fully supported. The J2EE 1.3 feature implementations use non-final
versions of the appropriate API specifications. Therefore, application code developed for
BEA WebLogic Server 6.1 that uses the new features of J2EE 1.3 may be incompatible with
the J2EE 1.3 platform supported in future releases of BEA WebLogic Server.

WEBLOGIC SERVER 6.1 WITH J2EE 1.2 CERTIFICATION

With this download, WebLogic Server defaults to running with J2EE 1.3 features
disabled and is fully compliant with the J2EE 1.2 specification and regulations.

PRODUCT CD INSTALLERS FOR J2EE 1.2 AND 1.3

241
In addition to being available at http://commerce.bea.com/downloads/products.jsp,
both distributions are provided on the WebLogic Server 6.1 product CD. (On Windows
machines, the installer for WebLogic Server with J2EE 1.3 features enabled starts
automatically when you insert the CD.)

XML IMPLEMENTATION

WebLogic Server consolidates Extensible Markup Language (XML) technologies


applicable to WebLogic Server and XML applications based on WebLogic Server. A
simplified version of the Standard Generalized Markup Language (SGML) markup language,
XML describes the content and structure of data in a document and is an industry standard
for delivering content on the Internet. Typically, XML is used as the data exchange format
between J2EE applications and client applications, or between components of a J2EE
application. The WebLogic Server XML subsystem supports the use of standard parsers, the
WebLogic FastParser, XSLT transformers, and DTDs and XML schemas to process and
convert XML files.

APPLICATION DEPLOYMENT ACROSS DISTRIBUTED,


HETEROGENEOUS ENVIRONMENTS

WebLogic Server provides essential features for developing and deploying mission-
critical e-commerce applications across distributed, heterogeneous computing environments.
These features include the following:

 Standards leadership—Comprehensive Enterprise Java support to ease


implementation and deployment of application components. WebLogic Server is
the first independently developed Java application server to achieve J2EE
certification.

 Rich client options—WebLogic Server supports Web browsers and other clients
that use HTTP; Java clients that use RMI (Remote Method Invocation) or IIOP
(Internet Inter-ORB Protocol); and mobile devices that use (WAP) Wireless
Access Protocol. Connectors from BEA and other companies enable virtually any
client or legacy application to work with a WebLogic Server application.

 Flexible Web services—WebLogic Server provides a solid platform for deploying


Web services as components of a heterogeneous distributed application. Web
services use a cross-platform, cross-language data model (XML) to provide
interoperability among application components on diverse hardware and software
platforms.

242
WebLogic Server 6.1 uses Web Services Description Language (WSDL) 1.1, an
XML-based specification, to describe Web services. WebLogic Web Services use
Simple Object Access Protocol (SOAP) 1.1 as the message format and HTTP as a
connection protocol.

 Enterprise e-business scalability—Efficient use and high availability of critical


resources are achieved through Enterprise JavaBean business components and
mechanisms such as WebLogic Server clustering for dynamic Web pages, backend
resource pooling, and connection sharing.

 Robust administration—WebLogic Server offers a Web-based Administration


Console for configuring and monitoring WebLogic Server services. A command-
line interface for configuration makes it convenient to administer WebLogic
Servers ith scripts.

 E-commerce-ready security—WebLogic Server provides Secure Sockets Layer


(SSL) support for encrypting data transmitted across WebLogic Server, clients,
and other servers. WebLogic security realms feature user authentication and
authorization for all WebLogic Server services. External security stores, such as
Lightweight Directory Access Protocol (LDAP) servers, can be adapted to
WebLogic realms, enabling single sign-on for the enterprise. The Security Service
Provider Interface makes it possible to extend WebLogic Security services and to
implement ebLogic Security features in applications.

 Maximum development and deployment flexibility—WebLogic Server provides


tight integration with and support for leading databases, development tools, and
other environments.

WHAT IS WEBLOGIC EXPRESS?

BEA WebLogic ExpressTM is a scalable platform that serves dynamic content and data
to Web and wireless applications. WebLogic Express incorporates the presentation and
database access services from WebLogic Server, enabling developers to create interactive and
transactional e-business applications quickly and to provide presentation services for existing
applications.

WebLogic Express offers many services and APIs available with WebLogic Server,
including WebLogic JDBC features, JavaServer Pages (JSP), servlets, Remote Method
Invocation (RMI), and Web server functionality.

243
WebLogic Express differs from WebLogic Server in that WebLogic Express does not provide
Enterprise JavaBeans (EJB), Java Message Services (JMS), or the two-phase commit
protocol for transactions.

WEBLOGIC SERVER APPLICATION ARCHITECTURE

WebLogic Server is an application server: a platform for developing and deploying


multitier distributed enterprise applications. WebLogic Server centralizes application services
such as Web server functionality, business components, and access to backend enterprise
systems. It uses technologies such as caching and connection pooling to improve resource
use and application performance. WebLogic Server also provides enterprise-level security
and powerful administration facilities.

WebLogic Server operates in the middle tier of a multitier (or n-tier) architecture. A
multitier architecture determines where the software components that make up a computing
system are executed in relation to each other and to the hardware, network, and users.
Choosing the best location for each software component lets you develop applications faster;
eases deployment and administration; and provides greater control over performance,
utilization, security, scalability, and reliability.

WebLogic Server implements J2EE, the Java Enterprise standard. Java is a network-
savvy, object-oriented programming language, and J2EE includes component technologies
for developing distributed objects. This functionality adds a second dimension to the
WebLogic Server application architecture—a layering of application logic, with each layer
selectively deployed among WebLogic Server J2EE technologies.

The next two sections describe these two views of WebLogic Server architecture:
software tiers and application logic layers.

SOFTWARE COMPONENT TIERS

The software components of a multitier architecture consist of three tiers:

 The client tier contains programs executed by users, including Web browsers and
network-capable application programs. These programs can be written in virtually
any programming language.
 The middle tier contains WebLogic Server and other servers that are addressed
directly by clients, such as existing Web servers or proxy servers.
 The backend tier contains enterprise resources, such as database systems, mainframe
and legacy applications, and packaged enterprise resource planning (ERP)
applications.

244
Client applications access WebLogic Server directly, or through another Web server or proxy
server. WebLogic Server generally connects with backend services on behalf of clients.
However, clients may directly access backend services using a multitier JDBC driver.

THREE-TIER ARCHITECTURE

CLIENT-TIER COMPONENTS

WebLogic Server clients use standard interfaces to access WebLogic Server services.
WebLogic Server has complete Web server functionality, so a Web browser can request pages
from WebLogic Server using the Web's standard HTTP protocol. WebLogic Server servlets

245
and JavaServer Pages (JSPs) produce the dynamic, personalized Web pages required for
advanced e-commerce Web applications.

Client programs written in Java may include highly interactive graphical user
interfaces built with Java Swing classes. They can also access WebLogic Server services
using standard J2EE APIs.

All these services are also available to Web browser clients by deploying servlets and
JSP pages in WebLogic Server.

CORBA-enabled client programs written in Visual Basic, C++, Java, and other
programming languages can execute WebLogic Server Enterprise JavaBeans and RMI
(Remote Method Invocation) classes using WebLogic RMI-IIOP. Client applications written
in any language with support for the HTTP protocol can access any WebLogic Server service
through a servlet.

MIDDLE-TIER COMPONENTS

The middle tier includes WebLogic Server and other Web servers, firewalls, and
proxy servers that mediate traffic between clients and WebLogic Server. The Nokia WAP
server, part of the BEA mobile commerce solution, is an example of another middle tier
server that provides connectivity between wireless devices and WebLogic Server.

Applications based on a multitier architecture require reliability, scalability, and high


performance in the middle tier. The application server you select for the middle tier is,
therefore, critical to the success of your system.

The WebLogic Server cluster option allows you to distribute client requests and back-
end services among multiple cooperating WebLogic Servers. Programs in the client tier
access the cluster as if it were a single WebLogic Server. As the workload increases, you can
add WebLogic Servers to the cluster to share the work. The cluster uses a selectable load-
balancing algorithm to choose a WebLogic Server in the cluster that is capable of handling
the request.

When a request fails, another WebLogic Server that provides the requested service
can take over. Failover is transparent whenever possible, which minimizes the amount of
code that must be written to recover from failures. For example, servlet session state can be
replicated on a secondary WebLogic Server so that if the WebLogic Server that is handling a
request fails, the client's session can resume uninterrupted on the secondary server. WebLogic
EJB, JMS, JDBC, and RMI services are all implemented with clustering capabilities.

BACKEND-TIER COMPONENTS

246
The backend tier contains services that are accessible to clients only through
WebLogic Server. Applications in the backend tier tend to be the most valuable and mission-
critical enterprise resources. WebLogic Server protects them by restricting direct access by
end users. With technologies such as connection pools and caching, WebLogic Server uses
back-end resources efficiently and improves application response.

Backend services include databases, enterprise resource planning (ERP) systems,


mainframe applications, legacy enterprise applications, and transaction monitors. Existing
enterprise applications can be integrated into the backend tier using the Java Connector
Architecture (JCA) specification from Sun Microsystems. WebLogic Server makes it easy to
add a Web interface to an integrated backend application.

A database management system is the most common backend service, required by


nearly all WebLogic Server applications. WebLogic EJB and WebLogic JMS typically store
persistent data in a database in the backend tier.

A JDBC connection pool, defined in WebLogic Server, opens a predefined number of


database connections. Once opened, database connections are shared by all WebLogic Server
applications that need database access. The expensive overhead associated with establishing
a connection is incurred only once for each connection in the pool, instead of once per client
request. WebLogic Server monitors database connections, refreshing them as needed and
ensuring reliable database services for applications.

WebLogic Enterprise Connectivity, which provides access to BEA WebLogic


EnterpriseTM systems, and Jolt® for WebLogic Server, which provides access to BEA
Tuxedo® systems, also use connection pools to enhance system performance.

APPLICATION LOGIC LAYERS

WebLogic Server implements J2EE component technologies and services. J2EE


component technologies include servlets, JSP Pages, and Enterprise JavaBeans. J2EE
services include access to standard network protocols, database systems, and messaging
systems. To build a WebLogic Server application, you must create and assemble components,
using the service APIs when necessary.

Components are executed in the WebLogic Server Web container or EJB container.
Containers provide the life cycle support and services defined by the J2EE specifications so
that the components you build do not have to handle underlying details.

Web components provide the presentation logic for browser-based J2EE applications.
EJB components encapsulate business objects and processes. Web applications and EJBs are

247
built on J2EE application services, such as JDBC, JMS (Java Messaging Service), and JTA
(Java Transaction API).

Illustrates WebLogic Server component containers and application services.

Application Logic Layers

The following sections discuss the presentation layer, business logic, and application
services.

PRESENTATION LOGIC LAYER

The presentation layer includes an application's user interface and display logic. Most
J2EE applications use a Web browser on the client machine because it is much easier than
deploying client programs to every user's computer. In this case, the presentation logic is the

248
WebLogic Server Web container. Client programs written in any programming language,
however, must contain either logic to render HTML or their own presentation logic. A client
that accesses a Web service must assemble a SOAP message that describes the Web service it
wants to invoke, and include the necessary data in the body of the SOAP message.

WEB BROWSER CLIENTS

Web-based applications built with standard Web technologies are easy to access,
maintain, and port. Web browser clients are standard for e-commerce applications.

In Web-based applications, the user interface is represented by HTML documents,


JavaServer Pages (JSP), and servlets. The Web browser contains the logic to render the Web
page on the user's computer from the HTML description.

JavaServer Pages (JSP) and servlets are closely related. Both produce dynamic Web
content by executing Java code on WebLogic Server each time they are invoked. The
difference between them is that JSP is written with an extended version of HTML, and
servlets are written with the Java programming language.

JSP is convenient for Web designers who know HTML and are accustomed to
working with an HTML editor or designer. Servlets, written entirely in Java, are more suited
to Java programmers than to Web designers. Writing a servlet requires some knowledge of
the HTTP protocol and Java programming. A servlet receives the HTTP request in a request
object and typically writes HTML or XML in its response object.

JSP pages are converted to servlets before they are executed on WebLogic Server, so
ultimately JSP pages and servlets are different representations of the same thing. JSP pages
are deployed on WebLogic Server the same way an HTML page is deployed.

The .jsp file is copied into a directory served by WebLogic Server. When a client
requests a .jsp file, WebLogic Server checks whether the page has been compiled or has
changed since it was last compiled. If needed, it calls the WebLogic JSP compiler, which
generates Java servlet code from the .jsp file, and then it compiles the Java code to a Java
class file.

NON-BROWSER CLIENTS

249
A client program that is not a Web browser must supply its own code for rendering
the user interface. Non-browser clients usually contain their own presentation and rendering
logic, depending on WebLogic Server only for business logic and access to back-end
services. This makes them more difficult to develop and deploy and less suited for Internet-
based e-commerce applications than browser-based clients.

Client programs written in Java can use any WebLogic Server service over Java RMI
(Remote Method Invocation). RMI allows a client program to operate on a WebLogic Server
object the same way it would operate on a local object in the client. Because RMI hides the
details of making calls over a network, J2EE client code and server-side code are very
similar.

Java programs can use the Java Swing classes to create powerful and portable user
interfaces. Although by using Java you can avoid portability issues, you cannot use
WebLogic Server services over RMI unless the WebLogic Server classes are installed on the
client. This means that Java RMI clients are not suited to e-commerce applications. They can
be used effectively, however, in enterprise applications in which an internal network makes
installation and maintenance viable. Client programs written in languages other than Java and
Java client programs that do not use WebLogic Server objects over RMI can access
WebLogic Server using HTTP or RMI-IIOP.

HTTP is the standard protocol for the Web. It allows a client to make different types
of requests to a server and to pass parameters to the server. A servlet on WebLogic Server can
examine client requests, retrieve parameters from the request, and prepare a response for the
client, using any WebLogic Server service. For example, a servlet might respond to a client
program with an XML business document. Thus an application can use servlets as gateways
to other WebLogic Server services.

WebLogic RMI-IIOP allows CORBA-enabled programs to execute WebLogic Server


enterprise beans and RMI classes as CORBA objects. The WebLogic Server RMI and EJB
compilers can generate IDL (Interface Definition Language) for RMI classes and enterprise
beans. IDL generated this way is compiled to create skeletons for an ORB (Object Request
Broker) and stubs for the client program. WebLogic Server parses incoming IIOP requests
and dispatches them to the RMI run-time system.

WEB SERVICE CLIENTS

Client applications that invoke WebLogic Web Services can be written using any
technology: Java, Microsoft SOAP Toolkit, and so on. The client application assembles a
SOAP message that describes the Web service it wants to invoke and includes all the
necessary data in the body of the SOAP message. The client then sends the SOAP message
over HTTP/HTTPS to WebLogic Server, which executes the Web service and sends a SOAP
message back to the client over HTTP/HTTPS.

250
WebLogic Server provides a Web Services run-time component, which is a set of
servlets and associated infrastructure needed to create a Web service. One element of the run-
time is a set of servlets that handle SOAP requests from a client. You do not need to write
these servlets; they are automatically included in the WebLogic Server distribution.

For Java-based Web Services clients, WebLogic Server also provides an optional Java
client JAR file. The JAR file includes everything a client application needs to invoke a
WebLogic Web Service, such as the WebLogic Web Services Client API and WebLogic
FastParser. Unlike other Java WebLogic Server clients, you do not need to include the
weblogic.jar file with Web Services clients, thus making for very thin client
applications.

BUSINESS LOGIC LAYER

Enterprise JavaBeans are the business logic components for J2EE applications. The
WebLogic Server EJB container hosts enterprise beans, providing life cycle management and
services such as caching, persistence, and transaction management.

There are three types of enterprise beans: entity beans, session beans, and message-
driven beans. The following sections describe each type in detail.

ENTITY BEANS

An entity bean represents an object that contains data, such as a customer, an account,
or an inventory item. Entity beans contain data values and methods that can be invoked on
those values. The values are saved in a database (using JDBC) or some other data store.
Entity beans can participate in transactions involving other enterprise beans and transactional
services.

Entity beans are often mapped to objects in databases. An entity bean can represent a
row in a table, a single column in a row, or an entire table or query result. Associated with
each entity bean is a unique primary key used to find, retrieve, and save the bean.

An entity bean can employ one of the following:

 Bean-managed persistence—the bean contains code to retrieve and save


persistent values.
 Container-managed persistence—the EJB container loads and saves values on
behalf of the bean.

When container-managed persistence is used, the WebLogic EJB compiler can


generate JDBC support classes to map an entity bean to a row in a database. Other container-

251
managed persistence mechanisms are available. For example, TopLink for WebLogic
Foundation Library, from WebGain, provides persistence for an object relational database.

Entity beans can be shared by many clients and applications. An instance of an entity
bean can be created at the request of any client, but it does not disappear when that client
disconnects. It continues to live as long as any client is actively using it. When the bean is no
longer in use, the EJB container may passivate it: that is, it may remove the live instance
from the server.

SESSION BEANS

A session bean is a transient EJB instance that serves a single client. Session beans
tend to implement procedural logic; they embody actions more than data.

The EJB container creates a session bean at a client's request. It then maintains the
bean as long as the client maintains its connection to the bean. Sessions beans are not
persistent, although they can save data to a persistent store if needed.

A session bean can be stateless or stateful. Stateless session beans maintain no client-
specific state between calls and can be used by any client. They can be used to provide access
to services that do not depend on the context of a session, such as sending a document to a
printer or retrieving read-only data into an application.

A stateful session bean maintains state on behalf of a specific client. Stateful session
beans can be used to manage a process, such as assembling an order or routing a document
through a workflow process. Because they can accumulate and maintain state through
multiple interactions with a client, session beans are often the controlling objects in an
application. Because they are not persistent, session beans must complete their work in a
single session and use JDBC, JMS, or entity beans to record the work permanently.

MESSAGE-DRIVEN BEANS

Message-driven beans, introduced in the EJB 2.0 specification, are enterprise beans
that handle asynchronous messages received from JMS Message Queues. JMS routes
messages to a message-driven bean, which selects an instance from a pool to process the
message.

Message-driven beans are managed in the WebLogic Server EJB container. Because
they are not called directly by user-driven applications, they cannot be accessed from an
application using an EJB home. An user-driven application can, however, instantiate a
message-driven bean indirectly by sending a message to the bean's JMS Queue.

252
APPLICATION SERVICES LAYER

WebLogic Server supplies the fundamental services that allow components to


concentrate on business logic without concern for low-level implementation details. It
handles networking, authentication, authorization, persistence, and remote object access for
EJBs and servlets. Standard Java APIs provide portable access to other services that an
application can use, such as database and messaging services.

NETWORK COMMUNICATIONS TECHNOLOGIES

Client applications connect with WebLogic Server using standard networking


protocols over TCP/IP. WebLogic Server listens for connection requests at a network address
that can be specified as part of a Uniform Resource Identifier (URI).

A URI is a standardized string that specifies a resource on a network, including the


Internet. It contains a protocol specifier called a scheme, the network address of the server,
the name of the desired resource, and optional parameters. The URL you enter in a Web
browser, for example, http://www.bea.com/index.html, is the most familiar URI
format.

Web-based clients communicate with WebLogic Server using the HTTP protocol.
Java clients connect using Java RMI (Remote Method Invocation), which allows a Java client
to execute objects in WebLogic Server. CORBA-enabled clients access WebLogic Server
RMI objects using RMI-IIOP, which allows them to execute WebLogic Server objects using
standard CORBA protocols.

In the following table, the scheme in a URI determines the protocol for network exchanges
between a client and WebLogic Server.

TABLE 1-1 NETWORK PROTOCOLS

Scheme Protocol
HTTP HyperText Transfer Protocol. Used by Web browsers and HTTP-capable
programs.
HTTPS Hypertext Transfer Protocol over Secure Sockets Layer (SSL). Used by Web
browsers and HTTPS-capable client programs.
T3 WebLogic T3 protocol for Java-to-Java connections, which multiplexes JNDI,
RMI, EJB, JDBC, and other WebLogic services over a network connection.
T3S WebLogic T3 protocol over Secure Sockets Layer (SSL).
RMI Remote Method Invocation (RMI), the standard Java facility for distributed

253
applications.
IIOP Internet Inter-ORB protocol, used by CORBA-enabled Java clients to execute
WebLogic RMI objects over IIOP. Other CORBA clients connect to WebLogic
Server with a CORBA naming context instead of a URI for WebLogic Server.
IIOPS Internet Inter-ORB protocol over Secure Sockets Layer (SSL).
SOAP WebLogic Web Services use Simple Object Access Protocol (SOAP) 1.1 as the
message format and HTTP as a connection protocol.

The following sections provide more information about these protocols.

HTTP

HTTP, the standard protocol of the World Wide Web, is a request-response protocol.
A client issues a request that includes a URI. The URI begins with http:// and the
WebLogic Server address, and the name of a resource on WebLogic Server, such as an
HTML page, servlet, or JSP page. If the resource name is omitted, WebLogic Server returns
the default Web page, usually index.html. The header of an HTTP request includes a
command, usually GET or POST. The request can include data parameters and message
content.

WebLogic Server always responds to an HTTP request by executing a servlet, which


returns results to the client. An HTTP servlet is a Java class that can access the contents of an
HTTP request received over the network and return an HTTP-compliant result to the client.

WebLogic Server directs a request for an HTML page to the built-in File servlet.
The File servlet looks for the HTML file in the document directory of the WebLogic Server
file system. A request for a custom-coded servlet executes the corresponding Java class on
WebLogic Server. A request for a JSP page causes WebLogic Server to compile the JSP page
into a servlet, if it has not already been compiled, and then to execute the servlet, which
returns results to the client.

T3

T3 is an optimized protocol used to transport data between WebLogic Server and


other Java programs, including clients and other WebLogic Servers. WebLogic Server keeps
track of every Java Virtual Machine (JVM) with which it connects, and creates a single T3
connection to carry all traffic for a JVM.

For example, if a Java client accesses an enterprise bean and a JDBC connection pool
on WebLogic Server, a single network connection is established between the WebLogic
Server JVM and the client JVM. The EJB and JDBC services can be written as if they had

254
sole use of a dedicated network connection because the T3 protocol invisibly multiplexes
packets on the single connection.

T3 is an efficient protocol for Java-to-Java applications because it avoids unnecessary


network connection events and uses fewer OS resources. The protocol also has internal
enhancements that minimize packet sizes

RMI

Remote Method Invocation (RMI) is the standard Java facility for distributed
applications. RMI allows one Java program, called the server, to publish Java objects that
another Java program, called a client, can execute. In most applications, WebLogic Server is
the RMI server and a Java client application is the client. But the roles can be reversed; RMI
allows any Java program to play the role of server.

RMI architecture is similar to the CORBA architecture. To create a remote object, a


programmer writes an interface for a Java class that defines the methods that may be
executed by a remote client. The WebLogic Server RMI compiler, rmic, processes the
interface, producing RMI stub and skeleton classes. The remote class, stubs, and skeletons
are installed in WebLogic Server.

A Java client looks up a remote object in WebLogic Server using the Java Naming
and Directory Interface (JNDI), which is described later in this section. JNDI establishes a
connection to WebLogic Server, looks up the remote class, and returns the stubs to the client.

The client executes a stub method as if it were executing the method directly on the
remote class. The stub method prepares the call and transmits it over the network to the
skeleton class in WebLogic Server.

On WebLogic Server, the skeleton class unpacks the request and executes the method
on the server-side object. Then it packages the results and returns them to the stub on the
client side.

WebLogic EJB and several other services available to Java clients are built on RMI.
Most applications should use EJB instead of using RMI directly, because EJB provides a
better abstraction for business objects. In addition, the WebLogic Server EJB container
provides enhancements such as caching, persistence, and life cycle management that are not
automatically available to remote classes.

255
RMI-IIOP

Remote Method Invocation over Internet Inter-ORB Protocol (RMI-IIOP) is a


protocol that allows CORBA client programs to execute WebLogic RMI objects, including
enterprise beans. RMI-IIOP is based on two specifications from the Object Management
Group (http://www.omg.com):

 Java-to-IDL mapping
 Objects-by-value

The Java-to-IDL specification defines how an Interface Definition Language (IDL) is


derived from a Java interface. The WebLogic Server compilers for RMI and EJB give you the
option of producing IDL when compiling RMI and EJB objects. This IDL can be compiled
with an IDL APIs compiler to produce the stubs required by a CORBA client.

The objects-by-value specification defines how complex data types are mapped
between Java and CORBA. To use objects-by-value, a CORBA client must use an Object
Request Broker (ORB) with CORBA 2.3 support. Without a CORBA 2.3 ORB, CORBA
clients can use only Java primitive data types.

SSL

Data exchanged with the HTTP and T3 protocols can be encrypted with the Secure
Sockets Layer (SSL) protocol. Using SSL assures the client that it has connected with an
authenticated server and that data transmitted over the network is private.

SSL uses public key encryption. Public key encryption requires you to purchase a
Server ID, which is a certificate for your WebLogic Server from a Certificate Authority such
as VeriSign. When a client connects to the WebLogic Server SSL port, the server and client
execute a protocol that includes authenticating the server's Server ID and negotiating
encryption algorithms and parameters for the session. WebLogic Server can also be
configured to require the client to present a certificate, an arrangement that is called mutual
authentication.

SOAP

SOAP (Simple Object Access Protocol) is a lightweight, XML-based protocol used to


exchange information in a decentralized, distributed environment. The protocol consists of an
envelop that describes the SOAP message, encoding rules, and conventions for representing
remote procedure calls and responses.

256
All information is embedded in a Multipurpose Internet Mail Extensions (MIME)-
encoded package that can be transmitted over HTTP or other Web protocols. MIME is a
specification for formatting non-ASCII messages so that they can be sent over the Internet.

DATA AND ACCESS SERVICES

WebLogic Server implements standard J2EE technologies to provide data and access services
to applications and components. These services include the following APIs:

 Java Naming and Directory Interface (JNDI)


 Java Database Connectivity (JDBC)
 Java Transaction API (JTA)
 J2EE Connector Architecture

The following sections discuss these services in detail.

JNDI

The Java Naming and Directory Interface (JNDI) is a standard Java API that enables
applications to look up an object by name. WebLogic Server or a user application binds the
Java objects it serves to a name in a naming tree. An application can look up objects, such as
RMI objects, Enterprise JavaBeans, JMS Queues and Topics, and JDBC DataSources, by
getting a JNDI context from WebLogic Server and then calling the JNDI lookup method with
the name of the object. The lookup returns a reference to the WebLogic Server object.

WebLogic JNDI supports WebLogic Server cluster load balancing and failover. Each
WebLogic Server in a cluster publishes the objects it serves in a replicated cluster-wide
naming tree. An application can get an initial JNDI context from any WebLogic Server in the
cluster, perform a lookup, and receive an object reference from any WebLogic Server in the
cluster that serves the object. A configurable load-balancing algorithm is used to spread the
workload among the servers in the cluster.

JDBC

Java Database Connectivity (JDBC) provides access to backend database resources.


Java applications access JDBC using a JDBC driver, which is a database vendor-specific
interface for a database server. Although any Java application can load a vendor's JDBC
driver, connect to the database, and perform database operations, WebLogic Server provides
a significant performance advantage by offering JDBC connection pools.

257
A JDBC connection pool is a named group of JDBC connections managed through
WebLogic Server. At startup time WebLogic Server opens JDBC connections and adds them
to the pool. When an application requires a JDBC connection, it gets a connection from the
pool, uses it, and then returns it to the pool for use by for other applications. Establishing a
database connection is often a time-consuming, resource-intensive operation, so a connection
pool, which limits the number of connection operations, improves performance.

WebLogic Server also provides JDBC multipools for achieving load balancing or
high availability capabilities with database connections in single-server configurations.
Multipools are a "pool of pools" that provide a configurable algorithm for choosing which
pool to provide a connection for a given request. Currently, WebLogic Server provides
algorithms to support either high availability or load balancing behavior for database
connections.

To register a connection pool in the JNDI naming tree, define a DataSource object for
it. Java client applications can then get a connection from the pool by performing a JNDI
lookup on the DataSource name.

Server-side Java classes use the WebLogic JDBC pool driver, which is a generic
JDBC driver that calls through to the vendor-specific JDBC driver. This mechanism makes
application code more portable, even if you change the brand of database used in the backend
tier.

The client-side JDBC driver is the WebLogic JDBC/RMI driver, which is an RMI
interface to the pool driver. Use this driver the same way you use any standard JDBC driver.
When the JDBC/RMI driver is used, Java programs can access JDBC in a manner consistent
with other WebLogic Server distributed objects, and they can keep database data structures in
the middle tier.

WebLogic EJB and WebLogic JMS rely on connections from a JDBC connection
pool to load and save persistent objects. By using EJB and JMS, you can often get a more
useful abstraction than you can get by using JDBC directly in an application. For example,
using an enterprise bean to represent a dataful object allows you to change the underlying
store later without modifying JDBC code. If you use persistent JMS messages instead of
coding database operations with JDBC, it will be easier to adapt your application to a third-
party messaging system later.

JTA

The Java Transaction API (JTA) is the standard interface for managing transactions in
Java applications. By using transactions, you can protect the integrity of the data in your
databases and manage access to that data by concurrent applications or application instances.

258
Once a transaction begins, all transactional operations must commit successfully or all of
them must be rolled back.

WebLogic Server supports transactions that include EJB, JMS, JCA, and JDBC
operations. Distributed transactions, coordinated with two-phase commit, can span multiple
databases that are accessed with XA-compliant JDBC drivers, such as BEA WebLogic
jDriver for Oracle/XA.

The EJB specification defines bean-managed and container-managed


transactions.When an enterprise bean is deployed with container-managed transactions,
WebLogic Server coordinates the transaction automatically. If an enterprise bean is deployed
with bean-managed transactions, the EJB programmer must provide transaction code.

Application code based on the JMS or JDBC API can initiate a transaction, or
participate in a transaction started earlier. A single transaction context is associated with the
WebLogic Server thread executing an application; all transactional operations performed on
the thread participate in the current transaction.

J2EE CONNECTOR ARCHITECTURE

The J2EE Connector Architecture adds simplified Enterprise Information System


(EIS) integration to the J2EE platform. It provides a Java solution to the problem of
connectivity between the multitude of application servers and EISes. By using the Connector
Architecture, it is no longer necessary for EIS vendors to customize their product for each
application server. By conforming to the J2EE Connector Architecture, BEA WebLogic
Server does not require added custom code in order to extend its support connectivity to a
new EIS.

The J2EE Connector Architecture is implemented both in WebLogic Server and in an


EIS-specific resource adapter. A resource adapter is a system library specific to an EIS and
provides connectivity to the EIS. A resource adapter is analogous to a JDBC driver. The
interface between a resource adapter and the EIS is specific to the underlying EIS, and can be
a native interface.

The J2EE Connector Architecture comprises the system-level contracts between


WebLogic Server and a given resource adaptor, a common interface for clients to access the
adaptor, and interfaces for packaging and deploying resource adaptors to J2EE applications.
See Programming the J2EE Connector Architecture for more information.

259
MESSAGING TECHNOLOGIES

The J2EE messaging technologies provide standard APIs that WebLogic Server
applications can use to communicate with one another as well as with non-WebLogic Server
applications. The messaging services include the following APIs:

• Java Message Service (JMS)


• JavaMail

The following sections describe these APIs in detail.

JMS

Java Messaging Service (JMS) enables applications to communicate with one another
by exchanging messages. A message is a request, report, and/or event that contains the
information needed to coordinate communication between different applications. A message
provides a level of abstraction, allowing you to separate details about the destination system
from the application code.

WebLogic JMS implements two messaging models: point-to-point (PTP) and


publish/subscribe (pub/sub). The PTP model allows any number of senders to send messages
to a Queue. Each message in the Queue is delivered to a single reader. The pub/sub model
allows any number of senders to send messages to a Topic. Each message on the Topic is sent
to every reader with a subscription to the Topic. Messages can be delivered to readers
synchronously or asynchronously; the particular messaging mode can be controlled either
using the Administration Console or via the method used to send messages in the JMS
application.

JMS messages can be persistent or non-persistent. Persistent messages are stored in a


database and are not lost if WebLogic Server restarts. Non-persistent messages are lost if
WebLogic Server is restarted. Persistent messages sent to a Topic can be retained until all
interested subscribers have received them.

JMS supports several message types that are useful for different types of applications.
The message body can contain arbitrary text, byte streams, Java primitive data types,
name/value pairs, serializable Java objects, or XML content.

JAVA MAIL

WebLogic Server includes the Sun JavaMail reference implementation. JavaMail


allows an application to create e-mail messages and send them through an SMTP server on
the network.

260
5.4 HTTP REQUESTS

An HTTP request consists of three components:

 Method-URI-Protocol/Version

 Request headers

 Entity body

AN EXAMPLE HTTP REQUEST IS:

POST /servlet/default.jsp HTTP/1.1


Accept: text/plain; text/html
Accept-Language: en-gb
Connection: Keep-Alive
Host: localhost
Referer: http://localhost/ch8/SendDetails.htm
User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)
Content-Length: 33
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate

LastName=Franks&FirstName=Michael

HTTP RESPONSES

Similar to requests, an HTTP response also consists of three parts:


• Protocol-Status code-Description
• Response headers
• Entity body

THE SOCKET CLASS

A socket is an endpoint of a network connection. A socket enables an application to


read from and write to the network. Two software applications residing on two different
computers can communicate with each other by sending and receiving byte streams over a
connection. To send a message to another application, you need to know its IP address, as

261
well as the port number of its socket. In Java, a socket is represented by the java.net.Socket
class.

To create a socket, you can use one of the many constructors of the Socket class. One
of these constructors accepts the host name and the port number:

public Socket(String host, int port) where host is the remote machine name or IP
address, and port is the port number of the remote application. For example, to connect to
yahoo.com at port 80, you would construct the following socket:
new Socket("yahoo.com", 80);

Once you create an instance of the Socket class successfully, you can use it to send
and receive streams of bytes. To send byte streams, you must first call the Socket class'
getOutputStream method to obtain a java.io.OutputStream object.

To send text to a remote application, you often want to construct a java.io.PrintWriter


object from the OutputStream object returned. To receive byte streams from the other end of
the connection, you call the Socket class' getInputStream method, which returns a
java.io.InputStream.

THE SERVERSOCKET CLASS

The Socket class represents a "client" socket; a socket that you construct whenever
you want to connect to a remote server application. If you want to implement a server
application, such as an HTTP server or an FTP server, you need a different approach. This is
because your server must stand by all the time, as it does not know when a client application
will try to connect to it.

For this purpose, you need to use the java.net.ServerSocket class. This is an
implementation of a server socket. A server socket waits for a connection request from a
client. Once it receives a connection request, it creates a Socket instance to handle the
communication with the client.

To create a server socket, you need to use one of the four constructors the
ServerSocket class provides. You need to specify the IP address and port number on which
the server socket will listen.

Typically, the IP address will be 127.0.0.1, meaning that the server socket will be
listening on the local machine. The IP address the server socket is listening on is referred to
as the binding address. Another important property of a server socket is its backlog, which is
the maximum queue length for incoming connection requests before the server socket starts
to refuse incoming requests.

One of the constructors of the ServerSocket class has the following signature:

262
PUBLIC SERVERSOCKET(INT PORT, INT BACKLOG, INETADDRESS
BINDINGADDRESS);

For this constructor, the binding address must be an instance of java.net.InetAddress.


An easy way to construct an InetAddress object is by calling its static method getByName,
passing a String containing the host name:
InetAddress.getByName("127.0.0.1");

The following line of code constructs a ServerSocket that listens on port 8080 of the local
machine with a backlog of 1.

new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));

JAVA SERVLET

The Java Servlet API allows a software developer to add dynamic content to a Web
server using the Java platform. The generated content is commonly HTML, but may be other
data such as XML. Servlets are the Java counterpart to non-Java dynamic Web content
technologies such as PHP, CGI and ASP.NET. Servlets can maintain state across many server
transactions by using HTTP cookies, session variables or URL rewriting.

The Servlet API, contained in the Java package hierarchy javax.servlet, defines the
expected interactions of a Web container and a servlet. A Web container is essentially the
component of a Web server that interacts with the servlets. The Web container is responsible
for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring
that the URL requester has the correct access rights.

A Servlet is an object that receives a request and generates a response based on that
request. The basic servlet package defines Java objects to represent servlet requests and
responses, as well as objects to reflect the servlet's configuration parameters and execution
environment.

The package javax.servlet.http defines HTTP-specific subclasses of the generic


servlet elements, including session management objects that track multiple requests and
responses between the Web server and a client. Servlets may be packaged in a WAR file as a
Web application.

Servlets can be generated automatically by JavaServer Pages (JSP), or alternately by


template engines such as WebMacro. Often servlets are used in conjunction with JSPs in a
pattern called "Model 2", which is a flavor of the model-view-controller pattern.

263
LIFE CYCLE OF A SERVLET

The Servlet life cycle consists of the following steps:

2. The Servlet class is loaded by the container during start-up.

3. The container calls the init() method. This method initializes the servlet and must be
called before the servlet can service any requests. In the entire life of a servlet, the
init() method is called only once.

4. After initialization, the servlet can service client-requests. Each request is serviced in
its own separate thread. The container calls the service() method of the servlet for
every request. The service() method determines the kind of request being made and
dispatches it to an appropriate method to handle the request.

5. The developer of the servlet must provide an implementation for these methods. If a
request for a method that is not implemented by the servlet is made, the method of the
parent class is called, typically resulting in an error being returned to the requester.

6. Finally, the container calls the destroy() method which takes the servlet out of service.
The destroy() method like init() is called only once in the life-cycle of a Servlet.

THE SERVICE METHOD

Each time the server receives a request for a servlet, the server spawns a new thread
and calls service. The service method checks the HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc., as appropriate.

A GET request results from a normal request for a URL or from an HTML form that
has no METHOD specified. A POST request results from an HTML form that specifically
lists POST as the METHOD. Other HTTP requests are generated only by custom clients.

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException

264
{
doGet(request, response);
}

THE INIT METHOD

Most of the time, your servlets deal only with per-request data, and doGet or doPost
are the only life-cycle methods you need. Occasionally, however, you want to perform
complex setup tasks when the servlet is first loaded, but not repeat those tasks for each
request. The init method is designed for this case; it is called when the servlet is first created,
and not called again for each user request. So, it is used for one-time initializations, just as
with the init method of applets. The init method definition looks like this:

public void init() throws ServletException {


// Initialization code...
}
The init method performs two varieties of initializations: general initializations
and initializations controlled by initialization parameters

THE DESTROY METHOD

The server may decide to remove a previously loaded servlet instance, perhaps 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 server to crash So, don’t count on
destroy as the only mechanism for saving state to disk. If your servlet performs activities like
counting hits or accumulating lists of cookie values that indicate special access, you should
also proactively write the data to disk periodically.

HYPERTEXT TRANSFER PROTOCOL

Hypertext Transfer Protocol (HTTP) is a communications protocol used to transfer


or convey information on the World Wide Web. Its original purpose was to provide a way to
publish and retrieve HTML hypertext pages. Development of HTTP was coordinated by the
W3C (World Wide Web Consortium) and the IETF (Internet Engineering Task Force),
culminating in the publication of a series of RFCs, most notably RFC 2616 (1999), which
defines HTTP/1.1, the version of HTTP in common use today.

265
HTTP is a request/response protocol between clients and servers. The client making
an HTTP request - such as a web browser, spider, or other end-user tool - is referred to as the
user agent. The responding server - which stores or creates resources such as HTML files and
images - is called the origin server. In between the user agent and origin server may be
several intermediaries, such as proxies, gateways, and tunnels. It is useful to remember that
HTTP does not need to use TCP/IP or its supporting layers. Indeed HTTP can be
"implemented on top of any other protocol on the Internet, or on other networks. HTTP only
presumes a reliable transport; any protocol that provides such guarantees can be used."

An HTTP client initiates a request by establishing a Transmission Control Protocol


(TCP) connection to a particular port on a host (port 80 by default; see List of TCP and UDP
port numbers). An HTTP server listening on that port waits for the client to send a request
message.

An HTTP client initiates a request by establishing a Transmission Control Protocol


(TCP) connection to a particular port on a host (port 80 by default; see List of TCP and UDP
port numbers). An HTTP server listening on that port waits for the client to send a request
message.

Upon receiving the request, the server sends back a status line, such as "HTTP/1.1
200 OK", and a message of its own, the body of which is perhaps the requested file, an error
message, or some other information.

Resources to be accessed by HTTP are identified using Uniform Resource Identifiers (URIs).

REQUEST METHODS

HTTP defines eight methods (sometimes referred to as "verbs") indicating the desired action
to be performed on the identified resource.

HEAD
Asks for the response identical to the one that would correspond to a GET request,
but without the response body. This is useful for retrieving meta-information written
in response headers, without having to transport the entire content.
GET
Requests a representation of the specified resource. By far the most common method
used on the Web today. Should not be used for operations that cause side-effects
(using it for actions in web applications is a common misuse). See 'safe methods'
below.
POST

266
Submits data to be processed (e.g. from an HTML form) to the identified resource.
The data is included in the body of the request. This may result in the creation of a
new resource or the updates of existing resources or both.
PUT
Uploads a representation of the specified resource.

DELETE

Deletes the specified resource

TRACE
Echoes back the received request, so that a client can see what intermediate servers
are adding or changing in the request.

OPTIONS
Returns the HTTP methods that the server supports. This can be used to check the
functionality of a web server.

CONNECT

Converts the request connection to a transparent TCP/IP tunnel, usually to facilitate


SSL-encrypted communication (HTTPS) through an unencrypted HTTP proxy.[1]

HTTP servers are supposed to implement at least the GET and HEAD methods and,
whenever possible, also the OPTIONS method.

SAFE METHODS

Some methods (e.g. HEAD or GET) are defined as safe, which means they are
intended only for information retrieval and should not change the state of the server (in other
words, they should not have side effects). Unsafe methods (such as POST, PUT and
DELETE) should be displayed to the user in a special way, typically as buttons rather than
links.

Despite the required safety of GET requests, in practice they can cause changes on the
server. For example, a Web server may use the retrieval through a simple hyperlink to initiate
deletion of a domain database record, thus causing a change of the server's state as a side-
effect of a GET request. This is discouraged, because it can cause problems for Web caching,
search engines and other automated agents, which can make unintended changes on the
server. Another case is that a GET request may cause the server to create a cache space.

267
The GET method means retrieve whatever information (in the form of an entity) is
identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the
produced data which shall be returned as the entity in the response and not the source text of
the process, unless that text happens to be the output of the process.

The semantics of the GET method change to a "conditional GET" if the request
message includes an If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or
If-Range header field. A conditional GET method requests that the entity be transferred only
under the circumstances described by the conditional header field(s). The conditional GET
method is intended to reduce unnecessary network usage by allowing cached entities to be
refreshed without requiring multiple requests or transferring data already held by the client.

The semantics of the GET method change to a "partial GET" if the request message
includes a Range header field. A partial GET requests that only part of the entity be
transferred.

The partial GET method is intended to reduce unnecessary network usage by


allowing partially-retrieved entities to be completed without transferring data already held by
the client.

The response to a GET request is cacheable if and only if it meets the requirements
for HTTP caching.

The POST method is used to request that the origin server accept the entity enclosed
in the request as a new subordinate of the resource identified by the Request-URI in the
Request-Line.

POST is designed to allow a uniform method to cover the following functions:

- Annotation of existing resources;


- Posting a message to a bulletin board, newsgroup, mailing list,
or similar group of articles;
- Providing a block of data, such as the result of submitting a
form, to a data-handling process;
- Extending a database through an append operation.

The actual function performed by the POST method is determined by the server and
is usually dependent on the Request-URI. The posted entity is subordinate to that URI in the
same way that a file is subordinate to a directory containing it, a news article is subordinate
to a newsgroup to which it is posted, or a record is subordinate to a database.

268
The action performed by the POST method might not result in a resource that can be
identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate
response status, depending on whether or not the response includes an entity that describes
the result..

If a resource has been created on the origin server, the response SHOULD be 201
(Created) and contain an entity which describes the status of the request and refers to the new
resource, and a Location header.

Responses to this method are not cacheable, unless the response includes appropriate
Cache-Control or Expires header fields. However, the 303 (See Other) response can be used
to direct the user agent to retrieve a cacheable resource.

POST requests MUST obey the message transmission requirements…….

Using HTTP GET

An HTTP GET request is most commonly used to request the contents of a URL or
web address. The GET request is typically limited to ~2k in size, plenty large to request data
from a URL. In it's basic form, a typical HTTP GET Request will look something like:

GET http://www.caslsoft.com

SendData function in a little more detail. This function handles allot of work for you,
including parsing the URL, determining the host to connect to, formatting the GET or POST
Request, sending the request, checking for timeouts and returning the response.

CONSIDER THE FOLLOWING DEFINITION FOR THE SENDDATA FUNCTION:

SendData(String URL, Numeric asPost, String inMsg) as string

Parameter Description
A string which contains the URL you want to
receive (GET) or send (POST) to. This will
commonly be a request such as
URL "http://www.yourwebsite.com". The function will
handle parsing the URL for you.

asPost true/false value that indicates if the request should

269
be sent as an HTTP GET (false) or POST (true).

This value contains the message you want to send


for the HTTP POST Request. This may be a
inMsg formatted XML message or any other type of data
the server is setup to handle. When performing an
HTTP GET Request, this parameter is ignored.

USING HTTP POST

In the previous section we sent an HTTP GET request to receive (or get) data from an
existing webpage, but what if you want to send data instead?

To send data to a remote web server, you'll want to perform an HTTP POST
Request. The data you send to the remote server will make use of the last two parameters of
the SendData function. The asPost (2nd parameter) should be set for true to indicate the
request should be sent as a POST.

The last parameter, inMsg is the message you want to POST (or send) to the remote
server. What appears within the inMsg string really depends upon the receiving system.

In some cases, it may be a formatted XML Message or a simple string of characters.


You will want to determine how the inMsg request should be formatted before using it.

It can easily be used to send an HTTP POST request to a Weblogic Java Server Page (.jsp) or
most any other web server..

THE FUNDAMENTAL DIFFERENCES BETWEEN "GET" AND "POST"

The HTML specifications technically define the difference between "GET" and
"POST" so that former means that form data is to be encoded (by a browser) into a URL
while the latter means that the form data is to appear within a message body.

But the specifications also give the usage recommendation that the "GET" method should be
used when the form processing is "idempotent", and in those cases only. As a simplification,
we might say that "GET" is basically for just getting (retrieving) data whereas "POST" may
involve anything, like storing or updating data, or ordering a product, or sending E-mail.

270
If the processing of a form is idempotent (i.e. it has no lasting observable effect on the state
of the world), then the form method should be GET. Many database searches have no visible
side-effects and make ideal applications of query forms.

If the service associated with the processing of a form has side effects (for example,
modification of a database or subscription to a service), the method should be POST.

In particular, the convention has been established that the GET and HEAD methods
SHOULD NOT have the significance of taking an action other than retrieval. These methods
ought to be considered "safe". This allows user agents to represent other methods, such as
POST, PUT and DELETE, in a special way, so that the user is made aware of the fact that a
possibly unsafe action is being requested.

Naturally, it is not possible to ensure that the server does not generate side-effects as a
result of performing a GET request; in fact, some dynamic resources consider that a feature.
The important distinction here is that the user did not request the side-effects, so therefore
cannot be held accountable for them.

When users revisit a page that resulted from a form submission, they might be
presented with the page from their history stack (which they had probably intended), or they
might be told that the page has now expired. Typical user response to the latter is to hit
Reload.

This is harmless if the request is idempotent, which the form author signals to the browser by
specifying the GET method.

Browsers typically will (indeed "should") caution their users if they are about to
resubmit a POST request, in the belief that this is going to cause a further "permanent change
in the state of the universe", e.g. ordering another Mercedes-Benz against their credit card or
whatever. If users get so accustomed to this happening when they try to reload a harmless
idempotent request, then sooner or later it's going to bite them when they casually [OK] the
request and do, indeed, order a second pizza, or invalidate their previous competition entry
by apparently trying to enter twice, or whatever.

Thus, some browsers can act more cleverly if the author uses "GET" or "POST"
consistently, i.e. using "GET" for pure queries and "POST" for other form submissions. It
needs to be noted, though, that using "GET" gives no protection against causing changes. A
script which processes a form submission sent with the "GET" could cause a pizza ordering.
It's just that authors are expected to take care that such things don't happen.

Moreover, the use of "POST" cannot guarantee that the user does not inadvertantly
submit the same form data twice; the browser might not give a warning, or the user might fail

271
to understand the warning. Users are known to become impatient when it seems that "nothing
happens" when they click on a button, so they might click on it again and again.

A "GET" request is often cacheable, whereas a "POST" request can hardly be. For
query systems this may have a considerable efficiency impact, especially if the query strings
are simple, since caches might serve the most frequent queries.

DIFFERENCES IN FORM SUBMISSION

For both METHOD="GET" and METHOD="POST", the processing of a user's submit


request (such as clicking on a submit button) in a browser begins with a construction of the
form data set, which is then encoded in a manner which depends on the ENCTYPE attribute.
That attribute has two possible values mentioned in the specifications, but multipart/form-
data is for "POST" submissions only, whereas application/x-www-form-urlencoded (the
default) can be used both for "POST" and for "GET".

If the method is "get" - -, the user agent takes the value of action, appends a ? to it, then
appends the form data set, encoded using the application/x-www-form-urlencoded content
type. The user agent then traverses the link to this URI. In this scenario, form data are
restricted to ASCII codes.

If the method is "post" --, the user agent conducts an HTTP post transaction using the
value of the action attribute and a message created according to the content type specified by
the enctype attribute.

Thus, for METHOD="GET" the form data is encoded into a URL (or, speaking more
generally, into a URI). This means that an equivalent to a form submission can be achieved
by following a normal link referring to a suitable URL.

DIFFERENCES IN SERVER-SIDE PROCESSING

In principle, processing of a submitted form data depends on whether it is sent with


METHOD="GET" or METHOD="POST". Since the data is encoded in different ways, different
decoding mechanisms are needed. Thus, generally speaking, changing the METHOD may
necessitate a change in the script which processes the submission. For example, when using
the CGI interface, the script receives the data in an environment variable when
METHOD="GET" is used but in the standard input stream (stdin) when METHOD="POST" is
used.

It is, however, possible to construct libraries of subroutines (e.g. Perl functions)


which allow one to write scripts in a manner which works both for METHOD="GET" and

272
METHOD="POST". This would be based on distinguishing between the cases within the
subroutine code and returning the data to the caller in a uniform manner.

5.5 SESSION TRACKING

Session tracking is a mechanism that servlets use to maintain state about a series of
requests from the same user (that is, requests originating from the same browser) across some
period of time.

SESSION-TRACKING BASICS

• Every user of a site is associated with a javax.servlet.http.HttpSession object that


servlets can use to store or retrieve information about that user

• Basic session tracking functionalities,

• Obtain a session (an HttpSession object) for a user.

• Store or get data from the HttpSession object.

• Invalidate the session (optional).

GET SESSION

• A servlet uses its request object's getSession() method to retrieve the current
HttpSession object:

• public HttpSession HttpServletRequest.getSession(boolean create)

• This method returns the current session associated with the user making the request.

• If the user has no current valid session, this method creates one if create is true or
returns null if create is false.

• To ensure the session is properly maintained, this method must be called at least once
before any output is written to the response.

PUT VALUE

• You can add data to an HttpSession object with the putValue() method:
• public void HttpSession.putValue(String name, Object value)

273
• This method binds the specified object value under the specified name. Any existing
binding with the same name is replaced

GET VALUE

• To retrieve an object from a session, use getValue():


• public Object HttpSession.getValue(String name)
• This methods returns the object bound under the specified name or null if there is no
binding.
• You can also get the names of all of the objects bound to a session with
getValueNames():
• public String[] HttpSession.getValueNames()
• This method returns an array that contains the names of all objects bound to this
session or an empty (zero length) array if there are no bindings

REMOVE VALUE

• Finally, you can remove an object from a session with removeValue():


• public void HttpSession.removeValue(String name)
• This method removes the object bound to the specified name or does nothing if there
is no binding
• Each of these methods can throw a java.lang.IllegalStateException if the session
being accessed is invalid

THE SESSION LIFE CYCLE

• Sessions do not last forever.


• A session either expires automatically, after a set time of inactivity (for the Java Web
Server the default is 30 minutes), or manually, when it is explicitly invalidated by a
servlet.

274
• When a session expires (or is invalidated), the HttpSession object and the data values
it contains are removed from the system.
• Beware that any information saved in a user's session object is lost when the session
is invalidated.
• If you need to retain information beyond that time, you should keep it in an external
location (such as a database) and store a handle to the external data in the session
object (or your own persistant cookie)

METHODS INVOLVED IN MANAGING THE SESSION LIFE CYCLE:

• public boolean HttpSession.isNew() This method returns whether the session is


new or not.
• public void HttpSession.invalidate()
• This method causes the session to be immediately invalidated. All objects stored in
the session are unbound.

• public long HttpSession.getCreationTime()


• This method returns the time at which the session was created
• public long HttpSession.getLastAccessedTime()
• This method returns the time at which the client last sent a request associated with
this session

5.6 COOKIES

In Javascript, cookies are a mechanism for storing persistent data on the client in a
file called cookies.txt. Because Hypertext Transport Protocol (HTTP) is a stateless protocol,
cookies provide a way to maintain information between client requests.

Each cookie is a small item of information with an optional expiration date and is
added to the cookie file in the following format:

name=value;expires=expDate;

275
Here,

• name is the name of the datum being stored, and value is its value.

• expDate is the expiration date, in GMT date format: Wdy, DD-Mon-YY HH:MM:SS
GMT

Below is a simple function named setCookie() to create a cookie called myname. It also
uses a function getCookie() to get the value of a cookie, if cookie name exist and is given as
an argument.

We end the discussion of javascript by providing you with the organizational chart which
features you the hierarchy of objects of HTML 4.0 that can be easily accessed using the
javascript.

OBJECTS HIERARCHY OF HTML 4.0

window

document history location

276
Anchor Applet Area Form Image Link

Button FileUpload Password Reset Submit TextArea

Checkbox Hidden Radio Select Text

The Web Concept such as Server push and Client pull can be described as:

With server push, the Web page server maintains a connection between the client (the
browser) and server. Server push restricts the number of simultaneous connections the Web
page server can maintain a popular page using server push will frequently reward potential
visits with a “sorry, not now, try later” message.

Client pull, on the other hand, involves the client frequently reestablishing its
connection to the server, artificially adding to the traffic at the server. We can use Javascript
to create dynamic documents that would have required either server push or client pull in
CGI, but that involve no additional traffic or long, drawn-out connections between the client
and the server.

COOKIES IN PERL:

In Perl, Cookies can be set by using the “Set-Cookie” method as described below:

Print “Set-Cookie:name=siva”;

The cookie can be later referred again from the Perl Script by using
the”Environmental Variable” as:

$var=$ENV{‘HTTP_COOKIE’};

In this case, the value of the cookie is extracted to the variable var.

277
Database connectivity in PERL:

Any web programming language does not have its honor without providing the
necessary interaction commands for database connectivity. PERL has its own interactive
statements to connect to a database and display the details of the database.

The WIN32:: ODBC module is an extension to Perl which permits connectivity to


database using ODBC drivers. To add ODBC connectivity, the following step is to be added
to the source code:

Use Win32:: ODBC;

The possible object methods for Database connectivity and straightaway run to a sample
coding:

i. The new method:


Syntax : new Win32:: ODBC(DSN);

This method creates a new ODBC object for the given DSN

ii. The Connection Method:


This method will return the object’s ODBC Connection number on success.
Each of the connections is assigned a unique number for identification purposes.

iii. The Sql Method:

Syntax : Sql( sql statement)

This method executes a sql command and returns undef on success. Else, an
error code is returned.

The FetchRow method:

This method fetches the next row of the data from the specified SQL method
source. Returns True if there exist next row. If the record pointer is already at the last row or
if there is no record in the sql statement, false is returned.

278
iv. The Data method:

This method retrieves data from a FetchRow method for a list of field names. If
no field names are given, all fields are returned in an unspecified order. In a scalar context,
the Data method returns all of the specified fields concatenated together. In an array context,
it returns the array values, in the specified order.

v. The DataHash Method:

This method retrieves data from a FetchRow method just like the Data method.

vi. The Close Method:

This method closes the ODBC connection for the object and returns an undef.

The listing given below just attempts to connect to an Access database using
DSN connection and prints the data present in the database.

To run this coding properly, we have to create a DSN named bibilo. If we know the process,
keep creating the DSN, else follow the steps given below:

i. Go to Start Menu -> Settings -> Control panel -> Administrative Tools -> Data Sources
The entire code(ODBC)
listing is
# ! /usr/bin/perl ->given below:
System DSN -> Add.
ii. In the newly appeared dialog box, select the “Driver do Microsoft Access(*.mdb) and
# This program illustrates DB connectivity concepts
press Finish
iii. In the new dialog box, type the DataSourceName as “bibilo” and select the
print “Content-type:
“bibilo.mdb” text/html\n\n”;
by pressing the Select button. Finally press the OK button.
print “<html><head></head><body>”;

use Win32: :ODBC;


print “<table border=1 cellpadding=1 cellspacing=1><tr bgcolor=gray> <td>”;
print “<b> Aythor id </b> </td> <td> <b> Author Name </b></td></tr>”;
if(($db=new Win32: :ODBC(“dsn=bibilo;”)))
{
$no=$db->Connection;

print “Connection identification number is: $no”;


print “<p align=center> <font color=red> DATA IS </font> </p>”;
$db ->Sql (“SELECT * FROM authors”);
while($db->FetchRow())
{
undef %Data;
%Data=$$db->DataHash();
print “<tr> <td>$Data{ ‘Au_ID’ } </td><td> $Data{ ‘Author’ }</td></tr>”;
}
print “</table>”;
279
}
print “</body></html>”;
5.7 JDBC

INTRODUCTION

It is actually inherited inside our coding using “use command. Then, new method
creates a new ODBC object for the given DSN named ‘bibilo’. The ODBC object’s name is
db. Then the connection method is used to return the ODBC connection identification
number, which is printed on the screen. The Sql method executes the Select statement and the
FetchRow() method fetches the next row of data from the Sql statement. The FetchRow()
method is placed inside a while loop and the method returns false and terminates the loop if
the end of the record is reached. Inside the loop, the DataHash() method retrieves data for the
fields “Au_ID” and “Author”. The values are got in an associative array in our case, and
printed on the screen using the print method.

280
• A database is a collection of interrelated data is contiguous in some organized fashion
and DBMS is a software that provides a mechanism to retrive, modify and add data to
the database.

• A table is a unit of storage which holds data in the form of rows and columns.Thus, a
collection of all tables with their interrelationship could be termed as database.

• The DBMS whose design is based on the Relational theory is called RDBMS.

• There are many DBMS/RDBMS product are available,

 For eg: Oracle, Sybase, Informix, MS-SQL Server, MS-Access stores


data in .MDB file format.

• JDBC(Java Database Connectivity)is defined,as a set of java classes and methods


to interface with database. It also provides uniform access to a wide range of
relational databases.The java 2 software bundle includes JDBC-ODBC bridge.

Introduction to SQL:

The SQL(Structured Query Language) is used to retrive, store and change the data.

Commands which are used to create a table in SQL * plus in oracle.

Create:
This command is used to create a table

Syntax:

CREATE TABLE tabname(colname1 datatype(size),colname2 datatype(size),….., colnameN


datatype(size));

Eg: Create a student table

Colname Data type Size

281
Regno Number 5

Name Varchar2 20

Class Varchar2 20

Mark Number 3

SQL>CREATE TABLE student(regno number(5),name varchar2(20),class


varchar2(20),mark number(3));

INSERT:

It is used to add one or more rows in a table.

SYNTAX: INSERT INTO tablename VALUES(a list of values);

Eg: Insert a record in the student table regno 1001 name xxxx class ICSE mark 97

INSERT INTO student VALUES(1001,’xxxx’,’ICSE’,97);

SELECT:

It is used to retrive the information in the table.

SYNTAX: SELECT colname1,…….colnameN from table name;

Eg1: Select the student names in student table.

SELECT name FROM student;

Eg2: Select all the records in the student table

SELECT * FROM student;

UPDATE:

It is used to change the column values in a table.

SYNTAX: UPDATE tablename SET column name=value WHERE condition.

Eg: Update table student set mark=100 where regno=1001

282
UPDATE student SET mark=100 WHERE regno=1001;

DELETE:

It is used to delete the rows in a table.

SYNTAX: DELETE FROM tablename WHERE CONDITION;

Eg1: Delete the stud where regno=1001

DELETE FROM student WHERE regno=1001;

Eg2: Delete all records from student table.

DELETE FROM student;

DATA BASE CONNECTIVITY:

For any application to communicate with the database,it needs to have the following
information:

1.The RDBMS/DBMS product is used to which the database is created.


2.where database reside(location)
3.The name of the database.

So, we use JDBC calls to retrive and update information from a database using JDBC.
This involves the following functions:

1.Opening and establish a database connection.


2.send SQL statements.
3.Process the returned result set.
4.Close the database connection.

ODBC API:
• Microsoft ODBC(Open Data Base Connectivity) Application programming interface
is mostly used programming interface for accessing RDBMS.

• JDBC and ODBC are based on the X/Open SQL command level interface.

• This is an interface to perform SQL calls to database.

283
Application Oracle
Data Base
ODBC
Oracle SQL
Driver Driver SQL
Data Base

JDBC API

The JDBC API is available in the java.sql and javax.sql packages. Following are
important JDBC classes, interfaces and exceptions in the java.sql package:

• DriverManager - Loads JDBC drivers in memory. Can also be used to open


connections to a data source.
• Connection - Represents a connection with a data source. Is also used for creating
Statement, PreparedStatement and CallableStatement objects.
• Statement - Represents a static SQL statement. Can be used to retrieve ResultSet
object/s.
• PreparedStatement - Higher performance alternative to Statement object, represents
a precompiled SQL statement.
• CallableStatement - Represents a stored procedure. Can be used to execute stored
procedures in a RDBMS which supports them.
• ResultSet - Represents a database result set generated by using a SELECT SQL
statement.
• SQLException - An exception class which encapsulates database base access errors.

javax.sql is part of J2SE 1.4 and J2EE 1.3. It adds following features to JDBC in addition to
the ones provided by java.sql package:

• DataSource - Abstracts a data source. This object can be used in place of


DriverManager to efficiently obtain data source connections (possibly using hidden
connection pooling).
• Provides built-in connection pooling.
• XADataSource, XAConnection - Allows/supports distributed transactions.
• RowSet - It extends ResultSet interface to add support for disconnected result sets.
• Java Database connectivity provides a database programming API for java programs.

• Java programs cannot directly communicate with the ODBC driver.

284
• Sun Microsystem provides a JDBC-ODBC bidge that translate JDBC to ODBC.

• There are several types of JDBC drivers available.They are:

• JDBC-ODBC bridge+ODBC driver


• Native API partly java driver.
• JDBC-Net pure java driver.
• Native protocol pure java driver.

JDBC-ODBC bridge + ODBC driver (Type 1 Drivers)

• This drivers are the bridge drivers such as the JDBC-ODBC bridge.

• These drivers rely on an intermediary such as ODBC to transfer the SQL


Calls to database.

• Bridgedrivers often rely on native code, although the JDBC-ODBC library native
code is part of the java 2 virtual machine.

Application
JDBC-
DriverManager
ODBC Driver
Manager ODBC
ODBC libraries Database

NATIVE API PARTLY JAVA DRIVER (TYPE 2 DRIVERS)

• A native API is partly a java driver uses native C language library calls to translate
JDBC to native client library.
• These drivers are available for oracle,Sybase. DB2 and other client library based
RDBMS.
• Type 2 drivers are faster than Type 1 driver.

285
• Type 2 drivers use native code and require additional permissions to work in an
applet.
• A Type 2 driver might need client-side database code to connect over the network.

Application

JDBC
Socket
DBMS Vendor connection
Client Side DBMS
Libraries based Server
On C Language

JDBC-NET PURE JAVA DRIVER (TYPE 3 DRIVERS)

• JDBC- Net pure java Driver consist of JDBC and DBMS independent protocol driver.
• Here the calls are translate and sent to middle tier server through the socket. The
middle tier contact the databases.

• Type 3 Drivers call the database API on the server. JDBC requests from the client are
first proxied to the JDBC Driver on the server to run.
• Type 3 and 4 drivers can be used by thin(java based) clients as they need no native
code.

NATIVE PROTOCOL PURE JAVA DRIVER (TYPE 4 DRIVERS)

• A native protocol java driver contain JDBC calls that are converted directly to the
network protocol used by the DBMS server.

• Type 4 drivers can also be used on this clients as they also have no native code.

• The network protocol is defined by the vendor and is typically proprietary, the
driver usually comes only from the database vendor.

Application
Socket
JDBC connection(DBMS
specific protocol
Java based
Socket driver

286
DBMS
server

5.8 SIMPLE APPLICATIONS

• An N-tier application is anything that is divided into discrete logical parts.

• The most common choice is a three-part breakdown—presentation, business logic,


and data.

• N-tier applications first emerged as a way of solving some of the problems associated
with traditional client/server applications, but with the arrival of the Web, this
architecture has come to dominate new development.

• The Microsoft .NET Framework also provides a solid platform for building N-tier
applications.

5.9 MULTI TIER APPLICATIONS

INTRODUCTION

 The 3-tier architecture overcomes the weaknesses of the 2-tier and client/server
architectures.
 It contains a client workstation, a component server, and a database server.
 The user interface is on the client side while business logic and data
management are in dedicated tiers.

The 3-Tier architecture has the following 3-tiers:


 Presentation Tier
 Application Tier/Logic Tier/Business Logic Tier
 Data Tier

287
• Multitier applications divide functionality into separate tiers.

• Although tiers can be located on the same computer, the tiers of Web-based
applications reside on separate computers.

288
INFORMATION TIER

• The information tier also called the data tier or the bottom tier.
• It maintains data pertaining to the application.
• This tier typically stores data in a relational database management system (RDBMS).

MIDDLE TIER

• The middle tier implements business logic, controller logic and presentation logic
to control interactions between the application's clients and the application's data.
• It acts as an intermediary between data in the information tier and the application's
clients.
• The middle-tier controller logic processes client requests and retrieves data from the
database.

CLIENT TIER

• The client tier, or top tier, is the application's user interface, which gathers input and
displays output.
• Users interact directly with the application through the user interface, which is
typically a Web browser, keyboard and mouse. In response to user actions the client

289
tier interacts with the middle tier to make requests and to retrieve data from the
information tier.
• The client tier then displays the data retrieved from the middle tier to the user. The
client tier never directly interacts with the information tier.

TIER-TO-TIER COMMUNICATION

Communication between the user interface and business tiers can be achieved by
• HTTP
• RMI
• CORBA
• DCOM
Communication between the business and persistence tier can be achieved by
• JDBC

END OF UNIT V

QUESTION BANK

UNIT I – BASIC NETWORK AND WEB CONCEPTS

1. Why networking in Java is essential?

290
Java is the first programming language designed from the ground up with networking
in mind.
As the global internet continues to grow, java is uniquely suited to build the next
generation of network applications.
Java is platform independence, security, and international character sets being the
most important – that are crucial to internet applications.
It makes network programs easy. It is easy for java applications to send and receive
data across the internet.
It is also possible for applets to communicate across the internet, though they are
limited by security restrictions.

2. What can a network program do?

Networking adds a lot of power to simple programs. With networks, a single program
can retrieve information stored in millions of computers located anywhere in the
world.
A single program can communicate with tens of millions of people. A single program
can harness (tie together) the power of many computers to work on one problem.
Network applications generally take one of several forms. The distinction is
clients and servers.
In the simplest case, clients retrieve data from a server and display it. More complex
clients filter and reorganize data, repeatedly retrieve changing data, send data to other
people and computers, and interact with peers in real time for chat, multiplayer
games, or collaboration.

3. Mention the advantages of java/java script

• Use sending data continuously File storage


• Massively parallel computing
• Smart forms – includes various controls like text box, radio button, text area control
etc.
• Peer-to-Peer Interaction – used in various client/server model.
• Games – Combine the ability to easily include networking in your programs with
java’s powerful graphics and you have the recipe for truly awesome multiplayer
games.
• Chat – Used in various chat applications.
• Whiteboards – Java programs are not limited to sending ext and data across the
network. A number of programmers have developed whiteboard software that allows
users in diverse locations to draw on their computers.

291
4. Define Internet.

Network is an interconnection of systems to share data and information.

Internet is network of network or collection of heterogeneous networks.

5. What can a network program do? Or uses or advantages of Networking


concept.

Repeatedly Retrieve Data


• Use sending data continuously.
• File storage
• Massively parallel computing
• Smart forms – includes various controls like text box, radio button, text area control
etc.
• Peer-to-Peer Interaction – used in various client/server model.
• Games – Combine the ability to easily include networking in your programs with
java’s powerful graphics and you have the recipe for truly awesome multiplayer
games.
• Chat – Used in various chat applications.
• Whiteboards – Java programs are not limited to sending ext and data across the
network. A number of programmers have developed whiteboard software that allows
users in diverse locations to draw on their computers.
• Servers Java applications can listen for network connections and respond to them.
This makes it possible to implement servers in Java. Both Sun and W3C have written
web servers in Java designed to be as fully functional and fast as servers written in C.
• Various protocols are available in Server for communication like HTTP, FTP, TCP
etc.
ELECTRONIC COMMERCE

292
3. Shopping sites have proven to be one of the few real ways to make money from
consumers on the web.
4. Although many sites accept credit cards through HTML forms, the mechanism is
clunky (clubbing).
5. Shopping carts (pages that keep track of where users have been seen and what they
have chosen) are at the outer limits of what’s possible with HTML and forms.
6. MENTION THE LAYERS OF A NETWORK

Application Layer Logical path Application Layer

Transport Layer (TCP, UDP) Transport Layer (TCP, UDP)

Internet layer (IP) The Host to Internet layer (IP)


Physical path Host Physical path(Ethernet, FDDI
Layer etc
7.
INTERNET PROTOCOL (IP) CONTAINS ONLY 4 LAYERS, NAMELY

6.1 Application layer


6.2 Transport Layer(TCP, UDP)
6.3 Internet Layer (IP)
6.4 Host to Host Layer

7. WHAT IS THE USE OF IP ADDRESSES AND PORTS?

4. It is very difficult to remember the IP address of each and every node.


5. It order to avoid this problem domain names are used.
6. Example googl.com, rediff.com etc.

PORTS

4. Ports are used in receiving and sending data to another server or client.
5. Example for port numbers

Protocol Port Protocol Purpose

Echo 7 TCP/UDP Echo is a test protocol used to verify that 2 machines


are able to connect by having one echo back the

293
other’s input.
Discard 9 TCP/UDP Discard is a less useful test protocol in which all data
received by the server is ignored.
FTP 21
SMTP 25
HTTP 80
POP3 110
NTP 119 Usenet news transfer is more formally known as the
Network News Transfer Protocol
RMI 1099 This is the registry service for Java Remote Objects.
Registry

8. MENTION THE DIFFERENT INTERNET ADDRESS CLASS AND IT’S RANGE.

8. Internet addresses are assigned to different organizations by the Internet


Assigned Numbers Authority (IANA).
9. ISP – Internet Service Providers gives a block addresses.
10. Class C address block specifies the first 3 bytes of address, for example
199.1.32. This allows room for 254 individual addresses from 199.1.32.1 to
199.1.32.254
11. Class B address specified only the first 2 bytes of the addresses .
12. There are also Class D and E addresses are used for IP multicast group.

9. DEFINE FIREWALL.

The hardware and software that sits between the Internet and the local network, checking all
the data that comes and goes out is called “firewalls”. The security is provided using
SSL(Secure Socket Layer) in internet.

10. DEFINE PROXY SERVERS

Proxy servers are related to firewalls prevents hosts on a network from making direct
connections to the outside world, a proxy server can act as a go-between.

Thus a machine that is prevented from connecting to the external network by a firewall
would make a request for a web page from the local proxy server instead of requesting the
web page directly from the remote web server.

11. Mention the various levels of W3C RECOMMENDATIONS (WWW 3 Consortium)

W3C Levels

294
4. Recommendation - is the highest level of W3C standard. However, the W3C is very
careful not to actually call this a “standard” for fear of running afoul (afraid) of
antivirus statutes.

5. Proposed Recommendation - A proposed recommendation is mostly complete and


unlikely to undergo more than minor changes.

The main purpose of a Proposed recommendation is to work out bugs in the


specification document rather that in the in the underlying technology documented.

6. Candidate Recommendation

A candidate Recommendation indicates that the working group has reached consensus
on all major issues and is ready for third-party comment and implementations.

12. WHAT IS THE USE OF HTTP PROTOCOL?

HTTP is a standard protocol that defines how a web client talks to a server and how data
is transferred from the server back to the client.

HTTP relies heavily on two other standards.


2. MIME (Multi purpose Internet Mail Extensions
3. HTML

13. WHAT IS THE USE OF MIME?(Multipurpose Internet Mail Extension)

7. MIME is a way to encode different kinds of data, such as sound and text, to be
transmitted over a 7-bit ASCII connection.

8. It also lets the recipient know what kind of data has been sent, so that it can be
displayed properly.

9. MIME was originally designed to facilitate multimedia email and to provide an


encoding that could get binary data past the most train –damaged mail transfer
programs.

14. DEFINE URL & URN.

URL

• Uniform Recourse Locator is a way to unambiguously identify the location of a


resource on the Interned.

295
URI Uniform Resource Identifier is a string of characters in a particular syntax that
identifies a resource.

• The resource identified may be a file on a server, but it may also be an email address,
a news message, b book, a person’s name, an Internet host.
Syntax

Scheme:scheme-specific-part

Scheme types

1. data – base 64 encoded data included directly in a link


2. file – A file on a local disk
4. FTP – An FTP server
5. gopher – a Gopher server
6. mailto – an email address
7. news – A Usenet newsgroup
8. Telnet – A connection to a Telnet based service (only used in Remote Login System)
9. urn – Uniform Resource Name

15. EXPLAIN ABOUT URN

There are 2 types of URLs.

3. URL – Unform Resource Locaters (is a pointer to a particular resource on the Internet
at a particular location.)

4. URNs – Uniform Resource Name (is a name for a particular resource but without
reference to a particular location)

SYNTAX OF URN

urn:namespace:resource-name

1. namespace - is the name of a collection of certain kinds of resources maintained by


some authority.
2. resource-name – is the name of a resource within that collection.

16. WHAT IS MEANT BY RELATIVE URL?

URLs that are not complete but inherit pieces from their parent are called relative URL.

In contrast, a completely specified URL is called an absolute URL.

296
17. EXPLAIN ABOT SGML – STANDARD GENERALIZED MARKUP LANGUAGE

• HTML is an instance of SGML.


• SGML was invented beginning in the mid-1970s by Charles Goldfarb at IBM
• SGML is now an International Standards Organization (ISO) standard, specifically
ISO 8879:1986.
• SGML allows the user to create various user defined tags easily without any rules.

EXAMPLE 1 – FOR PRODUCT DETAILS

<PRODUCT MANUFACTURER=”ABC COMPANY”> -Assumed as record name


<NAME> KEY BOARD </NAME>
<TYPE> KEY BOARD </TYPE>
<PRICE> 1500 </PRICE>
</PRODUCT

18. EXPLAIN ABOUT XML – EXTENSIBLE MARKUP LANGUAGE

• Similar to SGML
• Allows the user to create any number of user defined tags.
• The value of an attribute may be enclosed in double of single quotes like this:
• <H1 ALIGN=CENTER> THIS IS CENTERED H1 HEADING </H1>
• STYLES can be introduced for XML program like CSS using XLS file(XML Style
Sheet program)
• Here XML styles are saved with an extension of .xls (XML style sheet)
• Using .xls files various styles can be given to the data which is inside the XML
program.

19. LIST THE STEPS FUNCTIONS OF HTTP PROTOCOL.

1. Standard protocol for communication between web browsers and web servers.
2. HTTP specifies how a client and server establish a connection, how the client
requests data from the server, how the server responds to that request, and
finally how the connection is closed.

297
3.HTTP 1.0 is the currently accepted version of the protocol. It uses MIME to encode
data. The basic protocol defines a sequence of 4 steps for each request from a client to
the server.
3. Making the connection
4. Making a request
5. Receiving the response
6. Closing the connection
20. MIME

1. MIME is an open standard for sending multipart, multimedia data through


Internet email.

2. MIME was originally intended for email, it has become a widely used
technique to describe a file’s contents so that client software can tell the
difference between different kinds of data.

Type Subtype Description

Text Calendar Calendar control

Css A CSS used for HTML and XML

directory Address book information such as name, phone, email


address.

21. EXPLAIN ABOUT CGI – COMMON GATEWAY INTERFACE

• CGI is used to generate web pages dynamically.


• It is not a programming language.
• It is an environment which provides facility for executing programs and

Simple program

<HTML>
<HEAD>
<TITLE> CGI EXAMPLE </TITLE>
</HEAD>

298
<BODY>
<FORM METHOD = GET ACTION = “/cgi/register.pl”>

Enter your Name <input type = “text” name = nname size = 25>
Enter your Mail address <input type = “text” name = nmail size = 10>
</FORM>
<input type = “submit” name = “nsubmit”>
<input type = “reset” name = “nreset”>
</FORM> </BODY> </HTML>

NOTE: CGI files are stored in .pl extension.

22. WHAT DO YOU MEAN BY APPLETS AND SECURITY?

• Applets are just more files that are transferred like any other.

• Applets are small windows in which the data can be given and data can be
displayed also.

WHERE DO APPLETS AND CLASSES COME FROM?

• When a browser sees an applet tag and decides to download and play the applet, it starts a
long chain of events.

• Let’s say your browser sees the following applet tag:

<applet codebase = http://javafaq/classes code = “Animation.class” width = 200 height


= 300>

1. The web browser sets aside a rectangular area on the page 200 pixels wide and
300 pixels height.
2. The browser opens a connection to the server specified in the codebase parameter,
using port 80.
3. The browser requests the .class file from the web server as it requests any other
file. If a code base is present, it is prefixed to the requested filename. Otherwise,
the document base (the directory that contains the HTML page) is used.
4. The server responds by sending a MIME header followed by a blank line (\r\n)
followed by the binary data in the .class file.
5. The web browser receives the data and stores it in a byte array.

299
6. The byte code verifier goes over the byte codes that have been received to make
sure they don’t do anything forbidden, such as converting an integer in to pointer.

SECURITY: WHO CAN AN APPLET TALK TO AND WHAT CAN IT SAY?

There is much FUD (fear, uncertainty, and doubt) in the press about what Java applets
can and cannot do.

6. Applets cannot access arbitrary addresses in memory. Unlike the other


restrictions I the list, which are enforced by the browser’s SecurityManager
instance, this restriction is a property of the Java language itself and the byte code
verifier.
7. Applets cannot access the local file system in any way. They cannot read from or
write to the local file system nor can they find out any information about files.
8. Applets cannot launch other programs on the client. In other words, they can not
call Sysem.exec() or Runtime.exec().
9. Applets cannot load native libraries or define native method calls.
10. Applets may not define any system properties.

Finally, most important of applets are

4. An applet can only open network connections to the host from which the applet
itself was downloaded.
5. An applet cannot listen on ports below 1024 (IE 5.0 does not allow applets to
listen on any ports)
6. Even if an applet can listen on a port, it can accept incoming connections only
from the host from which the applet itself was downloaded.

END OF UNIT I

UNIT II - I/O STREAMING

23. LIST THE VARIOUS TYPES OF STREAM CLASSES IN JAVA

8. I/O in java is built on streams.

300
9. Input streams read data/Output streams write data

10. Different fundamental stream classes such as java.io.FileInputStream and


sun.net.TelnetOutputStream read and write particular sources of data.

11. Filter streams can be chained to wither an input stream or an output stream.

12. Filters can modify the data as it’s read or written – for instance, by encrypting or
compressing it.

13. java.io.DataOutpurStream class provides a method that converts an integer to four


bytes and writes those bytes onto its underlying output stream.

14. Finally, readers and writers can be chained to input and output streams to allow
programs to read and write text (that is characters) rather than bytes.

24. DEFINE STREAM AND MENTION ITS TWO MAJOR CLASSIFICATION

STREAM is a path of communication between two clients or client to server or server to


client or server to server. There are two types of streams. They are

1. Byte Stream -> Read/Write operation is performed byte by byte at a time.

2. Character Stream -> Read/Write operation is performed character by character


at a time.

25. LIST THE CLASS PROVIDES THE FUNDAMENTAL METHODS NEEDED TO


WRITE DATA.

public abstract void write(int b) throws IOException


public void write(byte[] data) throws IOException
public void write(byte[] data, int offset, int length ) throws IOException
public void flush() throws IOException
public void close() throws IOException

26. WHAT IS THE MEANING OF FLUSH (WASH OUT) METHOD ?

301
Flush method rescues you from deadlock by forcing the buffered stream to send its data
even if the buffer is not yet full.

26. LIST THE CLASS PROVIDES THE FUNDAMENTAL METHODS NEEDED TO


READ DATA.

public abstract int read() throws IOException

public int read(byte[] input) throws IOException

public int read(byte[] input, int offset, int length ) throws IOException

public long skip(long ) throws IOException

public int available() throws IOException

public void close() throws IOException

27. MARKING AND RESETTING

• The InputStream class also has three less commonly used methods that allow
programs to back up and reread data they’ve already read. These are:

1. public void mark(int readAheadLimit)


2. public void reset() throws IOException
3. public Boolean markSupported()
Marking
7. Mark the current position in the stream with the mark() method.
8. At a later point, you can reset the stream back to the marked position using the reset()
method.
9. Subsequent reads then return data starting from the marked position.

10. The number of bytes you can read from the mark and still reset is determined by the
readAheadLimit argument to mark.

11. If you try to reset back too far, and IOException will be thrown.
12. There can be only one mark in a stream at any given time. Marking a second location
erases the first mark.

13. Marking and resetting are usually implemented by storing every byte read from the
marked position in an internal buffer.

28. WHAT IS THE USE OF FILTER STREAMS?

302
3. Input/Output stream are fairly raw classed. They allow you to read and write bytes,
either singly or in groups, but deciding what those bytes mean – whether they are
integers or IEEE 754 floating numbers or Unicode text is completely up to the
programmer and the code.

4. Many files transferred by ftp are stored in the zip format. Java provides a number of
filter classes you can attach to raw streams to translate the raw bytes to and from
these and other formats.

29. WHAT IS THE USE OF BUFFERED STREAMS?

1. The BufferedOutputStream class stores written data in a buffer until the buffer is full
or the stream is flushed.

2. Then it writes the data onto the underlying output stream all at once.

3. BufferedInputStream class works Similar to BufferedOutputStream class for read


operation.

30. LIST THE CONSTRUCTORS USED IN BUFFERED IN/OUT STREAM CLASSES

public BufferedInputStream(InputStream in)


public BufferedInputStream(InputStream in, int bufferSize)
public BufferedInputStream(InputStream out)
public BufferedInputStream(InputStream out, int bufferSize)

31. THE PRINTSTREAM

The printStream class is the first filter output stream most programmers encounter’ because
System.out is a PrintStream. However, other output streams can also be chained to print
streams, using these two constructors:

public printStream(OutputStream out)


public printStream(OutputStream out, Boolean autoflush)

32. LIST THE METHODS OF PRINTSTREAM CLASS

PRINTSTREAM – has 9 overloaded print() methods and 10 overloaded println() methods.

303
1. public void print(boolean b)
2. public void print(char b)
3. public void print(int b)
4. public void print(long b)
5. public void print(float b)
6. public void print(double b)
7. public void print(char[] text)
8. public void print(String s)
9. public void print(Object o)

1. public void println(boolean b)


2. public void println(char b)
3. public void println(int b)
4. public void println(long b)
5. public void println(float b)
6. public void println(double b)
7. public void println(char[] text)
8. public void println(String s)
9. public void println(Object o)
10. println()

33. LIST VARIOUS COMPRESSING STREAMS

Java .util.zip package contsins filter streams that compress and decompress
streams in zip, gzip, and deflate(shrink or reduce) formats.

There are 6 stream classes that perform compression and decompression.

1. public class DeflaterOutputStream extends FilterOutputStream


2. public class DeflaterInputStream extends FilterInputStream
3. public class QDeflaterOutputStream extends FilterOutputStream
4. public class DeflaterOutputStream extends FilterOutputStream
5. public class DeflaterOutputStream extends FilterOutputStream
6. public class DeflaterOutputStream extends FilterOutputStream and so on.

34. WHAT IS THE USE OF DIGEST (assimilate, absorb, grasp, observe)STREAMS

• The java.util.security package contains two filter streams that can


calculate a message digest for a stream.

• They are DigestInputStream and Digest-OutputStream.

304
• A message digest, represented in Java by the
java.util.security.MessageDigest class, is a strong hash code for the
stream; that is, it is a large integer (typically 20 bytes long in binary
format) that can easily be calculated from a stream of any length in such a
fashion that no information about the stream is available from the message
digest.

• A messageDigest object that uses a particular algorithm, such as the


Secure Hash Algorithm (SHA).

35. WHAT IS THE USE OF ENCRYPTING STREAMS?

1. CipherInputStream and CipherOutputStream are part of a standard extension to java


called the Java Cryptography Extension.

2. public CipherInputStream(InputStream in, Cipher c)

3. public CipherOutStream(InputStream in, Cipher c) – used for encryption and


decryption respectively.

36. READERS AND WRITERS

1. Java’s native character set is the 2-byte Unicode character set. Consequently, Java
provides an almost complete mirror of the input and output stream class hierarchy
that’s designed for working with characters instead of bytes.

2. Two abstract super classes define the basic API for reading and writing characters.

3. The java.io.Reader class specifies the API by which characters are read.

4. The java.io.Writer class specifies the API by which characters are written.

5. Wherever input and output streams use bytes, readers and writers use Unicode
Characters.

6. The most important sub classes are InputStreamReader and the


OutputStreamWriter classes.
FileReader
FileWriter
StringReader
StringWriter
ChararrayReader
CharArrayWriter

305
WRITERS

• The Writer class mirrors the java.io.OutputStream.class. It’s abstract and has two
protected constructors. Write OutputStream, the Writer class is never used
directly, but one of its subclasses.

1. protected Writer()
2. protected Writer(Object lock)
3. public abstract void write(char[] text, int offset, int length) throws
IOException

4. public void write(int c) throws IOException


5. public void write(char[] text) throws IOException
6. public void write(String s, int offset, int length) throws IOException
7. public abstract void flush() throws IOException
8. public abstract void close() throws IOException

READERS

• The Reader class mirrors the java.io.InputStream class.


• All the classes of writers is applicable for readers also, change read instead of
write

LineNumberReader

• The LineNumberReader class replaces the deprecated LineNumberInputStream class


from Java 1.0. It’s a subclass of BufferedReader that keeps track of the current line
number being read.

• Line number can be retrieved at any time with the getLineNumber() method.
public LineNumberReader(Reader in)
public LineNumberReader(Reader in, int bufferSize)

Similarly we have

3. PushbackReader
4. PrintWriter classes.

37. DEFINE THREAD.

• A thread with a little t is a separate independent path of execution in the virtual


machine.

306
• A Thread with a capital T is an instance of the java.lang.Thread class.

• There is a one-to one relationship between threads executing in the virtual


machine and Thread objects also constructed by the virtual machine.

• Most of the time it’s obvious from the context which is meant if the difference is
really important.

• To start a new thread running in the virtual machine, construct an instance of


Thread class and invoke its start() method as follows:

3. For creating a Thread

Thread t = new Thread();


t.start()

4. To run a Thread
Public void run()

NOTE By default a java program has one thread.

38. DEFINE RACE CONDITION ALGORITHM. POLLING AND CALLBACKS

Java Virtual Machine uses different algorithms to allot time to different threads. This is
called a race condition.

POLLING

The solution mostly adopt is to have the getter method return a flag value (or perhaps throw
an exception) until the result field is set. Then the main thread periodically polls the getter
method to see whether it’s returning something other than the flag value.

CALLBACKs

307
There are more efficient way to handle the problem. The infinite loop that repeatedly polls
each ReturnDigest object to see whether it is finished can be eliminated.
39. SYNCHRONIZATION (organization)

Synchronization is the process of organizing threads in a proper way. That is if one thread is
activated another thread will be put into sleep mode. In the next cycle the thread which is in
sleep mode is activated now and the other thread is put in to sleep mode.

Synchronization process is very much essential for handling Threads properly.

CYNCHRONIZED BLOCKS

Synchronization must be considered any time multiple threads share resources. These
threads may be instances of the same Thread subclass or use the same Runnable class, or they
may be instances of completely different classes.

40. LIST THE VARIOUS ALTERNATICES TO SYNCHRONIZATION

1. Synchronization is not always the best possible solution to the problem of


inconsistent behavior as a result of thread scheduling.

2. There are a number of techniques you can use to avoid the need for synchronization.

Method 1

1.5 Use local variables instead of fields wherever possible. Local variables do not have
synchronization problems.

1.6 String arguments are safe because they are immutable, that is, once a string object has
been created, it cannot be changed by any thread.

1.7 An immutable object never changes state.

1.8 A third technique is to use a thread unsafe class but only as a private field of a class that
is thread-safe. As long as the containing class accesses the unsafe class only in a thread –
safe fashion, and as long as it never lets a reference to the private field leak out into
another object, the class is safe.

1.9 Each separate thread its own separate log so that no resources were shared between the
individual threads.

41. DEADLOCK, THREAD SCHEDULING

308
Deadlock occurs when two threads each need exclusive access to the same set of resources,
but each thread possesses a different subset of those resources.

THREAD SCHEDULING

1. The order in which the threads are executed is called thread scheduling.
2. It is used to schedule the thread one by one without overlapping.
3. If the scheduling is not proper it may lead to errors.

42. EXPLAIN ABOUT THREAD PRIORITIES

3. Each thread has a priority that’s specified as an integer from 1 to 10. When multiple
threads are able to run, generally the VM will run only the highest-priority thread,
though that’s not a hard-and-fast rule.

4. public static final int MIN_PRIORITY = 1;


public static final int MIN_PRIORITY = 5;
public static final int MIN_PRIORITY = 10;

The priority which has 10, 5, 1 will get executed in the order.

Thread PRIORITY is divided into

Preemptive -> Possible to alter the sequence

NonPreemptive -> Not possible to alter the sequence.

43. DEFINE BLOCKING, YIELDING AND SLEEPING

• Blocking occurs any time a thread has to stop and wait for a resource it doesn’t
have.

• The most common way a thread in a network program will voluntarily give up
control of the CPU is by blocking on I/O.

• Threads can also block when they enter a synchronized method or block.

YIELDING
• The second way for a thread to give up control is to explicitly yield.

309
• A thread does this by invoking the static Thread.yield() method
public static void yield()

SLEEPING
• Sleeping is more powerful form of yielding. Whereas yielding indicates only that a
thread is willing to pause and let other equal-priority threads have a turn, a thread that
goes to sleep will pause whether any other thread is ready to run or not.

• Sometimes sleeping is useful even if you don’t need to yield to other threads. Putting
a thread to sleep for a specified period of time lets you write code that executes one
every second, every minute, every ten minutes, and so forth.

Thread.sleep() – used to put the thread in sleep mode.

44. WHAT IS MEANT BY JOINING THREADS ?

It is used to join two threads. After joining threads it can be sequenced one by one

Public final void join(long milliseseconds) throws InterrupteException


Public final void join(long milliseseconds, int nanoseconds) throws InterrupteException

45. WHAT IS THE USE OF THREAD POOLS?

3. Adding multiple threads to a program dynamically improves performance, especially


for I/O – bound programs such as most network programs.

Even if the threads finish quickly, this can overload the garbage collector or other parts of the
VM, and hurt performance

45.1 LIST THE JOBS WHICH ARE INVOLVED IN THREADS.

• It can block on I/O


• It can block on a synchronized object
• It can yield

310
• It can go to sleep
• It can join with an another thread
• It can wait on an object
• It can finish
• It can be preempted y a higher-priority thread
• It can be suspended
• It can stop

46. WHAT IS THE USE OF DNS, IP ADDRESSES?

7. Devices connected to the Internet are called nodes.

8. Nodes that are computers are called hosts.

9. Each node or host is identified by at least one unique 32-bit number called an Internet
address.

10. An IP address is normally written as four bytes of memory, each ranging from 0 to
255.

11. For example 152.255.6.9 is called the dotted quad format.

12. To avoid the complexity of IP address problem, the designers of the Internet invented
the domain Name System (DNS).

47. WHAT IPv6 AND 128-bit Addresses

• The current IP address standard uses 32 bits, which is enough to address more
than four billion computers, almost one for every person on earth.
• A new standard called IPv6 will begin using 16-byte, 128-bit addresses.
• This expands the available address space to 2128 or 1.6043703E32 different
addresses.

IPv6 AND 128-bit Addresses

• The current IP address standard uses 32 bits, which is enough to address more
than four billion computers, almost one for every person on earth.

• A new standard called IPv6 will begin using 16-byte, 128-bit addresses.

311
• This expands the available address space to 2128 or 1.6043703E32 different
addresses.

The InetAddress Class

• The java.net.InetAddress class is Java’s encapsulation of an IP address.

• It is used by most of the other networking classes, including Socket, ServerSocket,


URL, DatagramSocket, DatagramPacket, and more.

Creating New InetAddress Objects

4. public static InetAddress InetAddress.getByname(String hostname) throws


UnknownHostException

5. public static InetAddress[] InetAddress.getAllByname(String hostname) throws


UnknownHostException

6. public static InetAddress InetAddress.getLocalHost() throws UnknownHostException

48. GIVE THE SYNTAX FOR CREATING A NEW URL

The simplest URL constructor just takes an absolute URL in string form as its single
argument:

Public URL(String url) throws MalformedURLException

Try
{

URL u = new URL(http://www.macfaq.com/personal.html);


}

49. LIST THE 5 METHODS OF URL

Read-only access to these parts of a URL is provided by five public methods. They are as
follows:

312
7. getFile()
8. getHost()
9. getPort()
10. getProtocol()
11. getRef() and getAuthority()

8. getProtocol() – method returns a String containing the scheme of the URL. For
example http,https or file.

9. getHost() – method returns a String containing the hostname of the URL.

10. getPort() – method returns the port number specified in the URL as an int. If no port
was specified in the URL, then getport() returns -1 to signify that the URL does not
specify the port explicitly, and will use the default port for the protocol.

11. getFile() – method returns a String that contains the path and file portion of a URL;
remember that java does not break a URL into separate path and file parts.

12. getRef() – method returns the named anchor part of the URL. If the URL does not
have a named anchor, the method returns null.

13. getQuery() – method returns the query of the URL,

14. getAuthority() – Between the scheme and the path of a URL, you will find the
authority. The term authority is taken from the URI specification (RFC 2396), where
this part of the URI indicates the authority that’s resolving the resource.

50. DATAGRAM PACKET & DATAGRAM SOCKET *****

• Data is transmitted across the Internet in packets of finite size called datagrams.
• Data gram is a container for holding the data.
• Each datagram contains a header and payload.

Data gram socket is a mechanism or method for sending or receiving datagram packets.

51. LIST THE SOCKET BASIC STEPS

• A socket is a connection between two hosts. It can perform 7 basic operations:

8. Connect to a remote machine

313
9. Send data
10. Receive data
11. Close a connection
12. Bind a port
13. Listen for incoming data
14. Accept connections from remote machine on the bound port

52. WHAT IS A PORT?

• Each and every socket is bind with a port only.


• Port is a communication device between 2 different sockets.
• Data is always transmitted via ports only.
• Ports are always specified as integer values from 0 to 65,535.

53. LIST THE VARIOUS CONSTRUCTERS USED FOR CREATING SOCKETS

5. public Socket(String host, int port) throws UnknownHostException, IOException

Creates a TCP socket to the specified port on the specified host and attempts to
connect to the remote host.

6. public Socket(InetAddress host, int port) throws IOException

This constructor creates a TCP socket to the specified port on the specified
host and tries to connect. It differs by using an InetAddress object.

7. public Socket(String host, int port, InetAddress interface, int localPort) throws
IOException

This constructor creates a socket to the specified port on the specified host and
tries to connect. It connects to the host and port specified in the first two arguments.

8. public Socket(InetAddress host, int port, InetAddress interface, int localPort) throws
IOException

54. WHAT IS FINGER?

• Finger is a straightforward protocol described in RFC 1288.

314
• The client makes a TCP connection to the server on port 79 and sends a one line
query.

• The server responds to the query and closes the connection.

• The format of the query precisely, defied, the format of the response somewhat less
so.

• The data transferred is pure printable and ASCII text.

55. WHAT IS WHOIS?

• Whois is a simple directory service protocol defined in RFC 954.

• It was originally designed to keep track of administrators responsible for Internet


hosts and domains.

• A whois client connects to one of several central servers and requests directory
information for a person or persons; it can usually give you a phone number, and
email address, and a U.S. mail address (not necessarily current ones though).

THE STRUCTURE OF SHOIS PROTOCOL

The client opens a TCP socket to port 43 on the server whois.internic.net.

When you are using whois, you almost always connect to this server; there are a few
other servers, but these are relatively rare.

But there is a separate whois server for the U.S. department of Defencse.

4. The client sends a search string terminated by a carriage return/linefeed pair (/r/n).
You can also search for domain names, like oreilly.com or netscape.com, which give
you information about a network.

5. The server sends an unspecified amount of human-readable information in response


to the command and closes the connection.

6. The client displays this information to the user.

56. WHAT YOU MEAN BY FULL-FLEDGED HTTP SERVERS?

5. HTTP is a large protocol.

315
6. A full featured HTTP server must respond to requests for files, convert URLs into
file-names on the local system.

7. It also respond to POST and GET requests, handle requests for files that don’t
exist, interpret MIME types, launch CGI programs.

8. Our investigation of HTTP servers begins with a server that always sends out the
same file, no matter who or what the request.

A FULL-FLEDGED HTTP SERVER

3. HTTP server can serve an entire document tree, including images, applets, HTML
files, and more.

4. This server is called full fledged server.

57. WHAT IS THE USE OF SECURE SOCKET LAYER (SSL)?

4. Confidential communication through an open channel such as the public Internet that
nonetheless resists eavesdropping absolutely requires that the data be encrypted.

5. In traditional secret key (or symmetric) encryption, the same key is used both to encrypt
and decrypt the data.

6. In public key (or asymmetric) encryption, different keys are used to encrypt and decrypt
the data. One key, called the public key, is used to encrypt the data. This key can be
given to anyone.

58. WHAT IS THE USE OF SESSION MANAGEMENT?

• SSL is most commonly used on web servers.


• Web connections tend to be transitory(fleeting or temporary)
• Using JSSE, you don’t need to do anything extra to take advantage of sessions.
• Using session, various information can be retrieved.

7. public byte[] getId()


8. public SSLSessionContext getSessionContext()
9. public long getCreateation()
10. public long getLastAccessdTime()
11. public void invalidate()

316
12. public void removeValue(String name)

59. WHAT IS THE USE OF UDP PROTOCOL?

• UDP – User Datagram protocol is an alternative protocol for sending data over IP that
is very quick, but not reliable.

• That is, when you send UDP data, you have no way of knowing whether it arrived,
much less whether different pieces of data arrived in the order in which you sent
them.

• It is connectionless type of protocol.

60. DIFFERENCIATE CONNECTION-ORIENTED AND CONNECTION LESS


PROTOCOL.

Connection oriented protocol Connection less protocol


Client has to establish a connection to Establishing connection is not needed
another client or server
Once the connection is established, then data Data transfer takes place regardless of
transfer takes place. connection.
At the end of data transfer client should Not applicable.
disconnect the connection.

61. WHAT DO YOU MEAN BY UNICAST SOCKETS?

• Unicast socket provides point-to-point communication.

• Unicast sockets create a connection with two well-defined endpoints.

• There is one sender and one receiver, and although they may switch roles, at any
given time it is easy to tell which is which.

62. WHAT IS THE USE OF MULTICAST SOCKETS?

• Multicasting sends data from one host to many different hosts, but not to everyone.

317
• The data goes only to clients that have expressed an interest in the data by joining a
particular multicast group.

• Protocols require broadcasts only when there is no alternative, and routers limit
broadcast to the local network or subnet, preventing broadcasts from reaching the
Internet at large.

• Multicast is useful during Real Audio, Video broadcasting.

63. WHAT IS DOINPUT & DOOUTPUT?

• Most URLConnection objects provide input to a client program.

• Fox example, a connection to a web server with the GET method would produce
input for the client, but a connection to a web server with the POST method might
not.

DOOUTPUT

• Programs can use a URLConnection to send output back to the server. For example,
a program that needs to send data to the server using the POST method could do so
by getting an output stream from URLConnection.

• useCaches - The useCaches variable determines whether a cache will be used if it is


available. The default value is true, meaning that the cache will be used; false means
the cache won’t be used.

64. DEFINE CONTENT, PROTOCOL HANDLERS

• The URLConnection class is intimately tied to Java’s protocol and content handler
mechanism.

• The protocol handler is responsible for making connections, exchanging headers,


requesting particular documents, and so fourth.

• Protocol handler is used to identify what type of protocol is used in network.

• Content handler is used to identify what type of content is to be received i.e.


picture/text/ASCII type.

318
• Based on the type of the content type responsible protocol is allocated by the protocol
handler.

65. DEFINE RMI (important)

RMI – Remote Method of Invocation is the method of creating an object in one machine
and accessing it in some other machine.
RMI allows the user to call an object remotely.
Since Java is platform independent language RMI can be implemented in Java very well.

66. CONTENT HANDLER FACTORY

The URLConnection class contains a static Hashtable of ContentHandler objects. Whenever


the getContent() method of URLConnection is invoked, java looks in this Hashtable to find
the right content handler for the current URL, as indicated by the URL’s content type. This is
referred as
Content Factory.

END OF UNIT II

319
UNIT III – SCRIPTING LANGUAGES

66. WHAT IS DOMAIN & MENTION DIFFERENT TYPES OF DOMAINS

Domain is a place where information is available.

DOMAIN NAME EXTENSION

.edu – Servers that provide Educational services

.gov – About the government of a country.

.mil – Servers that provide military information.

.org – Provide information about the organizations in the world.

.com – Servers providing commercial services on the Internet.

67. WRITE THE FORMAT OF HTML PROGRAM

<HTML>
<HEAD>
<TITLE> This is the Title </TITLE>
</HEAD>

<BODY>

…. Type the body of the program

</BODY>
</HTML>

Note: All the tags in HTML program are optional, however the file should be saved in .html
extension.

68. MENTION SOME TEXT FORMATTING TAGS

1. <p> </p> - is used for introducing various paragraphs.


5. <br> - this tag is used for giving an empty blank line.

320
6. HEADING TAGS - <h1> </h1> .. <h6> </h6> is used to introduce various headings.
<h1> is the biggest and h6 is the smallest heading tag.
7. <HR> TAG – is used to draw lines and horizontal rules.
8. <B>,<I>,<U> for bold, italic and underline respectively.

69. EXPLAIN ABOUT LIST TAG.

TYPES OF LISTS

1. Unordered lists
2. Ordered lists

UNORDERED LISTS

It starts with <ul> and ends with </ul>

Attributes of Unordered lists

TYPE:

TYPE = FILLROUND or TYPE = SQUARE

EXAMPLE

<UL TYPE = FILLGROUND>


<LI> CSE </LI>
<LI> IT </LI>
</UL>
ORDERED LISTS (NUMBERING>

TYPE: Controls the numbering scheme to be used

TYPE = “1” will give counting numbers (1,2,…>


“A” will give A,B,C..
“a” will give a,b,c
“I” starts with Capital roman letters I,II,II…
“I” starts with small case roman letters

START: Alters the numbering sequence, can be set to any numeric value

VALUE: Change the numbering sequence in the middle of an ordered list

321
EXAMPLE
<OL TYPE = “1” START = 5>
<LI> CSE </LI>
<LI> IT </LI>
</OL>
OUTPUT

5 CSE
6 IT

70. EXPLAIN THE ATTRIBUTES OF TABLE TAG WITH AN EXAMPLE

A table is a two dimensional matrix, consisting of rows and columns. All table related tags
are included between <TABLE> </TABLE> tags.

<TABLE>
<TH> Heading </TH>
<TR> Row elements </TR>
<TD> Table data values </TD>
</TABLE>
ATTRIBUTES OF TABLE TAG

ALIGN Horizontal alignment is controlled by the ALIGN attribute. It can be set


to LEFT, CENTER, or RIGHT
VALIGN Controls the vertical alignment of cell contents. It accepts the values TOP,
MIDDLE or BOTTOM
WIDTH Sets the WIDTH of a specific number of pixels or to a percentage of the
available screen width.
BORDER Controls the border to be placed around the table.
CELLPADING This attribute controls the distance between the data in a cell and the
boundaries of the cell
CELLSPACING Controls the spacing between adjacent cells
COLSPAN Used to spilt the single cell to one or more columns
ROWSPAN Used to spilt the single cell to one or more rows.

EXAMPLE
<TABLE BORDER = 3 WIDTH = 100 HEIGHT = 200>
<TR>
<TH> Roll Number </TH>
<TH> Age </TH>
<TR>
<TR> <TD> 1 </TD> <TD 35 </TD> </TR>
</TABLE>

322
8. ALIGN: ALIGN = TOP, MIDDLE,BOTTOM
9. BORDER: Specifies the size of the border to place around
the image.
10. WIDTH: Specifies the width of the image in pixels.
11. HEIGHT: Specifies the height of the image in pixels
12. HSPACE: Indicates the amount of space to the left and
right of the image
13. VSPACE: Indicates the amount of apace to the top and
bottom of the image.

71. WHAT DO YOU MEAN BY COLUMN SPANNING AND ROW SPANNING?


Row spanning is used to merge (combine) two or more rows.
Column spanning is used to merge (combine) two or more columns.

72. MENTION THE DIFFERENT TYPES OF LINKS

HTML allows linking to other HTML documents as well as images. There are 3 attributes
that can be introduced in BODY tag.

4. LINK – Changes the default color of a Hyperlink to


whatever color is specified with this tag.

5. ALINK – Changes the default color of a hyperlink that is


activated to whatever color is specified with this tag.

6. VLINK – Changes the default color of a hyperlink that is


already visited to whatever color is specified with this tag.

NOTE: User can specify the color name of a hyperlink or an


equivalent hexadecimal number.

EXTERNAL LINKS

SYNTAX

<A HREF = “location name”> Hyper Text Message </A>

323
73. EXPLAIN IMAGE MAPS WITH ITS SYNTAX

When a hyperlink is created on an image, clicking on any part of the image will lead to
opening of the document specified in the <A HREF TAG>.

Linked regions of an image map are called hot regions and each hot region is associated with
a filename.html.

Syntax

<MAP NAME = “map name”>

ATTRIBUTES OF IMAGE MAPS

4. COORDS: Each of the above shapes takes different coordinates as parameters.


a. Rectangle – 4 coordinates (x1,y2,x3,y2)
5. POLYGON: 3 or more coordinates.

6. HREF – Takes the name of the .html file that s linked to the particular area on the
image.

<MAP NAME = “fish.jpg”>


<AREA SHAPE = “rect” COORDS = “52,65,122,89” HREF = “sct.html”>
</MAP>

75. EXPLAIN ABOUT HTML FORM TAG WITH ITS ATTRIBUTES.

HTML form provides several mechanisms to collect information from people viewing your
site. The syntax of the form is

<FORM METHOD = “POST” ACTION = “/cgi-bin/formail”>

• The METHOD attribute indicates the way the web server will
organize and send you the form output.

• Use METHOD = “post” in a form that causes changes to server


data, for example when updating a database.

• The ACTION attribute in the FORM tag is the path to this script;
in this case, it is a common script which emails form data to an
address. Most Internet Service Providers will have a script like
this on their site.

324
76.MENTION THE VARIOUS FORM ELEMENTS.
Various elements or controls can be created in FORM using <INPUT> tag. They are
1. Label 2. Text box 3. Text Area 4. Radio button
5. Check box 6. List box 7. Command button 8. Scroll bars

77. WHAT IS THE USE OF FRAMES IN HTML GIVE THE SYNTAX OF FRAMES

Frames are used to call many html files at the same time. This can be done using
<FRAMESET> </FRAMESET> tags.

ATTRIBUTES OF FRAMES

ROWS – This attribute is used to divide the screen into multiple rows. It can be set equal to
a list of values. Depending on the required size of each row. The values can

• A number of pixels
• Expressed as a percentage of the screen resolution
• The symbol *, which indicates the remaining space.

COLS – This attribute is used to divide the screen into multiple columns.

EXAMPLE

<FRAMESET ROWS = “30%,*”> => Divides the screen into 2 rows,


* occupying the remaining space
<FRAMESET COLS = “50%,50%”> => Divides the first row into 2 equal
columns
<FRAME SRC = “file1.html”>
<FRAME SRC = “file2.html”>

<FRAMESET COLS = “50%,50%”> => Divides the second


row into 2 equal columns

<FRAME SRC = file3.html”>


<FRAME SRC = file4.html”>
</FRAMESET>
</FRAMESET>

325
78. MENTION THE TYPES OF SCRIPTING LANGUAGES

• JavaScript is a Scripting language (web site development environment) created by


Netscape.

• Hence JavaScript works best with the Netscape suite of Client and Server products.

• JavaScript is the native scripting language of Netscape Navigator.

• VBScript is the native Scripting language of HTML.

SERVER SIDE SCRIPTING

• In Server side scripting the script program is executed at Server Side the required
html program is sent to the client.

• The job of the server is more in server side scripting

CLIENT SIDE SCRIPTING


• Here the script program is processed and executed in the client side itself.

• So that it reduces the burden of the server.

79. LIST THE ADVANTAGES OF JAVA SCRIPT

3. JavaScript is an object-oriented language that allows creation of interactive Web


pages

4. JavaScript allows user entries, which are loaded into an HTML form to be processed
as required

ADVANTAGES

11. It is an interpreted language, which requires no compilation steps.


12. Embedded within HTML.
13. Minimal Syntax – easy to learn
14. Quick Development
15. Designed for simple, small programs
16. High performance
17. Procedural Capabilities – support facilities such as condition checking, looping and
branching.

326
18. Designed for programming user events – like VB Java Script is also based on Events.
19. Easy Debugging and Testing
20. Platform Independence/ Architecture Neutral

SYNTAX OF JAVASCRIPT PROGRAM

<HTML>
<HEAD>
<SCRIPT language = “JavaScript”>

… body of the script program


</SCRIPT>
</HEAD>

<BODY>
<SCRIPT language = “JavaScript”>

body of the program.


</SCRIPT>
</BODY>
</HTML>

80. WHAT IS DENSE ARRAYS?

• A dense array is an array that has been created with each of its elements being
assigned a specific value.

• Dense arrays are used exactly in the same manner as other arrays.

• Dense arrays are declared and initialized at the same time.

Array Methods

Join() – returns all elements of the array joined together as a single string.

Reverse() – reverses the order of the elements in the array.

81. LIST COMPARISION OPERATORS & STRING OPERATORS IN JAVA

• = = equal (perform type conversion before testing for equality.

327
• = = = strictly equal (do not perform type conversion before testing for equality

STRING OPERATIRS

Currently Java Script supports only one string concatenation (+) operator.

EXAMPLE
“ab” + “cd” produces “abcd”

82. LIST THE VARIOUS DIALOG BOXES IN JAVA SCRIPT


Dialog boxes are used to display small windows. This is also used to get input from user.

SYNTAX
alert(“message”);
alert(“Click here to continue”)
prompt(“Enter your name”, name)

4. Alert is only used to display some information


5. Prompt is used to display information along with some input value
6. Confirm dialog box, causes program execution to halt until user action takes place.
The user action can be either OK or CANCEL.
OK – returns true
CANCEL – returns false

83. MENTION THE VARIOUS JAVA SCRIPT OBJECT MODELS.


• Math Object
• String Object
• Date Object
• Boolean and Number Object
• Document Object
• Window Object

84. HOW SCRIPTING LANGUAGE IS DIFFERS FROM HTML.

• HTML is used for simple web page design


• HTML with FORM is used for both form design and Reading input values
from user.

328
• Scripting Language is used for Validating the given input values weather it is
correct or not, if the input value is incorrect, the user can pass an error
message to the user.
• Using form concept various controls like Text box, Radio Button, Command
Button, Text Area control and List box can be created.

85. DEFINE FUNCTION IN JAVA SCRIPT.

Function is a part of a program or in other words function is a module in java


program which can be called or invoked any number of times from the main
program.

Function can be called any number of times but it can accept any input values or
parameters, however it can return only one output at a time.

END OF UNIT III

329
UNIT – IV & V: DYNAMIC HTML, SERVLETS

86. DEFINE CSS – CASCADING STYLE SHEET

• DHTML is a new and emerging technology that has evolved to meet the increasing
demand for eye-catching and mind-catching web sites.
• DHTML combines HTML with Cascading Style Sheets (CSS) and Scripting
Languages. HTML specifies a web page’s elements like table, frame, paragraph,
bulleted list, etc. CSS can be used to determine an element’s size, color, position and a
number of other features.
• Scripting Languages (JavaScript and VBScript) can be used to manipulate the web
page’s elements so that styles assigned to them can change in response to a user’s input.

87. DEFINE CASDING STYLE SHEETS (CSS)

• CSS are powerful mechanism for adding styles (e.g. Fonts, Colors, Spacing) to web
documents.
• They enforce standards and uniformity throughout a web site and provide numerous
attributes to create dynamic effects.
• The advantage of a style sheet includes the ability to make global changes to all
documents from a single location. Style sheets are said to cascade when they combine
to specify the appearance of a page.
The style assignment process is accomplished with the <STYLE>…</STYLE>
tags.

87. MENTION THE TYPES OF STYLE SHEETS

87.1 Embedded or Internal Style sheet


87.2 External or Linked Style sheet
87.3 Inline style sheet

330
88. LIST THE DIFFERENCE BETWEEN STYLE SHEETS

Slno ‘Embedded Linked Inline Style Sheet

1 Style program is Style program alone is stored in a Different from


embedded with in the separate file with an extension of Embedded and
HTML program itself. .css file. Linked CSS
2 Explicit LINK statement Explicit LINK REL statement is Not required
is not needed. needed to connect with .CSS file
3 Styles can be used within Styles used in .CSS file can be Styles created should
the program only, it can used in any HTML program be used immediately
not be called some other before creating
files. another new style.

89. LIST THE PROPERTIES OF STYLE TAG

<STYLE> tag properties are divided in to 6 categories. They are

1. Font Attributes
2. Color and Background attributes
3. Text Attributes
4. Border Attributes
5. Margin Attributes and
6. List Attributes.
90. HOW TO INTRODUCE STYLE IN HTML PROGRAM?

<HTML>
<HEAD>
<STYLE Type = “text/css”>

predefined tag name {attribute name1:attribute value1; attribute name2:attribute


value2; ……attribute name-n:attribute value-n}

<STYLE>
</HEAD>
<BODY>

331
write the body of program
</BODY> </HTML>

91. WHAT DO YOU MEANT BY OBJECT MODEL AND COLLECTION?

• The object model allows web authors to control the presentation of their pages and
gives them access to all the elements on their web page.

• The whole web page – elements, forms, frames, tables, etc – is represented in an
object hierarchy.

• Using scripting, an author is able to retrieve and modify any properties or attributes of
the web page dynamically.

92. LIST THE TWO DATE OBJECTS

UTC – Coordinated Universal Time


GMT – Greenwich Mean Time

93. WHAT ARE COOKIES ?

Cookies provide web developers with a tool for personalizing web pages.

A cookie is a piece of data that is stored on the user’s computer to maintain information about
the client during and between browser sessions.

94. WHAT DO YOU MEAN BY OBJECT REFERENCING?

• The simplest way to reference an element is by using the element’s id attribute.

• The element is represented as an object, and its various XHTML attributes become
properties that ca be manipulated by scripting.

95. DEFINE Data Binding.

• With data binding, data need to longer reside exclusively on the server.

• Data can be maintained on the client, in a manner that distinguishes it from the
XHTML markup on the page.

332
• Typically, data is sent to the client. All subsequent manipulations than take place on
the data directly on the client, thus eliminating server activity and network delays.
• Once it is available on the client, the data can be sorted and filtered in various ways.

• In data binding technology, data made on the client do not propagate(spread,


broadcast) back to the server.

• Once it is available on the client, the data can be sorted and filtered in various ways.

• To bind external data to XHTML elements, Internet Explorer employs software


capable of connecting the browser to live data sources. These are known as Data
Source Objects (DSOs).

• The most popular DSO is – the Tabular Data Control (TDC).

96. WHAT DO YOU MEAN BY RECORDSET?


A recordset is simply a set of data or rows to be accessed by the program. It contains the
following recordset object methods.

5. MoveNext – used to move the recordset to the next row.


6. MovePrevious – used to move the recordset to the previous row.
7. MoveFirst – used to move the recordset to the first record immediately.
8. MoveLast – used to move the recordset to the last record immediately.

Note move previous and move next methods should be used before checking BOF(),
EOF() methods respectively.

97. WHAT IS EVENT MODEL LIST SOME DHTML EVENTS.


When the program is executed based on a particular event occurrence, it is referred as Event
modeling. The DHTML events are described below:
Event Description

Onbeforecut Fires before a selection is cut to the clipboard


Onbeforecopy Fires before a selection is copy to the clipboard
Onbeforepaste Fires before a selection is paste to the clipboard

Onbeforeupdate Fires before a data source is updated


Onafterupdate Fires after a data source is updated

onrowenter,onrowexit, Related to rows, executed when you enter into row, exit,
onrowsdelete,onrowsinserted delete and insert respectively.

onhelp, onkeydown, Fires help, keydown and keyup respectively

333
onkeyup
ondbclick, ondrag, ondrop Fires when double click, drag or drop event is occurred.
Onchange Fires when a new change occured

98. WHAT DO YOU MEAN BY FILTERS AND TRANSITIONS (Changeover, conversion,


shift) IN DHTML?

• Filters and transitions are specified with the CSS filter property.

• Applying filters to text and images causes changes that are persistent.

• Transitions are temporary: applying a transition allows you to transfer from one page
to another with a pleasant visual effect, such as a random dissolve.

• Filters and transitions do not add content to your pages – rather, they present existing
content in an engaging manner to capture the user’s attention.

• Each of the visual effects achievable with filters and transitions if programmable, so
these effects can be adjusted dynamically by programs that respond to user-initiated
events, such as mouse clicks and keystrokes.

99. EXPLAIN ABOUT FLIP FILTERS – (FLIPv AND FLIPh ) PROPERTIES.

• The flipv and fliph filters mirror text or images vertically and horizontally.

<!-- EVENT MODEL FOR ONCLICK - FILTERS1.HTML


<!------------------------------------------>
<?xml version = "1.0"?>
<!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">


<head>
<title> THE FLIP FILTER - FILTERS1.HTML </title>
<style type = "text/css">
body { background-color: cyan } table { font-size: 3em; font-family:arial,
sans-serif; background-color:pink; border-style: ridge}
td { border-style: groove; padding: lex }
</style
</head>
<body>

334
<table>
<tr>

<!-- Filters are applied in style declarations ---->


<! ------------------------------------------------>
<td style = "filter: fliph"> Text </td>

<td> Text
</tr>

<!-- More than one filter can be applied at once---->


<! ------------------------------------------------>
<tr>
<td style = "filter: flipv fliph"> Text </td>
<td style = "filter: flipv"> Text </td>
</tr>

</table>

</body>
</html>

OUTPUT

fliph filter applied

filpv filter applied

Both

335
100. WHAT IS THE USE OF XML?

• Extensible Markup Language, derived from SGML (Standard Generalized


Markup Language.

• XML is widely supported open technology (i.e. non-proprietary) for electronic


data exchange and storage.

• XML is actually a language used to create other markup languages to describe


data in a structured manner.

• XML documents contain only data, not formatting instructions, so


applications that process XML documents must decide how to manipulate or
display the document’s data.

101. WHAT DO YOU MEAN BY DTD IN XML?

• DTD means Document Type Definition.

• DTD file is similar to CSS file, because DTD also contains only styles.

• DTD contains various styles which are to be applied in XML document.

• Like .CSS file .DTD file also should be linked with XML program.

• Styles in XML program should be save with .xsl (Xml Style Sheet Language)
extension.

102. WHAT IS THE USE OF XML NAMESPACE?

• XML allows document authors to create custom elements.

• This extensibility can result in naming collisions (i.e. different elements that have
the same name) among elements in an XML document.

• An XML namespace is a collection of element and attribute names. Each


namespace has a unique name that provides a means for document authors to
unambiguously refer to elements with the same name (i.e. prevent collisions).

336
103. WHAT ARE THE USES OF XML?

• CML – Chemical Markup Language – for chemical equations

• MML - Mathematical Markup Language – for Mathematical equations and


derivations.

• Used in bio medical line.

104. What is SOAP? (Simple Object Access Protocol)

• SOAP is an XML based protocol that allows applications to easily over the
internet using XML documents called AOAP message.

• A SOAP message contains an envelope, which is a structure that describes a


method call.

• A SOAP message’s body contains either a request or a response.

• A request message’s body contains a Remote Procedure Call (RPC), which is a


request for another machine to perform task.

• The RPC specifies the method to be invoked and any parameters the method
takes.

• The application sends the SOAP message via an HTTP POST. A SOAP response
message is an HTTP response document that contains the results from the
methods call (e.g. return values, error messages.)

105. WHAT IS THE USE OF WEB SERVICES?

• Web services encompass a set of related standards that can enable two computer
applications to communicate and exchange data over the Internet.

337
• The data is passed back and forth using standard protocols such as HTTP, the same
protocol used to transfer ordinary web pages.

• Web services operate using open, text-based standards that enable components written
in different languages and on different platforms to communicate.

• They are ready to use pieces of software on the Internet. XML, SOAP, Web Services
Description Language (WSDL) and Universal Description, Discovery and Integration
(UDDI) are the standards on which web services rely.

• UDDI is another XML based format that enables developers and business to publish
and locate Web services on a network.

106. LIST AND THE FUNCTIONS OF THREE-TIER APPLICATIONS.

• 107.1 The client tier, or top tier, is the application’s user interface. Users interact
directly with the application through the client tier, which is typically a Web browser,
keyboard and mouse.

• 107.2 The Middle tier implements business logic and presentation logic to control
interactions between application clients and application data.

• 107.3 Business logic in the middle tier enforces business rules and ensures that data
is reliable before updating the database to presenting data to a user.

107. WHAT IS IIS?

• IIS – Microsoft Internet Information Services is an enterprise-level web server


that is included with several versions of Windows.

• Installing IIS on a machine allows that computer to serve documents

108. WHAT IS MYSQL?

• MYSQL is a multi-user, multithreaded (i.e. allows multiple simultaneous


connection).

• RDBMS server that uses SQL to interact with and manipulate data.

338
• Implementations of MYSQL are available for Windows, Mac OX X, Linux and
UNIX.

• The ability to access table from different databases y using a single query,
increasing the efficiency of retrieving accurate and necessary information.

• MYSQL provides the ability to handle large databases (e.g. ten of thousands of
tables with millions of rows.

109. WHAT IS THE USE OF PERL DATABASE INTERFACE.

• The Perl Database Interface (DBI) enables users to access relational databases
from Perl programs.

• Database vendors create drivers that can receive interactions through DBI and
process them in a database specific manner.

• DBI is the most widely used interface available for database connectivity in Perl.

339
PART B – QUESTIONS
BOOK NAME: Java Network Programming study all the points from notes
also)
1. *** Why Java is essential in Network programming? (page 2 13 – 8 marks)

2. With a neat diagram explain the layers of IP network (only 4 layers) (page 22 – 28 – 8
marks).

3. Explain the various types of Client/Server Models (Study from notes – 8 marks)

4. Write short notes on the following (PG NO. 50 – 62 - 16 marks)


URI
URN
URL
HTML
SGML
XML

5. ****Write short notes on MIME & CGI 70 (pg no. 63 – 70 – 8 marks)

6. Write short notes on applets and Security (page no. 71 – 74 – 8 marks)

7. Write short notes on different types of Stream(Input/Output/Filter/buffered/Print


Stream classes – 76 – 109 - ** Write one example program involving 5 to 6 stream
classes)

8. **** Explain in detail about Thread & Multi thread concept with example
program(117 onwards with an example program)

9. ***Explain the various types of Address format. (page no. 167 – Write detail about
address A, B, C, D and E in detail)

340
10. ***Explain in detail about retrieving data using URL connection (page 193)

• Explain URL connection concept


• Explain all the methods in URL like getConnection, getContent etc
• Explain Lab URL program without fail.

11. ***Explain Client/Server Socket Programming in detail (page no 301 onwards – 8


marks)

• Write the any socket program in Lab exercise without fail compulsory.

12. ***Write short notes Protocol Handlers and Content Handlers in detail with a small
program (page no 529 – 581 – 16 marks)

13. *** With a neat diagram explain the concept of RMI (Study from Java complete
reference book with diagram and write LAB exercise also without fail – 16 marks)

REFERENCE BOOK: INTERNET & WORLD WIDE WEB


HOW TO PROGRAM – THIRD EDITION – DEITEL & DEITEL

14. Discuss the various HTML tags in detail (16 marks – refer notes)

15. ** Write short notes on the following (165 marks - refer notes)
IMG tag
TABLE tag
FRAME tag

16. ** With a neat diagram write a SCRIPT PROGRAM with validation for the following
(each program carries 16 marks)

Student Mark List


Inventory System
Employee Pay Slip generation
Railway Ticket Reservation
Online Quiz program

NOTE Answer should be in the following format only.

341
1. Draw form design

2. Design must have one Primary key field – always


check for duplication for the primary key field

3. emp- name, product- name, dept-name etc should not


be blank
Write a function for all these validation

4. When you introduce any number field, always check it


is negative or not, if it so do not accept the input value

5. For calculations always use program concept, do not


ask the user to enter total, gross etc.

6. Instead through program calculate

Gross.value = val(basic.value + hra.value+da.value)

7. Always use val or ParseInt function when you perform


calculation with numbers.

8. for avoiding too much of validation better use the


following in the design itself

• Radio button
• Command button
• Check box
• List box

9. Must introduce SUBMIT & RESET button at the end


of the design

17. *** Explain in detail about all the types of Cascading Style sheet with an example
program(16 marks – page no. 140 -149)

draw the form design


Mention the 3 types of CSS
Write example program for each type
Write the differences and advantages of each CSS

342
18. ***Write short notes on the following.(16 marks – page no. 174 - 221)

Write short notes on Java Script/Advantages of Scripting


Java Script control statements
Java Script functions

19. ** Discuss briefly about HTML – Object Model and Collections (Page no 429 – 438)
** Study from notes also

Object modeling
Object Referencing
Dynamic Styles
Dynamic Positioning

20. *** Discuss briefly Dynamic HTML – Event Model (page mp 451 – 471 refer notes
also)

Short notes on event model


Printing all the tags using program
Explain Event bubbling with an example program

21. **** Discuss briefly about Dynamic HTML – Filters and Transitions (page no. 476 –
495 refer notes also)

Explain filters and transitions with example


Write program using flipv and fliph attribute with output
diagram.
List all the possible events given in the notes.

22. *** Discuss briefly about Data Binding using any control for example

• binding with table


• binding with an image
• sorting table data.

343
23. ** Discuss briefly the various servers (refer V th unit notes)

24. ****Discuss briefly about Handling of Multimedia database (very important


question) (page 985 - 1023)

25. *** Explain handing of ACTIVEX CONTROL.

26. ** Explain the concept of Servlets with an example program ( Lab exercise)

27. Explain about JSP with example program.

28. Explain about JDBC structure with example program.

THE STRUCTURE OF SHOIS PROTOCOL

The client opens a TCP socket to port 43 on the server whois.internic.net.

When you are using whois, you almost always connect to this server; there are a few
other servers, but these are relatively rare.

But there is a separate whois server for the U.S. department of Defencse.

7. The client sends a search string terminated by a carriage return/linefeed pair (/r/n).
You can also search for domain names, like oreilly.com or netscape.com, which give
you information about a network.

8. The server sends an unspecified amount of human-readable information in response


to the command and closes the connection.

9. The client displays this information to the user.

56. WHAT YOU MEAN BY FULL-FLEDGED HTTP SERVERS?

9. HTTP is a large protocol.

344
10. A full featured HTTP server must respond to requests for files, convert URLs into
file-names on the local system.

11. It also respond to POST and GET requests, handle requests for files that don’t
exist, interpret MIME types, launch CGI programs.

12. Our investigation of HTTP servers begins with a server that always sends out the
same file, no matter who or what the request.

A FULL-FLEDGED HTTP SERVER

5. HTTP server can serve an entire document tree, including images, applets, HTML
files, and more.

6. This server is called full fledged server.

57. WHAT IS THE USE OF SECURE SOCKET LAYER (SSL)?

7. Confidential communication through an open channel such as the public Internet that
nonetheless resists eavesdropping absolutely requires that the data be encrypted.

8. In traditional secret key (or symmetric) encryption, the same key is used both to encrypt
and decrypt the data.

9. In public key (or asymmetric) encryption, different keys are used to encrypt and decrypt
the data. One key, called the public key, is used to encrypt the data. This key can be
given to anyone.

58. WHAT IS THE USE OF SESSION MANAGEMENT?

• SSL is most commonly used on web servers.


• Web connections tend to be transitory(fleeting or temporary)
• Using JSSE, you don’t need to do anything extra to take advantage of sessions.
• Using session, various information can be retrieved.

13. public byte[] getId()


14. public SSLSessionContext getSessionContext()
15. public long getCreateation()
16. public long getLastAccessdTime()
17. public void invalidate()

345
18. public void removeValue(String name)

59. WHAT IS THE USE OF UDP PROTOCOL?

• UDP – User Datagram protocol is an alternative protocol for sending data over IP that
is very quick, but not reliable.

• That is, when you send UDP data, you have no way of knowing whether it arrived,
much less whether different pieces of data arrived in the order in which you sent
them.

• It is connectionless type of protocol.

61. DIFFERENCIATE CONNECTION-ORIENTED AND CONNECTION LESS


PROTOCOL.
Connection oriented protocol Connection less protocol
Client has to establish a connection to Establishing connection is not needed
another client or server
Once the connection is established, then data Data transfer takes place regardless of
transfer takes place. connection.
At the end of data transfer client should Not applicable.
disconnect the connection.

61. WHAT DO YOU MEAN BY UNICAST SOCKETS?


• Unicast socket provides point-to-point communication.

• Unicast sockets create a connection with two well-defined endpoints.

• There is one sender and one receiver, and although they may switch roles, at any
given time it is easy to tell which is which.

62. WHAT IS THE USE OF MULTICAST SOCKETS?


• Multicasting sends data from one host to many different hosts, but not to everyone.

• The data goes only to clients that have expressed an interest in the data by joining a
particular multicast group.

• Protocols require broadcasts only when there is no alternative, and routers limit
broadcast to the local network or subnet, preventing broadcasts from reaching the
Internet at large.

346
• Multicast is useful during Real Audio, Video broadcasting.

63. WHAT IS DOINPUT & DOOUTPUT?

• Most URLConnection objects provide input to a client program.

• Fox example, a connection to a web server with the GET method would produce
input for the client, but a connection to a web server with the POST method might
not.

DOOUTPUT
• Programs can use a URLConnection to send output back to the server. For example,
a program that needs to send data to the server using the POST method could do so
by getting an output stream from URLConnection.

• useCaches - The useCaches variable determines whether a cache will be used if it is


available. The default value is true, meaning that the cache will be used; false means
the cache won’t be used.

64. DEFINE CONTENT, PROTOCOL HANDLERS

• The URLConnection class is intimately tied to Java’s protocol and content handler
mechanism.

• The protocol handler is responsible for making connections, exchanging headers,


requesting particular documents, and so fourth.

• Protocol handler is used to identify what type of protocol is used in network.

• Content handler is used to identify what type of content is to be received i.e.


picture/text/ASCII type.

• Based on the type of the content type responsible protocol is allocated by the protocol
handler.

66. DEFINE RMI (important)

RMI – Remote Method of Invocation is the method of creating an object in one machine
and accessing it in some other machine.

347
RMI allows the user to call an object remotely.

Since Java is platform independent language RMI can be implemented in Java very well.

66. CONTENT HANDLER FACTORY

The URLConnection class contains a static Hashtable of ContentHandler objects. Whenever


the getContent() method of URLConnection is invoked, java looks in this Hashtable to find
the right content handler for the current URL, as indicated by the URL’s content type. This is
referred as Content Factory.

END OF UNIT II
UNIT III – SCRIPTING LANGUAGES

66. WHAT IS DOMAIN & MENTION DIFFERENT TYPES OF DOMAINS

Domain is a place where information is available.

DOMAIN NAME EXTENSION

.edu – Servers that provide Educational services

.gov – About the government of a country.

.mil – Servers that provide military information.

.org – Provide information about the organizations in the world.

.com – Servers providing commercial services on the Internet.

67. WRITE THE FORMAT OF HTML PROGRAM

<HTML>
<HEAD>
<TITLE> This is the Title </TITLE>
</HEAD>

<BODY>

…. Type the body of the program

348
</BODY>
</HTML>

Note: All the tags in HTML program are optional, however the file should be saved in .html
extension.

68. MENTION SOME TEXT FORMATTING TAGS

1. <p> </p> - is used for introducing various paragraphs.


9. <br> - this tag is used for giving an empty blank line.
10. HEADING TAGS - <h1> </h1> .. <h6> </h6> is used to introduce various headings.
<h1> is the biggest and h6 is the smallest heading tag.
11. <HR> TAG – is used to draw lines and horizontal rules.
12. <B>,<I>,<U> for bold, italic and underline respectively.

69. EXPLAIN ABOUT LIST TAG.

TYPES OF LISTS

4. Unordered lists
5. Ordered lists

UNORDERED LISTS

It starts with <ul> and ends with </ul>

Attributes of Unordered lists

TYPE:

TYPE = FILLROUND or TYPE = SQUARE

EXAMPLE

<UL TYPE = FILLGROUND>


<LI> CSE </LI>
<LI> IT </LI>
</UL>
ORDERED LISTS (NUMBERING>

TYPE: Controls the numbering scheme to be used

TYPE = “1” will give counting numbers (1,2,…>

349
“A” will give A,B,C..
“a” will give a,b,c
“I” starts with Capital roman letters I,II,II…
“I” starts with small case roman letters

START: Alters the numbering sequence, can be set to any numeric value

VALUE: Change the numbering sequence in the middle of an ordered list


EXAMPLE
<OL TYPE = “1” START = 5>
<LI> CSE </LI>
<LI> IT </LI>
</OL>
OUTPUT

5 CSE
6 IT

70. EXPLAIN THE ATTRIBUTES OF TABLE TAG WITH AN EXAMPLE

A table is a two dimensional matrix, consisting of rows and columns. All table related tags
are included between <TABLE> </TABLE> tags.

<TABLE>
<TH> Heading </TH>
<TR> Row elements </TR>
<TD> Table data values </TD>
</TABLE>
ATTRIBUTES OF TABLE TAG

ALIGN Horizontal alignment is controlled by the ALIGN attribute. It can be set


to LEFT, CENTER, or RIGHT
VALIGN Controls the vertical alignment of cell contents. It accepts the values TOP,
MIDDLE or BOTTOM
WIDTH Sets the WIDTH of a specific number of pixels or to a percentage of the
available screen width.
BORDER Controls the border to be placed around the table.
CELLPADING This attribute controls the distance between the data in a cell and the
boundaries of the cell
CELLSPACING Controls the spacing between adjacent cells
COLSPAN Used to spilt the single cell to one or more columns
ROWSPAN Used to spilt the single cell to one or more rows.

EXAMPLE

350
<TABLE BORDER = 3 WIDTH = 100 HEIGHT = 200>
<TR>
<TH> Roll Number </TH>
<TH> Age </TH>
<TR>
<TR> <TD> 1 </TD> <TD 35 </TD> </TR>
</TABLE>
14. ALIGN: ALIGN = TOP, MIDDLE,BOTTOM
15. BORDER: Specifies the size of the border to place around
the image.
16. WIDTH: Specifies the width of the image in pixels.
17. HEIGHT: Specifies the height of the image in pixels
18. HSPACE: Indicates the amount of space to the left and
right of the image
19. VSPACE: Indicates the amount of apace to the top and
bottom of the image.
71. WHAT DO YOU MEAN BY COLUMN SPANNING AND ROW SPANNING?
Row spanning is used to merge (combine) two or more rows.
Column spanning is used to merge (combine) two or more columns.

72. MENTION THE DIFFERENT TYPES OF LINKS

HTML allows linking to other HTML documents as well as images. There are 3 attributes
that can be introduced in BODY tag.

7. LINK – Changes the default color of a Hyperlink to


whatever color is specified with this tag.

8. ALINK – Changes the default color of a hyperlink that is


activated to whatever color is specified with this tag.

9. VLINK – Changes the default color of a hyperlink that is


already visited to whatever color is specified with this tag.

NOTE: User can specify the color name of a hyperlink or an


equivalent hexadecimal number.

351
EXTERNAL LINKS

SYNTAX
A HREF = “location name”> Hyper Text Message </A>

73. EXPLAIN IMAGE MAPS WITH ITS SYNTAX

When a hyperlink is created on an image, clicking on any part of the image will lead to
opening of the document specified in the <A HREF TAG>.

Linked regions of an image map are called hot regions and each hot region is associated with
a filename.html.

Syntax

<MAP NAME = “map name”>

ATTRIBUTES OF IMAGE MAPS

7. COORDS: Each of the above shapes takes different coordinates as parameters.


a. Rectangle – 4 coordinates (x1,y2,x3,y2)
8. POLYGON: 3 or more coordinates.

9. HREF – Takes the name of the .html file that s linked to the particular area on the
image.

<MAP NAME = “fish.jpg”>


<AREA SHAPE = “rect” COORDS = “52,65,122,89” HREF = “sct.html”>
</MAP>

75. EXPLAIN ABOUT HTML FORM TAG WITH ITS ATTRIBUTES.

HTML form provides several mechanisms to collect information from people viewing your
site. The syntax of the form is

<FORM METHOD = “POST” ACTION = “/cgi-bin/formail”>

• The METHOD attribute indicates the way the web server will
organize and send you the form output.

352
• Use METHOD = “post” in a form that causes changes to server
data, for example when updating a database.

• The ACTION attribute in the FORM tag is the path to this script;
in this case, it is a common script which emails form data to an
address. Most Internet Service Providers will have a script like
this on their site.

76.MENTION THE VARIOUS FORM ELEMENTS.


Various elements or controls can be created in FORM using <INPUT> tag. They are
1. Label 2. Text box 3. Text Area 4. Radio button
5. Check box 6. List box 7. Command button 8. Scroll bars

77. WHAT IS THE USE OF FRAMES IN HTML GIVE THE SYNTAX.

FRAMES

Frames are used to call many html files at the same time. This can be done using
<FRAMESET> </FRAMESET> tags.

ATTRIBUTES OF FRAMES

ROWS – This attribute is used to divide the screen into multiple rows. It can be set equal to
a list of values. Depending on the required size of each row. The values can

• A number of pixels
• Expressed as a percentage of the screen resolution
• The symbol *, which indicates the remaining space.

COLS – This attribute is used to divide the screen into multiple columns.

EXAMPLE

<FRAMESET ROWS = “30%,*”> => Divides the screen into 2 rows,


* occupying the remaining space
<FRAMESET COLS = “50%,50%”> => Divides the first row into 2 equal
columns

353
<FRAME SRC = “file1.html”>
<FRAME SRC = “file2.html”>

<FRAMESET COLS = “50%,50%”> => Divides the second


row into 2 equal columns

<FRAME SRC = file3.html”>


<FRAME SRC = file4.html”>
</FRAMESET>
</FRAMESET>
78. MENTION THE TYPES OF SCRIPTING LANGUAGES

• JavaScript is a Scripting language (web site development environment) created by


Netscape.

• Hence JavaScript works best with the Netscape suite of Client and Server products.

• JavaScript is the native scripting language of Netscape Navigator.

• VBScript is the native Scripting language of HTML.

SERVER SIDE SCRIPTING

• In Server side scripting the script program is executed at Server Side the required
html program is sent to the client.

• The job of the server is more in server side scripting

CLIENT SIDE SCRIPTING


• Here the script program is processed and executed in the client side itself.

• So that it reduces the burden of the server.

79. LIST THE ADVANTAGES OF JAVA SCRIPT

5. JavaScript is an object-oriented language that allows creation of interactive Web


pages

6. JavaScript allows user entries, which are loaded into an HTML form to be processed
as required

ADVANTAGES

354
21. It is an interpreted language, which requires no compilation steps.
22. Embedded within HTML.
23. Minimal Syntax – easy to learn
24. Quick Development
25. Designed for simple, small programs
26. High performance
27. Procedural Capabilities – support facilities such as condition checking, looping and
branching.
28. Designed for programming user events – like VB Java Script is also based on Events.
29. Easy Debugging and Testing
30. Platform Independence/ Architecture Neutral

SYNTAX OF JAVASCRIPT PROGRAM

<HTML>
<HEAD>
<SCRIPT language = “JavaScript”>

… body of the script program


</SCRIPT>
</HEAD>

<BODY>
<SCRIPT language = “JavaScript”>

body of the program.


</SCRIPT>
</BODY>
</HTML>

80. WHAT IS DENSE ARRAYS?

• A dense array is an array that has been created with each of its elements being
assigned a specific value.

• Dense arrays are used exactly in the same manner as other arrays.

• Dense arrays are declared and initialized at the same time.

Array Methods

355
Join() – returns all elements of the array joined together as a single string.

Reverse() – reverses the order of the elements in the array.

81. LIST COMPARISION OPERATORS & STRING OPERATORS IN JAVA

• = = equal (perform type conversion before testing for equality.

• = = = strictly equal (do not perform type conversion before testing for equality

STRING OPERATIRS
Currently Java Script supports only one string concatenation (+) operator.

EXAMPLE
“ab” + “cd” produces “abcd”

82. LIST THE VARIOUS DIALOG BOXES IN JAVA SCRIPT


Dialog boxes are used to display small windows. This is also used to get input from user.
SYNTAX
alert(“message”);
alert(“Click here to continue”)
prompt(“Enter your name”, name)

7. Alert is only used to display some information


8. Prompt is used to display information along with some input value
9. Confirm dialog box, causes program execution to halt until user action takes place.
The user action can be either OK or CANCEL.

OK – returns true
CANCEL – returns false

90. MENTION THE VARIOUS JAVA SCRIPT OBJECT MODELS.


• Math Object
• String Object
• Date Object
• Boolean and Number Object
• Document Object
• Window Object
91. HOW SCRIPTING LANGUAGE IS DIFFERS FROM HTML.

• HTML is used for simple web page design

356
• HTML with FORM is used for both form design and Reading input values
from user.
• Scripting Language is used for Validating the given input values weather it is
correct or not, if the input value is incorrect, the user can pass an error
message to the user.
• Using form concept various controls like Text box, Radio Button, Command
Button, Text Area control and List box can be created.
92. DEFINE FUNCTION IN JAVA SCRIPT.
Function is a part of a program or in other words function is a module in java
program which can be called or invoked any number of times from the main
program.

Function can be called any number of times but it can accept any input values or
parameters, however it can return only one output at a time.

END OF UNIT III

UNIT – IV & V: DYNAMIC HTML, SERVLETS

93. DEFINE CSS – CASCADING STYLE SHEET

• DHTML is a new and emerging technology that has evolved to meet the increasing
demand for eye-catching and mind-catching web sites.
• DHTML combines HTML with Cascading Style Sheets (CSS) and Scripting
Languages. HTML specifies a web page’s elements like table, frame, paragraph,
bulleted list, etc. CSS can be used to determine an element’s size, color, position and a
number of other features.
• Scripting Languages (JavaScript and VBScript) can be used to manipulate the web
page’s elements so that styles assigned to them can change in response to a user’s input.

87. DEFINE CASDING STYLE SHEETS (CSS)

• CSS are powerful mechanism for adding styles (e.g. Fonts, Colors, Spacing) to web
documents.

357
• They enforce standards and uniformity throughout a web site and provide numerous
attributes to create dynamic effects.
• The advantage of a style sheet includes the ability to make global changes to all
documents from a single location. Style sheets are said to cascade when they combine
to specify the appearance of a page.
The style assignment process is accomplished with the <STYLE>…</STYLE>
tags.

94. MENTION THE TYPES OF STYLE SHEETS

87.1 Embedded or Internal Style sheet


87.2 External or Linked Style sheet
87.3 Inline style sheet

95. DIFFERENCE TYPES OF STYLE SHEETS

Slno ‘Embedded Linked Inline Style Sheet

1 Style program is Style program alone is stored in a Different from


embedded with in the separate file with an extension of Embedded and
HTML program itself. .css file. Linked CSS
2 Explicit LINK statement Explicit LINK REL statement is Not required
is not needed. needed to connect with .CSS file
3 Styles can be used within Styles used in .CSS file can be Styles created should
the program only, it can used in any HTML program be used immediately
not be called some other before creating
files. another new style.

96. LIST THE PROPERTIES OF STYLE TAG

<STYLE> tag properties are divided in to 6 categories. They are

• Font Attributes

358
• Color and Background attributes
• Text Attributes
• Border Attributes
• Margin Attributes and
• List Attributes.
90. HOW TO INTRODUCE STYLE IN HTML PROGRAM?

<HTML>
<HEAD>
<STYLE Type = “text/css”>

predefined tag name {attribute name1:attribute value1; attribute name2:attribute


value2; ……attribute name-n:attribute value-n}

<STYLE>
</HEAD>
<BODY>
write the body of program
</BODY>
</HTML>

91. WHAT DO YOU MEANT BY OBJECT MODEL AND COLLECTION?

• The object model allows web authors to control the presentation of their pages and
gives them access to all the elements on their web page.

• The whole web page – elements, forms, frames, tables, etc – is represented in an
object hierarchy.

• Using scripting, an author is able to retrieve and modify any properties or attributes of
the web page dynamically.

92.LIST THE TWO DATE OBJECTS

359
UTC – Coordinated Universal Time
GMT – Greenwich Mean Time
93. WHAT ARE COOKIES ?

Cookies provide web developers with a tool for personalizing web pages.

A cookie is a piece of data that is stored on the user’s computer to maintain information about
the client during and between browser sessions.

94. WHAT DO YOU MEAN BY OBJECT REFERENCING?

• The simplest way to reference an element is by using the element’s id attribute.

• The element is represented as an object, and its various XHTML attributes become
properties that ca be manipulated by scripting.

95. DEFINE Data Binding.

• With data binding, data need to longer reside exclusively on the server.

• Data can be maintained on the client, in a manner that distinguishes it from the
XHTML markup on the page.

• Typically, data is sent to the client. All subsequent manipulations than take place on
the data directly on the client, thus eliminating server activity and network delays.
• Once it is available on the client, the data can be sorted and filtered in various ways.

• In data binding technology, data made on the client do not propagate(spread,


broadcast) back to the server.

• Once it is available on the client, the data can be sorted and filtered in various ways.

• To bind external data to XHTML elements, Internet Explorer employs software


capable of connecting the browser to live data sources. These are known as Data
Source Objects (DSOs).
• The most popular DSO is – the Tabular Data Control (TDC).

360
96. WHAT DO YOU MEAN BY RECORDSET?
A recordset is simply a set of data or rows to be accessed by the program. It contains the
following recordset object methods.

9. MoveNext – used to move the recordset to the next row.


10. MovePrevious – used to move the recordset to the previous row.
11. MoveFirst – used to move the recordset to the first record immediately.
12. MoveLast – used to move the recordset to the last record immediately.

Note move previous and move next methods should be used before checking BOF(),
EOF() methods respectively.

98. WHAT IS EVENT MODEL LIST SOME DHTML EVENTS.

When the program is executed based on a particular event occurrence, it is referred as Event
modeling. The DHTML events are described below:

Event Description

onbeforecut Fires before a selection is cut to the clipboard


onbeforecopy Fires before a selection is copy to the clipboard
onbeforepaste Fires before a selection is paste to the clipboard

onbeforeupdate Fires before a data source is updated


onafterupdate Fires after a data source is updated

onrowenter,onrowexit, Related to rows, executed when you enter into row, exit,
onrowsdelete,onrowsinserted delete and insert respectively.

onhelp, onkeydown, Fires help, keydown and keyup respectively


onkeyup
ondbclick, ondrag, ondrop Fires when double click, drag or drop event is occurred.
onchange Fires when a new change occured

98. WHAT DO YOU MEAN BY FILTERS AND TRANSITIONS (Changeover, conversion,


shift) IN DHTML?

• Filters and transitions are specified with the CSS filter property.

• Applying filters to text and images causes changes that are persistent.

361
• Transitions are temporary: applying a transition allows you to transfer from one page
to another with a pleasant visual effect, such as a random dissolve.

• Filters and transitions do not add content to your pages – rather, they present existing
content in an engaging manner to capture the user’s attention.

• Each of the visual effects achievable with filters and transitions if programmable, so
these effects can be adjusted dynamically by programs that respond to user-initiated
events, such as mouse clicks and keystrokes.

99. EXPLAIN ABOUT FLIP FILTERS – (FLIPv AND FLIPh ) PROPERTIES.

• The flipv and fliph filters mirror text or images vertically and horizontally.

<!-- EVENT MODEL FOR ONCLICK - FILTERS1.HTML


<!------------------------------------------>
<?xml version = "1.0"?>
<!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">


<head>
<title> THE FLIP FILTER - FILTERS1.HTML </title>
<style type = "text/css">
body { background-color: cyan } table { font-size: 3em; font-family:arial,
sans-serif; background-color:pink; border-style: ridge}
td { border-style: groove; padding: lex }
</style
</head>
<body>
<table>
<tr>
<!-- Filters are applied in style declarations ---->
<! ------------------------------------------------>
<td style = "filter: fliph"> Text </td>

<td> Text
</tr>

<!-- More than one filter can be applied at once---->


<! ------------------------------------------------>
<tr>

362
<td style = "filter: flipv fliph"> Text </td>
<td style = "filter: flipv"> Text </td>
</tr>

</table>

</body>
</html>

OUTPUT

fliph filter applied

filpv filter applied

Both

110. WHAT IS THE USE OF XML?

• Extensible Markup Language, derived from SGML (Standard Generalized


Markup Language.

• XML is widely supported open technology (i.e. non-proprietary) for electronic


data exchange and storage.

• XML is actually a language used to create other markup languages to describe


data in a structured manner.

• XML documents contain only data, not formatting instructions, so


applications that process XML documents must decide how to manipulate or
display the document’s data.

363
111. WHAT DO YOU MEAN BY DTD IN XML?

• DTD means Document Type Definition.

• DTD file is similar to CSS file, because DTD also contains only styles.

• DTD contains various styles which are to be applied in XML document.

• Like .CSS file .DTD file also should be linked with XML program.

• Styles in XML program should be save with .xsl (Xml Style Sheet Language)
extension.

112. WHAT IS THE USE OF XML NAMESPACE?

• XML allows document authors to create custom elements.

• This extensibility can result in naming collisions (i.e. different elements that have
the same name) among elements in an XML document.

• An XML namespace is a collection of element and attribute names. Each


namespace has a unique name that provides a means for document authors to
unambiguously refer to elements with the same name (i.e. prevent collisions).

113. WHAT ARE THE USES OF XML?

• CML – Chemical Markup Language – for chemical equations

• MML - Mathematical Markup Language – for Mathematical equations and


derivations.

• Used in bio medical line.

114. What is SOAP? (Simple Object Access Protocol)

• SOAP is an XML based protocol that allows applications to easily over the
internet using XML documents called AOAP message.

• A SOAP message contains an envelope, which is a structure that describes a


method call.

• A SOAP message’s body contains either a request or a response.

364
• A request message’s body contains a Remote Procedure Call (RPC), which is a
request for another machine to perform task.

• The RPC specifies the method to be invoked and any parameters the method
takes.

• The application sends the SOAP message via an HTTP POST. A SOAP response
message is an HTTP response document that contains the results from the
methods call (e.g. return values, error messages.)

115. WHAT IS THE USE OF WEB SERVICES?

• Web services encompass a set of related standards that can enable two computer
applications to communicate and exchange data over the Internet.

• The data is passed back and forth using standard protocols such as HTTP, the same
protocol used to transfer ordinary web pages.

• Web services operate using open, text-based standards that enable components written
in different languages and on different platforms to communicate.

• They are ready to use pieces of software on the Internet. XML, SOAP, Web Services
Description Language (WSDL) and Universal Description, Discovery and Integration
(UDDI) are the standards on which web services rely.

• UDDI is another XML based format that enables developers and business to publish
and locate Web services on a network.

116. MENTION

117. LIST AND THE FUNCTIONS OF THREE-TIER APPLICATIONS.

• 107.1 The client tier, or top tier, is the application’s user interface. Users interact
directly with the application through the client tier, which is typically a Web browser,
keyboard and mouse.

• 107.2 The Middle tier implements business logic and presentation logic to control
interactions between application clients and application data.

365
• 107.3 Business logic in the middle tier enforces business rules and ensures that data
is reliable before updating the database to presenting data to a user.

118. WHAT IS IIS?

• IIS – Microsoft Internet Information Services is an enterprise-level web server


that is included with several versions of Windows.

• Installing IIS on a machine allows that computer to serve documents

119. WHAT IS MYSQL?

• MYSQL is a multi-user, multithreaded (i.e. allows multiple simultaneous


connection).

• RDBMS server that uses SQL to interact with and manipulate data.

• Implementations of MYSQL are available for Windows, Mac OX X, Linux and


UNIX.

• The ability to access table from different databases y using a single query,
increasing the efficiency of retrieving accurate and necessary information.

• MYSQL provides the ability to handle large databases (e.g. ten of thousands of
tables with millions of rows.

120. WHAT IS THE USE OF PERL DATABASE INTERFACE.

• The Perl Database Interface (DBI) enables users to access relational databases
from Perl programs.

• Database vendors create drivers that can receive interactions through DBI and
process them in a database specific manner.

• DBI is the most widely used interface available for database connectivity in Perl.

366
PART B – QUESTIONS

BOOK NAME: Java Network Programming(study all the points from


notes also)
29. *** Why Java is essential in Network programming? (page 2 13 – 8 marks)

30. With a neat diagram explain the layers of IP network (only 4 layers) (page 22 – 28 – 8
marks).

31. Explain the various types of Client/Server Models (Study from notes – 8 marks)

32. Write short notes on the following (PG NO. 50 – 62 - 16 marks)


URI
URN
URL
HTML
SGML

367
XML

33. ****Write short notes on MIME & CGI 70 (pg no. 63 – 70 – 8 marks)

34. Write short notes on applets and Security (page no. 71 – 74 – 8 marks)

35. Write short notes on different types of Stream(Input/Output/Filter/buffered/Print


Stream classes – 76 – 109 - ** Write one example program involving 5 to 6 stream
classes)

36. **** Explain in detail about Thread & Multi thread concept with example
program(117 onwards with an example program)

37. ***Explain the various types of Address format. (page no. 167 – Write detail about
address A, B, C, D and E in detail)

38. ***Explain in detail about retrieving data using URL connection (page 193)

• Explain URL connection concept


• Explain all the methods in URL like getConnection, getContent etc
• Explain Lab URL program without fail.

39. ***Explain Client/Server Socket Programming in detail (page no 301 onwards – 8


marks)

• Write the any socket program in Lab exercise without fail compulsory.

40. ***Write short notes Protocol Handlers and Content Handlers in detail with a small
program (page no 529 – 581 – 16 marks)

41. *** With a neat diagram explain the concept of RMI (Study from Java complete
reference book with diagram and write LAB exercise also without fail – 16 marks)

REFERENCE BOOK: INTERNET & WORLD WIDE WEB


HOW TO PROGRAM – THIRD EDITION – DEITEL & DEITEL

42. Discuss the various HTML tags in detail (16 marks – refer notes)

43. ** Write short notes on the following (165 marks - refer notes)
IMG tag
TABLE tag

368
FRAME tag

44. ** With a neat diagram write a SCRIPT PROGRAM with validation for the following
(each program carries 16 marks)

Student Mark List


Inventory System
Employee Pay Slip generation
Railway Ticket Reservation
Online Quiz program

NOTE Answer should be in the following format only.

10. Draw form design

11. Design must have one Primary key field – always


check for duplication for the primary key field

12. emp- name, product- name, dept-name etc should not


be blank
Write a function for all these validation

13. When you introduce any number field, always check it


is negative or not, if it so do not accept the input value

14. For calculations always use program concept, do not


ask the user to enter total, gross etc.

15. Instead through program calculate

Gross.value = val(basic.value + hra.value+da.value)

16. Always use val or ParseInt function when you perform


calculation with numbers.

17. for avoiding too much of validation better use the


following in the design itself

• Radio button
• Command button
• Check box
• List box

369
18. Must introduce SUBMIT & RESET button at the end
of the design

45. *** Explain in detail about all the types of Cascading Style sheet with an example
program(16 marks – page no. 140 -149)

draw the form design


Mention the 3 types of CSS
Write example program for each type
Write the differences and advantages of each CSS

46. ***Write short notes on the following.(16 marks – page no. 174 - 221)

Write short notes on Java Script/Advantages of Scripting


Java Script control statements
Java Script functions

47. ** Discuss briefly about HTML – Object Model and Collections (Page no 429 – 438)
** Study from notes also

Object modeling
Object Referencing
Dynamic Styles
Dynamic Positioning

48. *** Discuss briefly Dynamic HTML – Event Model (page mp 451 – 471 refer notes
also)

Short notes on event model


Printing all the tags using program
Explain Event bubbling with an example program

49. **** Discuss briefly about Dynamic HTML – Filters and Transitions (page no. 476 –
495 refer notes also)

370
Explain filters and transitions with example
Write program using flipv and fliph attribute with output
diagram.
List all the possible events given in the notes.

50. *** Discuss briefly about Data Binding using any control for example

• binding with table


• binding with an image
• sorting table data.

51. ** Discuss briefly the various servers (refer V th unit notes)

52. ****Discuss briefly about Handling of Multimedia database (very important


question) (page 985 - 1023)

53. *** Explain handing of ACTIVEX CONTROL.

54. ** Explain the concept of Servlets with an example program ( Lab exercise)

55. Explain about JSP with example program.

56. Explain about JDBC structure with example program.

END OF QUESTION BANK

371