Escolar Documentos
Profissional Documentos
Cultura Documentos
Internet standards – TCP and UDP protocols – URLs – MIME – CGI – Introduction to
SGML.
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.
HTML forms – frames – tables – web page design – Java Script introduction – control
structures – functions – arrays – objects – simple web applications
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.
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.
REFERENCES
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
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
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.
EXPERIMENTAL STANDARD
4
PROPOSED STANDARD
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
EDIT STANDARD
• 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.
• 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.
• 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.)
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.
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).
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.
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.
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
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
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.
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
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.
Web Server
Request
Internet
Response
Client
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.
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.
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.
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.
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.
Request
Internet
15
Response
Client
Web server Transaction 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.
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.
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. Application Layer
2. Transport Layer
3. Internet Layer
4. Network Layer
5. Physical Layer
Presentation Layer
Session Layer
Transport (host – to – host) Layer
Transport Layer
17
Data Link Layer Network Access Layer
• 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.
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
19
THE NETWORKING CLASSES AND INTERFACES
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.
• Application layer provides access to OSI environment for users and also
provides distributed information services.
• 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
SYNTAX
Protocol name://username@hostname:port/path/filename#fragment?Query
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 optional port numbers, default port number value is 80 for HTTP
server.
PATH
21
Path points to a particular file in the directory specified.
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.
SYNTAX OF URN
Urn:name:resource-name
22
Name space - is the name of a collection of certain resources contained by some authority.
2. URNs – Uniform Resource Name (is a name for a particular resource but without
reference to a particular location)
FORMAT OF URI
URI
URL URN
1.3.4 URL
23
• Uniform Recourse Locator is a way to unambiguously identify the location of a
resource on the Interned.
• 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
RELATIVE URL
URL that is not complete but inherits pieces from their parent is called relative URLs.
ABSOLUTE URL
Protocol://username@hostname:port/path/filename#fragment?query
Where,
24
• Protocol is another word for what was called the scheme of the URL.
• 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.
• 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
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.
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.
6. The MIME contents are classified into two levels. They are
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
3. The original SMTP protocol was designed but MIME is designed for sending
multimedia data base like audio, video content types.
27
• The message body contains the actual data being transferred which may consist of
plain text, images, WWW electronic mail
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.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 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.
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
• 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 .
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.
File Database
• Traditionally, HTML program is static. CGI provides more interaction to their users.
• 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.
http://www.server-name.com/cgi-bin/example.pl
30
• In the above diagram the web browser sends a request to Web Server.
• Now the CGI server searches the output from the file or database.
• The CGI server can understand the above mentioned type of files.
CGI environment variables are entities which are known by both web server and CGI
programs for communicating useful data between them.
31
7 QUERY_STRING Returns the string in the query.
11 SCRIPT_NAME Stores the virtual path and name of the CGI script
being executed. This is used for self-referencing
URLs.
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.
• 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.
• 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.
34
3 CONTENT_LANGUAGE Specifies the language the returning document is
in. An example is “en” which is English in one of
its forms.
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.
<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>
• SGML allows the user to create various user defined tags easily without any rules.
• Similar to SGML
• The value of an attribute may be enclosed in double of single quotes like this:
• 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.
37
<PRODUCT MANUFACTURER=”ABC COMPANY”> -Assumed as record name
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.
1. 2xx Successful – between 200 and 299 indicates that the request was received,
understood, and accepted.
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.
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
39
• A response code from 300 to 399 always indicates redirection;
• 400 to 499 indicate client error;
• 500 to 599 indicate a server error.
• 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.
• When a browser sees an applet tag and decides to download and play the applet, it starts a
long chain of events.
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.
40
There is much FUD (fear, uncertainty, and doubt) in the press about what Java applets
can and cannot do.
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().
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
41
2.11 Applets
2.12 Image Handling
2.13 Remote Method Invocation
• 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 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.
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
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.
4. The main goal of Java program is “Write once, run anywhere, any time, forever”.
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.
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. Input streams are used to read data; Output streams are used to write data.
5. Filters can modify the data as it is read or written – for instance, by encrypting or
compressing it.
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
44
public abstract class OutputStream
This class provides the fundamental methods needed to write data. The methods in
OutputStream classes are:
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.
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.
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
INPUT STREAMS
This class provides the fundamental methods needed to read data. The methods in
InputStream classes are as follows:
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
This method is used for checking whether the data is available or not for read
operation.
if (b = = -1) break;
input[i] = (byte) b;
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:
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.
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.
49
CONSTRUCTORS FOR BUFFERED IN/OUT STREAM CLASSES
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)
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)
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()
• The read() and available() methods are invoked exactly as with normal input streams.
• More unread() methods that push a specified array or sub array onto the stream.
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
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.
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.
ENCRYPTING STREAMS
• Two abstract super classes define the basic API for reading and writing
characters.
• Wherever input and output streams use bytes, readers and writers use
Unicode Characters.
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
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.
Similarly we have
1. PushbackReader
2. PrintWriter classes.
THREADS
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.
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.
The priority which has 10, 5 and 1 will get executed in order.
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
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.
WAITING ON AN OBJECT
• 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.
THREAD POOLS
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.
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.
DNS, IP ADDRESSES
60
1. Devices connected to the Internet are called nodes.
3. Each node or host is identified by at least one unique 32-bit number called an Internet
address.
6. To avoid the complexity of IP address problem, the designers of the Internet invented
the domain Name System (DNS).
• 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.
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.
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.
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.
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.
62
7. bytes – This is the number of bytes of data that was sent to the client as a result of this
request.
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 itself forms the context through which the different strategies
are selected.
The simplest URL constructor just takes an absolute URL in string form as its single
argument
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.
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.
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.
• The URL class has three methods (four in java 1.3) to retrieve data from a URL.
They are
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.
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.
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.
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.
• 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.
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.
• 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())
66
SOCKETS FOR CLIENTS
DATAGRAMS
• Data is transmitted across the Internet in packets of finite size called datagrams.
• 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
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.
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.
2. Each lets you specify the host and the port you want to connect to.
Creates a TCP socket to the specified port on the specified host and attempts to
connect to the remote host.
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.
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.
Public synchronized void close() throws IOException – is used to close the socket.
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.
• 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 format of the query precisely, defied, the format of the response somewhat less
so.
WHOIS
• 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).
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.
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.
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.
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.
6. The server returns to step 2 and waits for the next connection.
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.
HTTP SERVERS
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.
1. HTTP server can serve an entire document tree, including images, applets, HTML
files, and more.
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
• JSSE(Java Secure Socket Extension) uses the standard event model to notify
programs when the handshaking between client and server is completes.
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.
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.
The following constructors create a new DatagramPacket objects for sending data across the
network.
2. DatagramPacket(byte[] data, int offset, int length, InetAddress destination, int 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.
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.
• 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.
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
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.
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.
• 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.
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.
79
• Multicasting is supported in the built-in TCP stack of Microsoft Windows 95, 98
and NT.
CONSTRUCTORS IN MULTICASTING
Once a Multicast Socket has been created, it can perform four key operations. These
are
• 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.
80
1. Construct a URL object
SYNTAX
try
{
URLConection uc = u.openConnection();
}
catch (IOException e)
{
System.err.println(e);
}
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();
if(len > 0)
{
System.out.println("=========Content =========");
InputStream input = hpCon.getInputStream();
int i = len;
System.out.print((char) c);
}
input.close();
}
else
{
System.out.println("No content Available ");
}
}
82
}
EXPLANATION
1. public String getContentType() – returns the MIME content type of the data.
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
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
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();
}
}
}
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);
}
}
}
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";
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");
}
}
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.
EMAIL ADDRESS
Some of the domain names and its descriptions are given below.
89
Two letters after period (.) can be used to segregate between the countries. Examples
are as given below:
The previous 6 methods specific commands from a MIME header. But the following
methods inspect arbitrary fields in a MIME header.
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.
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.
DOINPUT
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.
CONTENT HANDLERS
• The URLConnection class is intimately tied to Java’s protocol and content handler
mechanism.
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.
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)
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.
92
3. The getContent() method of the URL calls the getContent() method of its
underlying URLConnection.
5. getContentHandler() checks to see whether it already has a handler for this type in
its cache.
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();
}
}
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("CONTENT-TYPE : " +
HPCON.GETCONTENTTYPE());
IF(LEN > 0)
{
SYSTEM.OUT.PRINTLN("=========CONTENT =========");
INPUTSTREAM INPUT = HPCON.GETINPUTSTREAM();
INT I = LEN;
SYSTEM.OUT.PRINT((CHAR) C);
99
}
INPUT.CLOSE();
}
ELSE
{
SYSTEM.OUT.PRINTLN("NO CONTENT AVAILABLE ");
}
}
}
OUTPUT:
Expires : 0
Content-Length : 20737
=========Content =========
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.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:
OUTPUT WINDOW:
104
2.12 IMAGE HANDLING
• 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.
DATAGRAMS
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.
There are four constructors used in creation of Datagram Packet. They are
105
3. DatagramPacket(byte data[], InetAddress ip-address, int port)
4. DatagramPacket(byte data[], int offset, int size, InetAddress ip-address, int port)
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.
106
Step Five: Start the Server
Step Six: Start the Client
RMI PROGRAM FOR POWER COMPUTATION
import java.rmi.*;
public interface Number extends Remote
{
public double power(double x, double y)throws RemoteException
}
import java.io.*;
import java.rmi.*;
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 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
import java.rmi.*;
public interface AddServerIntf extends Remote
{
double add(double d1,double d2) throws RemoteException;
}
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
}
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);
}
}
}
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
There are different domain names. Each domain represents a group. For example the
following represents different domains and its uses.
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
<HTML>
<HEAD>
<TITLE> This is the Title </TITLE>
</HEAD>
<BODY>
…………..
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
<HTML>
<HEAD>
<TITLE> This is the Title </TITLE>
</HEAD>
<BODY>
114
<ADDRESS> This is Footer </ADDRESS>
</BODY>
</HTML>
EXAMPLE
<html>
<head>
<title> Example for Title and Footer</title>
</head>
<body>
Welcome to HTML page
OUTPUT
3. HEADING TAGS - <h1> </h1> .. <h6> </h6> is used to introduce various headings.
<h1> is the biggest and h6 is the smallest heading tag.
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
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>
OUTPUT
3.1.6 LISTS
TYPES OF LISTS
1. Unordered lists
2. Ordered lists
UNORDERED LISTS
Here DISC provides a shaded circle format and SQUARE provides square shapes
respectively.
118
SYNTAX
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
TYPE: Controls the numbering scheme to be used. The following TYPE schemes can be
used with respect to ordered lists.
START: Alters the numbering sequence, can be set to any numeric value
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
<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.
<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.
LINKS
HTML allows linking to other HTML documents as well as images. There are 3 attributes
that can be introduced in BODY tag.
126
2. ALINK – Changes the default color of a hyperlink that is
activated to whatever color is specified with this tag.
LINKS.HTML
<html>
<head>
<title> EXAMPLE FOR DIFFERENT LINKS </title>
</head>
<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>
</body>
</html>
127
ALINK.HTML
<html>
<head>
<title> Example for ALINK attribute </title>
</head>
<body>
</body>
</html>
VLINK.HTML
<html>
<head>
<title> Example for VLINK attribute </title>
</head>
<body>
</body>
</html>
EXTERNAL LINKS
SYNTAX
EXAMPLE
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
3. HREF – Takes the name of the .html file that s linked to the particular area on the
image.
HTML form provides several mechanisms to collect information from people viewing your
site. The syntax of the form is
• The METHOD attribute indicates the way the web server will
organize and send you the form output.
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.
<HTML>
<HEAD>
<BODY>
<FORM>
Create the necessary form elements (text box, radio, label etc.)
</FORM>
</BODY>
</HEAD>
</HTML>
<html>
<head>
<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>
<html>
<head>
<title> form2-Creating Reset and Submit Buttons </title>
</head>
<body>
<form>
132
CREATION OF LIST BOX
<html>
<head>
<title> Using List box Object </title>
</head>
<body>
<form>
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.
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
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>
135
FILE4.HTML
<html>
<body>
OUTPUT
Output of File2
Output of File1
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
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
<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
<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>
<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
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>
<p>
<h2> This Web Page is Displayed in Yellow Color </h2>
<br>
<br>
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>
145
<br><br>
<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>
146
OUTPUT
147
3.6 JAVA SCRIPT INTRODUCTION
SCRIPTING LANGUAGES
• Hence JavaScript works best with the Netscape suite of Client and Server products.
• In Server side scripting the script program is executed at Server Side the required
html program is sent to the client.
• Here the script program is processed and executed in the client side itself.
JAVA SCRIPT
2. JavaScript allows user entries, which are loaded into an HTML form to be processed
as required
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
4. Quick Development
6. High performance
8. Designed for programming user events – like VB Java Script is also based on Events.
<BODY>
<SCRIPT language = “JavaScript”>
body of the program.
149
</SCRIPT>
</BODY>
</HTML>
EXAMPLE
<HTML>
<HEAD>
<SCRIPT language = “JavaScript”>
</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
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;
for(i=num1;i<=num2;i++)
{
tot1 = tot1 + i;
}
</SCRIPT>
</HEAD>
<BODY>
document. write ("<H2>" + "SUM FROM " + num1 +" to " + num2 + " = " + tot1);
</SCRIPT>
</BODY>
</HTML>
151
OUTPUT
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>
153
OUTPUT
SYNTAX
function function-name(input parameter1, …input
parameter-n)
{
body of the function program
}
154
SYNTAX FOR CALLING THE FUNCTION
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;
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>
</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.
1. arrayName = new Array(Array length) => array size is explicitly specified, array
size is predefined.
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.
ARRAY METHODS
Join() – returns all elements of the array joined together as a single string.
EXAMPLE
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
LOGICAL OPERATORS
|| - Logical or
! Logical not
COMPARISION OPERATORS
• = = = 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.
If(condition)
{
java script code
}
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”);
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>
</SCRIPT>
</HEAD> </BODY> /BODY>
</HTML>
ARITHMETIC OPERATORS
+ - * / % (modulus)
162
3.9.5 JAVASCRIPT KEYWORDS
163
3.9.7 MORE JAVA SCRIPT PROGRAMS
164
JAVA SCRIPT PROGRAM FOR ADDING TWO NUMBERS
<HTML>
<HEAD>
<SCRIPT language = JavaScript>
var tot1 = 0;
var num1=0,num2=0;
</SCRIPT>
</HEAD>
<BODY>
</SCRIPT>
</BODY>
</HTML>
165
OUTPUT
<HTML>
<HEAD>
<SCRIPT language = JavaScript>
166
var tot1 = 0;
var num1=0,num2=0;i=0;
num1 = parseInt(num1);
num2 = parseInt(num2);
for(i=num1;i<=num2;i++)
{
tot1 = tot1 + i;
}
</SCRIPT>
</HEAD>
<BODY>
document.write("<H2>" + "SUM FROM " + num1 +" to " + num2 + " = " + tot1);
</SCRIPT>
</BODY>
</HTML>
167
OUTPUT
168
<HTML>
<HEAD>
<SCRIPT language = JavaScript>
var tot1 = 0;
var num1=0,num2=0;i=0;
num1 = parseInt(num1);
num2 = parseInt(num2);
i = num1;
while(i<=num2)
{
tot1 = tot1 + i;
i++;
}
document.writeln("sum = " + tot1);
</SCRIPT>
</HEAD>
<BODY>
document.write("<H2>" + "SUM FROM " + num1 +" to " + num2 + " = " + tot1);
</SCRIPT>
</BODY>
</HTML>
OUTPUT
169
JAVA SCRIPT PROGRAM USING ARRAY
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
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 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 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
172
Refer Class Note book and assignmet
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
• 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.
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.
<HTML>
<HEAD>
<STYLE Type = “text/css”>
<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.
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)
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
178
Unit name Abbreviation Explanation Relative
Em Em The height of a font Yes
NOTE: Like <STYLE> tag <LINK> also should be given with in <HEAD>… </HEAD>
tags.
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,
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>
<html>
<head>
<title>Embedded Style Sheet> </title>
<style type = "text/css">
</style>
</head>
<h4> <h3> <a href = "EXMAIN4.html" > Back to Main Menu </a> </h3> </h4>
</p> </body> </html>
style4.css
<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>
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
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 uses objects to perform many tasks and therefore is referred to as an object
based programming language.
1. MATH OBJECT
2. STRING OBJECT
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
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
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 element is represented as an object, and its various XHTML attributes become
properties that ca be manipulated by scripting.
EXAMPLE PROGRAM
<html>
<head>
<title> Object reference program </title>
function start()
{
alert( pText.innerText );
pText.innerText = "Thanks for comming";
}
191
</script>
</head>
</body>
</html>
OUTPUT
192
COLLECTIONS ALL AND CHILDREN
Collections, which basically arrays of related objects on a page. There are several special
collections in the 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.
<html>
<head>
<title> COLLECTIONS ALL AND CHILDREN </title>
194
var elements = "";
function start()
{
pText.innerHTML += elements;
alert( elements );
}
</script>
</head>
</body>
</html>
OUTPUT
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.
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.
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.
Event Description
196
onrowsdelete,onrowsinserted
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
</script>
</head>
<body>
<p id = "para"> Click on this button </p>
<input type = "button" value = "Click Here" onclick = "alert( 'Try agin' )" />
</body>
</html>
<!-------------------------------------------------------------------------------->
<! NOTE>
<! ------>
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.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
198
<head>
function documentClick()
{
alert( "You clicked in the document" );
}
if ( value )
event.cancelBubble = true;
}
document.onclick = documentClick;
</script>
</head>
<body>
</body>
</html>
OUTPUT
199
DYNAMIC STYLES – EXAMPLE PROGRAM
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
200
<title> Object model - Dynamic styles </title>
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
201
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
</style>
pText.className = inputClass;
}
</script>
</head>
OUTPUT
202
If the input value is smallText, then the output is
OUTPUT
• 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.
• The flipv and fliph filters mirror text or images vertically and horizontally.
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">
<head>
</style
</head>
<body>
<table>
<tr>
<td> Text
</tr>
<tr>
204
</tr>
</table>
</body>
</html>
OUTPUT
Both
• 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.
RECORDSET
A recordset is simply a set of data or rows to be accessed by the program. It contains the
following recordset object methods.
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>
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>
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>
<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
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>
</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.
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- 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>
</display-name>
<description>
servlet examples
</description>
<servlet>
<servletname> welcome1</servletname>
request</description>
220
<servlet-class>Welcomeservlet</servlet-class>
<servlet>
<servlet-mapping>
<servletname>welcome1</servletname>
<url-pattern>/welcome1</url-pattern>
</servlet-mapping>
</web-app>
• Servlet-mapping element specifies the servlet name and its url name.
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
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.
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.
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. SimpleFormServlet - a servlet that takes form input and redirects it into an HTML page
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
224
5.3.2 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.
• 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:
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
Table 1. Requirements
Name Location
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.
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
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:
229
• Servlets
• JavaServer Pages
• Utility Classes
• Note: For this series we will be using the proposed Servlet SDK 2.3.
• 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.
/onjavaThis is the root directory of the web application. All JSP and XHTML files are
stored here.
/onjava/WEB-INFThis directory contains all resources related to the application that are
not in the document root of the application.
230
/onjava/WEB-INF/libThis directory contains Java Archive files that the web
application depends upon.
• 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.
• Localized Content
• Session Configuration
• 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>
• 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.
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.
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.
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.
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:
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.
<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.
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:
PROPERTY:
<workername>.portThe port property defines the port number of this Tomcat worker. This
value must match the port attribute of the previously defined Tomcat <Connector> element.
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.
interface.
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 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>
.Table 1 contains a description of each of the attributes required in the <user> sub-element.
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.
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.
<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>.
<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.
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.
240
J2EE PLATFORM
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.
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.
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 provides essential features for developing and deploying mission-
critical e-commerce applications across distributed, heterogeneous computing environments.
These features include the following:
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.
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.
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 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.
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.
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.
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).
The following sections discuss the presentation layer, business logic, and application
services.
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-based applications built with standard Web technologies are easy to access,
maintain, and port. Web browser clients are standard for e-commerce applications.
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.
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.
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.
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
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.
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.
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 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
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.
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.
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
Java-to-IDL mapping
Objects-by-value
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
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.
WebLogic Server implements standard J2EE technologies to provide data and access services
to applications and components. These services include the following APIs:
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
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.
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.
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:
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.
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
260
5.4 HTTP REQUESTS
Method-URI-Protocol/Version
Request headers
Entity body
LastName=Franks&FirstName=Michael
HTTP RESPONSES
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.
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);
The following line of code constructs a ServerSocket that listens on port 8080 of the local
machine with a backlog of 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.
263
LIFE CYCLE OF A SERVLET
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.
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.
264
{
doGet(request, response);
}
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:
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.
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."
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
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
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 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.
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.
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.
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.
269
be sent as an HTTP GET (false) or POST (true).
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.
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 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.
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.
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.
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
GET SESSION
• A servlet uses its request object's getSession() method to retrieve the current
HttpSession object:
• 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
REMOVE VALUE
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)
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.
window
276
Anchor Applet Area Form Image Link
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 possible object methods for Database connectivity and straightaway run to a sample
coding:
This method creates a new ODBC object for the given DSN
This method executes a sql command and returns undef on success. Else, an
error code is returned.
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.
This method retrieves data from a FetchRow method just like the Data 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>”;
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.
Introduction to SQL:
The SQL(Structured Query Language) is used to retrive, store and change the data.
Create:
This command is used to create a table
Syntax:
281
Regno Number 5
Name Varchar2 20
Class Varchar2 20
Mark Number 3
INSERT:
Eg: Insert a record in the student table regno 1001 name xxxx class ICSE mark 97
SELECT:
UPDATE:
282
UPDATE student SET mark=100 WHERE regno=1001;
DELETE:
For any application to communicate with the database,it needs to have the following
information:
So, we use JDBC calls to retrive and update information from a database using JDBC.
This involves the following functions:
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.
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:
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:
284
• Sun Microsystem provides a JDBC-ODBC bidge that translate JDBC to ODBC.
• This drivers are the bridge drivers such as the JDBC-ODBC bridge.
• 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
• 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 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.
• 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
• 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.
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.
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
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.
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.
291
4. Define Internet.
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
PORTS
4. Ports are used in receiving and sending data to another server or client.
5. Example for port numbers
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
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.
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.
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.
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.
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.
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.
URL
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
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
URLs that are not complete but inherit pieces from their parent are called relative URL.
296
17. EXPLAIN ABOT SGML – STANDARD GENERALIZED 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. 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
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.
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>
• 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.
• When a browser sees an applet tag and decides to download and play the applet, it starts a
long chain of events.
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.
There is much FUD (fear, uncertainty, and doubt) in the press about what Java applets
can and cannot do.
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
300
9. Input streams read data/Output streams write 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.
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.
301
Flush method rescues you from deadlock by forcing the buffered stream to send its data
even if the buffer is not yet full.
public int read(byte[] input, int offset, int length ) throws IOException
• 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:
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.
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.
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.
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:
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)
Java .util.zip package contsins filter streams that compress and decompress
streams in zip, gzip, and deflate(shrink or reduce) formats.
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.
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.
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
READERS
LineNumberReader
• 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.
306
• A Thread with a capital T is an instance of the java.lang.Thread class.
• Most of the time it’s obvious from the context which is meant if the difference is
really important.
4. To run a Thread
Public void run()
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.
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.
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.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.
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.
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.
The priority which has 10, 5, 1 will get executed in the order.
• 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.
It is used to join two threads. After joining threads it can be sequenced one by one
Even if the threads finish quickly, this can overload the garbage collector or other parts of the
VM, and hurt performance
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
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.
12. To avoid the complexity of IP address problem, the designers of the Internet invented
the domain Name System (DNS).
• 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 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 simplest URL constructor just takes an absolute URL in string form as its single
argument:
Try
{
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.
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.
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.
• 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.
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
Creates a TCP socket to the specified port on the specified host and attempts to
connect to the remote host.
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
314
• The client makes a TCP connection to the server on port 79 and sends a one line
query.
• The format of the query precisely, defied, the format of the response somewhat less
so.
• 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).
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.
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.
3. HTTP server can serve an entire document tree, including images, applets, HTML
files, and more.
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.
316
12. public void removeValue(String name)
• 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.
• 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.
• 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.
• 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.
• The URLConnection class is intimately tied to Java’s protocol and content handler
mechanism.
318
• Based on the type of the content type responsible protocol is allocated by the protocol
handler.
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.
END OF UNIT II
319
UNIT III – SCRIPTING LANGUAGES
<HTML>
<HEAD>
<TITLE> This is the Title </TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>
Note: All the tags in HTML program are optional, however the file should be saved in .html
extension.
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.
TYPES OF LISTS
1. Unordered lists
2. Ordered lists
UNORDERED LISTS
TYPE:
EXAMPLE
START: Alters the numbering sequence, can be set to any numeric value
321
EXAMPLE
<OL TYPE = “1” START = 5>
<LI> CSE </LI>
<LI> IT </LI>
</OL>
OUTPUT
5 CSE
6 IT
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
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.
HTML allows linking to other HTML documents as well as images. There are 3 attributes
that can be introduced in BODY tag.
EXTERNAL LINKS
SYNTAX
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
6. HREF – Takes the name of the .html file that s linked to the particular area on the
image.
HTML form provides several mechanisms to collect information from people viewing your
site. The syntax of the form is
• The METHOD attribute indicates the way the web server will
organize and send you the form output.
• 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
325
78. MENTION THE TYPES OF SCRIPTING LANGUAGES
• Hence JavaScript works best with the Netscape suite of Client and Server products.
• In Server side scripting the script program is executed at Server Side the required
html program is sent to the client.
4. JavaScript allows user entries, which are loaded into an HTML form to be processed
as required
ADVANTAGES
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
<HTML>
<HEAD>
<SCRIPT language = “JavaScript”>
<BODY>
<SCRIPT language = “JavaScript”>
• 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.
Array Methods
Join() – returns all elements of the array joined together as a single string.
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”
SYNTAX
alert(“message”);
alert(“Click here to continue”)
prompt(“Enter your name”, name)
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.
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.
329
UNIT – IV & V: DYNAMIC HTML, SERVLETS
• 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.
• 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.
330
88. LIST THE DIFFERENCE BETWEEN STYLE SHEETS
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”>
<STYLE>
</HEAD>
<BODY>
331
write the body of program
</BODY> </HTML>
• 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.
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.
• The element is represented as an object, and its various XHTML attributes become
properties that ca be manipulated by scripting.
• 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.
• Once it is available on the client, the data can be sorted and filtered in various ways.
Note move previous and move next methods should be used before checking BOF(),
EOF() methods respectively.
onrowenter,onrowexit, Related to rows, executed when you enter into row, exit,
onrowsdelete,onrowsinserted delete and insert respectively.
333
onkeyup
ondbclick, ondrag, ondrop Fires when double click, drag or drop event is occurred.
Onchange Fires when a new change occured
• 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.
• The flipv and fliph filters mirror text or images vertically and horizontally.
334
<table>
<tr>
<td> Text
</tr>
</table>
</body>
</html>
OUTPUT
Both
335
100. WHAT IS THE USE OF XML?
• DTD file is similar to CSS file, because DTD also contains only styles.
• 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.
• This extensibility can result in naming collisions (i.e. different elements that have
the same name) among elements in an XML document.
336
103. WHAT ARE THE USES OF XML?
• SOAP is an XML based protocol that allows applications to easily over the
internet using XML documents called AOAP message.
• 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.)
• 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.
• 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.
• 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.
• 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)
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)
• 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)
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)
341
1. Draw form design
• Radio button
• Command button
• Check box
• List box
17. *** Explain in detail about all the types of Cascading Style sheet with an example
program(16 marks – page no. 140 -149)
342
18. ***Write short notes on the following.(16 marks – page no. 174 - 221)
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)
21. **** Discuss briefly about Dynamic HTML – Filters and Transitions (page no. 476 –
495 refer notes also)
22. *** Discuss briefly about Data Binding using any control for example
343
23. ** Discuss briefly the various servers (refer V th unit notes)
26. ** Explain the concept of Servlets with an example program ( Lab exercise)
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.
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.
5. HTTP server can serve an entire document tree, including images, applets, HTML
files, and more.
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.
345
18. public void removeValue(String name)
• 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.
• 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.
• 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.
• 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.
• The URLConnection class is intimately tied to Java’s protocol and content handler
mechanism.
• Based on the type of the content type responsible protocol is allocated by the protocol
handler.
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.
END OF UNIT II
UNIT III – SCRIPTING LANGUAGES
<HTML>
<HEAD>
<TITLE> This is the Title </TITLE>
</HEAD>
<BODY>
348
</BODY>
</HTML>
Note: All the tags in HTML program are optional, however the file should be saved in .html
extension.
TYPES OF LISTS
4. Unordered lists
5. Ordered lists
UNORDERED LISTS
TYPE:
EXAMPLE
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
5 CSE
6 IT
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
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.
HTML allows linking to other HTML documents as well as images. There are 3 attributes
that can be introduced in BODY tag.
351
EXTERNAL LINKS
SYNTAX
A HREF = “location name”> Hyper Text Message </A>
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
9. HREF – Takes the name of the .html file that s linked to the particular area on the
image.
HTML form provides several mechanisms to collect information from people viewing your
site. The syntax of the form is
• 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.
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
353
<FRAME SRC = “file1.html”>
<FRAME SRC = “file2.html”>
• Hence JavaScript works best with the Netscape suite of Client and Server products.
• In Server side scripting the script program is executed at Server Side the required
html program is sent to the client.
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
<HTML>
<HEAD>
<SCRIPT language = “JavaScript”>
<BODY>
<SCRIPT language = “JavaScript”>
• 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.
Array Methods
355
Join() – returns all elements of the array joined together as a single string.
• = = = 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”
OK – returns true
CANCEL – returns false
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.
• 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.
• 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.
• 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”>
<STYLE>
</HEAD>
<BODY>
write the body of program
</BODY>
</HTML>
• 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.
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.
• The element is represented as an object, and its various XHTML attributes become
properties that ca be manipulated by scripting.
• 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.
• Once it is available on the client, the data can be sorted and filtered in various ways.
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.
Note move previous and move next methods should be used before checking BOF(),
EOF() methods respectively.
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
onrowenter,onrowexit, Related to rows, executed when you enter into row, exit,
onrowsdelete,onrowsinserted delete and insert respectively.
• 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.
• The flipv and fliph filters mirror text or images vertically and horizontally.
<td> Text
</tr>
362
<td style = "filter: flipv fliph"> Text </td>
<td style = "filter: flipv"> Text </td>
</tr>
</table>
</body>
</html>
OUTPUT
Both
363
111. WHAT DO YOU MEAN BY DTD IN XML?
• DTD file is similar to CSS file, because DTD also contains only styles.
• 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.
• This extensibility can result in naming collisions (i.e. different elements that have
the same name) among elements in an XML document.
• SOAP is an XML based protocol that allows applications to easily over the
internet using XML documents called AOAP message.
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.)
• 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
• 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.
• RDBMS server that uses SQL to interact with and manipulate data.
• 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.
• 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
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)
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)
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)
• 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)
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)
• 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)
46. ***Write short notes on the following.(16 marks – page no. 174 - 221)
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)
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
54. ** Explain the concept of Servlets with an example program ( Lab exercise)
371