CS6501 IP Lecture Notes
CS6501 IP Lecture Notes
com
AIM
To explain Internet Programming concepts and related programming and scripting languages.
OBJECTIVES
• To describe basic Internet Protocols.
• Explain JAVA and HTML tools for Internet programming.
• Describe scripting languages – Java Script.
• Explain dynamic HTML programming.
• Explain Server Side Programming tools.
TEXT BOOKS
1. Deitel, Deitel and Nieto, ―Internet and World Wide Web – How to program‖,
Pearson
Education Publishers, 2000.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
REFERENCES
1. R. Krishnamoorthy & S. Prabhu, ―Internet and Java Programming‖, New Age International
Publishers, 2004.
2. Thomno A. Powell, ―The Complete Reference HTML and XHTML‖, fourth edition, Tata
McGraw Hill, 2003.
rd
3. Naughton, ―The Complete Reference – Java2‖, Tata McGraw-Hill, 3 edition, 1999.
UNIT I
BASIC NETWORK AND WEB CONCEPTS
Internet Standards
• While there are many standards organizations in the world, the two that produce most of other
standards relevant to network programming are Internet Engineering Task Force (IETF) and
World Wide Web Consortium (W3C).
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• It is a major source of proposals for protocol standards which are submitted to the Internet
Architecture Board (IAB) for final approval. The IETF meets three times a year and extensive
minutes are included in the IETF Proceedings.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• The Transmission Control Protocol (TCP) is one of the core protocols of the Internet Protocol
Suite. TCP is one of the two original components of the suite (the other being Internet Protocol,
or IP), so the entire suite is commonly referred to as TCP/IP.
• Whereas IP handles lower-level transmissions from computer to computer as a message makes its
way across the Internet, TCP operates at a higher level, concerned only with the two end systems,
for example a Web browser and a Web server.
• In particular, TCP provides reliable, ordered delivery of a stream of bytes from a program on one
computer to another program on another computer.
• Besides the Web, other common applications of TCP include e-mail and file transfer. Among
other management tasks, TCP controls segment size, flow control, and data exchange rate.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
maximum of 60 bytes, allowing for up to 40 bytes of options in the header. This field gets its
name from the fact that it is also the offset from the start of the TCP segment to the actual data.
• Reserved (4 bits) – for future use and should be set to zero
• Flags (8 bits) (aka Control bits) – contains 8 1-bit flags
• CWR (1 bit) – Congestion Window Reduced (CWR) flag is set by the sending host to
indicate that it received a TCP segment with the ECE flag set and had responded in
congestion control mechanism
• ECE (1 bit) – ECN-Echo indicates
• If the SYN flag is set, that the TCP peer is ECN capable.
• If the SYN flag is clear, that a packet with Congestion Experienced flag in IP header
set is received during normal transmission
• URG (1 bit) – indicates that the Urgent pointer field is significant
• ACK (1 bit) – indicates that the Acknowledgment field is significant. All packets after
the initial SYN packet sent by the client should have this flag set.
• PSH (1 bit) – Push function. Asks to push the buffered data to the receiving
application.
• RST (1 bit) – Reset the connection
• SYN (1 bit) – Synchronize sequence numbers. Only the first packet sent from each
end should have this flag set. Some other flags change meaning based on this flag, and
some are only valid for when it is set, and others when it is clear.
• FIN (1 bit) – No more data from sender
• Window (16 bits) – the size of the receive window, which specifies the number of bytes (beyond
the sequence number in the acknowledgment field) that the receiver is currently willing to receive
• Checksum (16 bits) – The 16-bit checksum field is used for error-checking of the header and data
• Urgent pointer (16 bits) – if the URG flag is set, then this 16-bit field is an offset from the
sequence number indicating the last urgent data byte
• Options (Variable 0-320 bits, divisible by 32) – The length of this field is determined by the data
offset field. Options 0 and 1 are a single byte (8 bits) in length. The remaining options indicate
the total length of the option (expressed in bytes) in the second byte
UDP
• The User Datagram Protocol (UDP) is one of the core members of the Internet Protocol Suite, the
set of network protocols used for the Internet.
• With UDP, computer applications can send messages, in this case referred to as datagram, to
other hosts on an Internet Protocol (IP) network without requiring prior communications to set up
special transmission channels or data paths.
• UDP is sometimes called the Universal Datagram Protocol. The protocol was designed by David
P.
• UDP uses a simple transmission model without implicit hand-shaking dialogues for guaranteeing
reliability, ordering, or data integrity. Thus, UDP provides an unreliable service and datagram
may arrive out of order, appear duplicated, or go missing without notice.
• UDP assumes that error checking and correction is either not necessary or performed in the
application, avoiding the overhead of such processing at the network interface level.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• Time-sensitive applications often use UDP because dropping packets is preferable to waiting for
delayed packets, which may not be an option in a real-time system.
Differences:
TCP:
• Connection oriented transport protocol
• Sends data as a stream of bytes
• Guarantee of delivery
UDP:
• Connection less protocol
• Datagram service
• No guarantee of delivery
URL
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• Uniform Resource Locator (URL) is a Uniform Resource Identifier (URI) that specifies where
an identified resource is available and the mechanism for retrieving it.
• The best-known example of a URL is the "address" of a web page on the World Wide Web,
e.g. http://www.example.com
• Every URL consists of some of the following: the scheme name (commonly called protocol),
followed by a colon, then, depending on scheme, a hostname (alternatively, IP address), a port
number, the path of the resource to be fetched or the program to be run, then, for programs such
as Common Gateway Interface (CGI) scripts, a query string, and with HTML documents, an
anchor (optional) for where the page should start to be displayed.
• The scheme name, or resource type, defines its namespace, purpose, and the syntax of the
remaining part of the URL. Most Web-enabled programs will try to dereference a URL according
to the semantics of its scheme and a context. For example, a Web browser will usually
dereference the URL http://example.org:80 by performing an HTTP request to the host
example.org, at the port number 80. Dereferencing the URN mailto:bob@example.com will
usually start an e-mail composer with the address bob@example.com in the To field.
• Other examples of scheme names include https:, gopher:, wais:, ftp:. URLs that specify https as a
scheme (such as https://example.com/) denote a secure website.
• The registered domain name or IP address gives the destination location for the URL. The
domain google.com, or its IP address 72.14.207.99, is the address of Google's website.
• The hostname and domain name portion of a URL are case-insensitive since the DNS is specified
to ignore case. http://en.wikipedia.org/ and HTTP://EN.WIKIPEDIA.ORG/ both open the same
page.
• The port number is optional; if omitted, the default for the scheme is used. For example, if
http://myvncserver.no-ip.org:5800 is typed into the address bar of a browser it will connect to
port 5800 of myvncserver.no-ip.org; this port is used by the VNC remote control program and
would set up a remote control session. If the port number is omitted a browser will connect to
port 80, the default HTTP port.
• The path is used to find the resource specified. It is case-sensitive, though it may be treated as
case-insensitive by some servers, especially those based on Microsoft Windows. If the server is
case sensitive and http://en.wikipedia.org/wiki/URL is correct,
http://en.wikipedia.org/WIKI/URL/ or http://en.wikipedia.org/wiki/url/ will display an HTTP 404
error page.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• The query string contains data to be passed to web applications such as CGI programs. The query
string contains name/value pairs separated by ampersands, with names and values in each pair
being separated by equal signs, for example first_name=John&last_name=Doe.
• The anchor part when used with HTTP specifies a location on the page. For example
http://en.wikipedia.org/wiki/URL#Syntax addresses the beginning of the Syntax section of the
page.
• On some sites, the anchor may have other functions; see: fragment identifier.
Absolute URL
• It is the complete path including the domain - file name. Example:
http://www.ip.com/images/logo.gif specifies an image file (logo.gif) located in the images
directory, for the www.ip.com domain. This type of URL is what your must use when you
want to link (or load) a file that is on another server.
• Another example is the absolute URL of this page (which is also the Address / Location of
the file) = http://www.ip.com/help/path/index.php
Relative URL
• A relative URL points to a file/directory in relation to the present file/directory
• example on a web server (where the web root is
public_html) Root (public_html)
.......index.html
.......top.gif
....images
......ibdhost.gif
....help
......path
........index.php (this page)
• For this page, the current page is the index.php file inside the path directory - inside the
help directory. Therefore, the relative path to this page is
/help/path/index.php
• Then to load the ibdhost.gif image (top left of this page), the relative path to the image is
../../images/ibdhost.gif
Which means the ibdhost.gif image is in a directory two levels up from this index.php file -
then down into the 'images' directory.
• The two dots .. instruct the server to move up one directory. Therefore two sets of ../../ moves
up two levels to the root directory (public_html) - then opens the images directory and loads the
ibdhost.gif file.
• if the image had been in the help directory the relative path would be ../help/imagename.jpg
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• This constructor sets the port to -1 so the default port for the protocol will be used. The file
argument should begin with a slash, and include a path, a filename, and optionally a reference to
a named anchor. Forgetting the initial slash is a common mistake, and one that is not easy to spot.
Like all URL constructors, it can throw a MalformedURLException.
• Example
try {
URL u = new URL("http", "www.eff.org", "/blueribbon.html#intro");
}
catch (MalformedURLException e)
{ // All VMs should recognize http
}
• This creates a URL object that points to http://www.eff.org/blueribbon.html#intro, using the
default port for the HTTP protocol (port 80). The file specification includes a reference to a
named anchor. The code catches the exception that would be thrown if the virtual machine did
not support the HTTP protocol. However, this shouldn't happen in practice.
• For those rare occasions when the default port isn't correct, the next constructor lets specify the
port explicitly, as an int:
public URL(String protocol, String host, int port, String file) throws MalformedURLException •
The other arguments are the same as for the URL(String protocol, String host,
String file) constructor and carry the same caveats.
Example 1:
try {
URL u = new URL("http", "lcsaxp.lcs.psu.edu", 1212, "/%3b&db=psu");
}
catch (MalformedURLException e) {
System.err.println(e);
}
This code creates a URL object that points to
http://lcsaxp.lcs.psu.edu:1212/%3b&db=psu,
Example 2:
The Parts of a URL
import java.net.*;
public class URLSplitter {
public static void main(String args[]) {
for (int i = 0; i < args.length; i++) {
try {
URL u = new URL(args[i]);
System.out.println("The URL is " + u);
System.out.println("The scheme is " + u.getProtocol( ));
System.out.println("The user info is " + u.getUserInfo( ));
String host = u.getHost( );
www.Vidyarthiplus.com
www.Vidyarthiplus.com
if (host != null) {
int atSign = host.indexOf('@');
if (atSign != -1)
host = host.substring(atSign+1);
System.out.println("The host is " + host);
}
else {
System.out.println("The host is null.");
}
System.out.println("The port is " + u.getPort( ));
System.out.println("The path is " + u.getPath( ));
System.out.println("The ref is " + u.getRef( ));
System.out.println("The query string is " + u.getQuery( ));
} // end try
catch (MalformedURLException e) { System.err.println(args[i] +
" is not a URL I understand.");
}
System.out.println( );
} // end
for } // end main
} // end URLSplitter
www.Vidyarthiplus.com
www.Vidyarthiplus.com
o audio
o video
o application-specific data.
spreadsheets
word processing documents
MIME Features
• Support of character sets other than ASCII
• Content type labeling System
• Support of non-text content in e-mail messages
• Support for compound documents
Content Labeling
• a set of registered MIME Types that map to specific file types
• MIME Types consist of :
a primary type
a sub type separated by a / ( as text/html)
• Common Mime Types:
FileExtension MIME Type Description
.txt text/plain Plain text
.htm text/html Styled text in HTML format
.jpg image/jpeg Picture in JPEG format
.gif image/gif Picture in GIF format
.wav audio/x-wave Sound in WAVE format
.mp3 audio/mpeg Music in MP3 format
.mpg video/mpeg Video in MPEG format
.zip application/zip Compressed file in PK-ZIP format
Non-text Content
• To be sent through the e-mail system non-textual content must be converted (encoded) to
ASCII for transmission and unencode back to its original format for display upon receipt.
• originally done via uuencode MIME uses base 64 encoding (RFC 2045)
www.Vidyarthiplus.com
www.Vidyarthiplus.com
binary to text encoding scheme
targets A-Z, a-z,0-9, +,/
scheme:
• take three byte of data, put into a 24 bit buffer
• extract 4 six bit values
• use each value as an index into:
o ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr
stuvwxyz0123456789+/
• this yields 4 ASCII characters
CGI
• "CGI" stands for "Common Gateway Interface." CGI is one method by which a web server can
obtain data from (or send data to) databases, documents, and other programs, and presents that
data to viewers via the web. More simply, a CGI is a program intended to be run on the web. A
CGI program can be written in any programming language, but Perl is one of the most popular
languages
• CGI is a standard for interfacing external applications with information servers, such as HTTP or
Web servers
• This interface provides a means for browsers and the server where document resides to
communicate and pass information back and forth
• Primarily, this is done through the <FORM> tag, but there can be other ways to use CGI
effectively, like through Server Side Includes (SSI)
• CGI, permits interactivity between a client and a host operating system through the World Wide
Web via the Hyper Text Transfer Protocol (HTTP)
• CGI program can be written in C or C++, Perl, ASP, PHP, Python, TCL, shells, and many others
languages and scripts
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• Database Interaction
an application of on-the-fly page creation. Web pages can be created using information
read from a database, or a web site form can allow a user to update database entries
• Logging / Counters
a log file can record traffic data updated with information on each visitor. A counter can
be included on the web page to advertise traffic.
• Animation
"server-push" programs can be used to feed the client successive images in an animated
sequence.
• Catalogs, Search engines
CGI programs
• Obtaining input from a user or from a data file.
• Storing that input in program variables.
• Manipulating those variables to achieve some desired purpose, and
• Sending the results to a file or video display.
EnvironmentVariables
• In order to pass data from the server to the script, the server uses command line arguments
along with environment variables.
• The Environment Variables are set when the server executes a CGI Script.
• Environment Variables allow the CGI Script to reference variables that might be wanted for
the Script output.
• There are two types of environment variables:
• Non-Request specific variables - those set for every request
• Request specific variables - those that are dependent on the request being fulfilled by the CGI
Script
www.Vidyarthiplus.com
www.Vidyarthiplus.com
‖ Advantages
• They are language independent .CGI programs can be written in any language that allows one
to write normal programs since they are executed in the same way as the normal programs.
• it's a very simple interface . It's not necessary to have any special library to create a CGI program, or
write programs using a particular API. Instead, CGI programs rely on the standard concepts of
standard input, standard output, and environment variables to communicate with the Web server.
Disadvantages
• CGI programs are slow since they need to fork a new process for every HTTP request and the
database connection must be reopened for the next instance of the program, which is quite costly
Example program:
myscript.html
<HTML>
<BODY>
<FORM METHOD="POST" ACTION="/cgi-
bin/myscript.cgi"> <PRE>
First Name <INPUT TYPE="text" NAME="fname" MAXLENGTH=15 SIZE=15>
Last Name <INPUT TYPE="text" NAME="lname" MAXLENGTH=20 SIZE=20>
E-Mail Addr <INPUT TYPE="text" NAME="email" MAXLENGTH=35 SIZE=35>
<INPUT TYPE="submit" VALUE="Send Mail!">
<INPUT TYPE="reset" value=" Clear-Form">
</PRE>
</FORM>
</BODY>
</HTML>
myscript.cgi
#!/usr/local/bin/perl
read(STDIN,$temp,$ENV{'CONTENT_LENGTH'});
@pairs=split(/&/,$temp);
foreach $item(@pairs)
{
($key,$content)=split(/=/,$item,2);
$content=~tr/+/ /;
$content=~s/%(..)/pack("c",hex($1))/ge;
www.Vidyarthiplus.com
www.Vidyarthiplus.com
$fields{$key}=$content;
}
print "Content-type:
text/html\n\n"; print "<HTML>\n";
print "<BODY BGCOLOR=#FFFFFF>\n";
print "<CENTER>\n";
print "THANK YOU<BR>\n";
print "$fields{fname} $fields{lname}</BR>";
print "I will write<BR>\n";
print "you at<BR>\n";
print "$fields{email}<BR>\n";
print "</CENTER>\n";
print "</BODY></HTML>";
Introduction to SGML
• Standard Generalized Markup Language
• Strictly descriptive
• Contains no means to mark up presentational aspects of documents
• Can be easily interfaced to external procedural markup systems and style sheets
• Like HTML, SGML is a computer language rather than a data format
• SGML files can be created manually, or through SGML editor software tools.
• SGML is a meta-language that defines only the syntax of a standard generalised markup
language, i.e. is prescribes how we should specify markup, but not what that markup is, nor what
it means.
SGML Parser
• Software that reads and analyzes an SGML document
• Validation or transformation
• Not much use by itself
• Part of a bigger SGML application system or browser
SGML History
• More than 10 years history of use and growth…
Widely used-
• publishing andaerospace, automotive, defense, software, semiconductor, pharmaceutical,
other industries
• ISO standard (ISO 8879) – adopted by several other standards bodies
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Descriptive markup
• Use of markup codes (names) to categorize parts of a document
• Example: <para> to identify a paragraph
• Advantage: Same document can be processed by different software for different purposes
Document Type
• Notion of ‗document type‘ (hence DTD)
• Type of a document is formally defined by its constituent parts and their structure – expressed in
a tree structure
• Example: Report
Title, followed by author (optional), abstract, one or more paragraphs
• If title is absent, it is not a report
• If abstract follows paragraphs, it is not a report
Data Independence
• Document portability across different HW and SW environments
• How to handle character set differences
• Descriptive mapping for non-portable characters
• String substitution mechanism (entities): process time substitution of a particular string of
characters by other string of characters
Defining an SGML Application
• From SGML view, a document is a hierarchical structure of nested elements (chapters,
sections, paragraphs, etc.)
• SGML does not specify any presentational aspects of these elements
• SGML also does not convey any meaning or role of these elements – meaning is implied by the
application
• SGML specifies the contexts and levels of document hierarchy in which an element can or must
occur
• All documents that can be marked up with the same hierarchy of elements are said to belong to a
certain document type
• SGML defines the structure of a particular type of documents via the DTD (Document Type
Definition)
• Some general features of an SGML application are specified in another component called SGML
Declaration.
• SGML Syntax:
• SGML statements are enclosed in angle brackets (<>) and contain a keyword or name
followed by one or more parameters separated by spacesCharacter ‗!‘ is inserted between
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Disadvantages of SGML:
• Creating DTD's requires exacting software engineering
• Linking tends to be complex
• Writing SGML software is extremely hard
• SGML tools tend to be expansive
UNIT II
JAVA PROGRAMMING
Java basics
• Java is a programming language originally developed by James Gosling at Sun Microsystems.
Java applications are typically compiled to byte code (class file) that can run on any Java Virtual
Machine (JVM) regardless of computer architecture.
• It is intended to let application developers "write once, run anywhere". Java is general-purpose,
concurrent, class-based, and object-oriented language.
Variables
• Local Variables
Similar to how an object stores its state in fields, a method will often store its temporary state
in local variables. The syntax for declaring a local variable is similar to declaring a field (for
example, int count = 0;).
‖ There is no special keyword designating a variable as local; that determination comes entirely
www.Vidyarthiplus.com
www.Vidyarthiplus.com
from the location in which the variable is declared — which is between the opening and
closing braces of a method.
Local variables are only visible to the methods in which they are declared; they are not accessible from the
rest of the class.
• Instance Variables (Non-Static Fields)
Objects store their individual states in "non-static fields", that is, fields declared without the static keyword.
Non-static fields are also known as instance variables because their values are unique to each instance of a
class (to each object, in other words
• Class Variables (Static Fields)
A class variable is any field declared with the static modifier; this tells the compiler that there
is exactly one copy of this variable in existence, regardless of how many times the class has
been instantiated.
Operators
• Operators are special symbols that perform specific operations on one, two, or three operands,
and then return a result.
• The closer to the top of the table an operator appears, the higher its precedence. Operators with
higher precedence are evaluated before operators with relatively lower precedence. Operators on
the same line have equal precedence. When operators of equal precedence appear in the same
expression, a rule must govern which is evaluated first.
• All binary operators except for the assignment operators are evaluated from left to right;
assignment operators are evaluated right to left.
Operator Precedence
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative */%
additive +-
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• The assignment operator "=" is far more common than the unsigned right shift operator ">>>".
The signed left shift operator "<<" shifts a bit pattern to the left and the signed right shift
operator ">>" shifts a bit pattern to the right.
• The bit pattern is given by the left-hand operand and the number of positions to shift by the right-
hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position,
while the leftmost position after ">>" depends on sign extension.
• The instanceof operator compares an object to a specified type. You can use it to test if an object
is an instance of a class, an instance of a subclass, or an instance of a class that implements a
particular interface.
• The following program, InstanceofDemo, defines a parent class (named Parent), a simple
interface (named MyInterface), and a child class (named Child) that inherits from the parent and
implements the interface.
class InstanceofDemo {
public static void main(String[] args)
{ Parent obj1 = new Parent();
Parent obj2 = new Child();
System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child));
System.out.println("obj1 instanceof MyInterface: "+(obj1 instanceof
MyInterface)); System.out.println("obj2 instanceof Parent: " + (obj2 instanceof
Parent)); System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child));
System.out.println("obj2 instanceof MyInterface: "+(obj2 instanceof
MyInterface));
}
}
class Parent{}
class Child extends Parent implements
MyInterface{} interface MyInterface{}
Output:
obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface:
false obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true
When using the instanceof operator, keep in mind that null is not an instance of anything.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• they appear.
‖ Control flow statements, however,
break up the flow of execution by
employing decision making,
looping, and branching, enabling
your program to conditionally
execute particular blocks of code.
• The Control Flow Statements are decision-making statements (if-then, if-then-else, switch), the
looping statements (for, while, do-while), and the branching statements (break, continue, return)
supported by the Java programming language.
I/O streaming
• A stream is an abstraction that either produces or consumes information. A stream is linked to a
physical device by the Java I/O system.
• Java 2 defines two types of streams: byte and character.
• Byte streams provide a convenient means for handling input and output of bytes. Byte streams are
used, for example, when reading or writing binary data. two abstract classes are InputStream and
OutputStream.
• Character streams provide a convenient means for handling input and output of characters. Two
abstract classes are Reader and Writer. These abstract classes handle Unicode character streams.
• The package needed is java.io
Byte Streams
• The byte stream classes provide a rich environment for handling byte-oriented I/O.
• A byte stream can be used with any type of object, including binary data. This versatility makes
byte streams important to many types of programs.
Input Streams
• Input streams read the bytes of data.
• Java's basic input class is java.io.InputStream
Methods
• public abstract int read( ) throws IOException
• public int read(byte[] input) throws IOException
• public int read(byte[] input, int offset, int length) throws IOException
• public long skip(long n) throws IOException
• public int available( ) throws IOException
• public void close( ) throws IOException
Output Streams
• Output streams write the bytes of data.
• Java's basic output class is java.io.OutputStream
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Methods
• public abstract void write(int b) throws IOException
• public void write(byte[] data) throws IOException
• public void write(byte[] data, int offset, int length) throws IOException
• public void flush( ) throws IOException
• public void close( ) throws IOException
FileInputStream
• The FileInputStream class creates an InputStream that you can use to read bytes from a file.
Example
import java.io.*;
class FISDemo {
public static void main(String args[]) throws Exception
{ int size;
InputStream f = new FileInputStream("input.txt");
System.out.println("Total Available Bytes: " +(size =
f.available())); int n = size;
for (int i=0; i < n; i++) {
System.out.print((char) f.read());
}
}
}
FileOutputStream
• FileOutputStream creates an OutputStream that you can use to write bytes to a file.
• Its constructors are
FileOutputStream (String filePath)
FileOutputStream (File fileObj)
• Creation of a FileOutputStream is not dependent on the file already existing.
FileOutputStream will create the file before opening it for output when you create the object.
In the case where you attempt to open a read-only file, an IOException will be thrown.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Example
import java.io.*;
class FOSDemo {
public static void main(String args[]) throws Exception {
String source = "This is the program to demonstrate file output
stream‖; byte buf[] = source.getBytes();
OutputStream f0 = new FileOutputStream
("file1.txt"); for (int i=0; i < buf.length; i += 2) {
f0.write (buf[i]);
}
f0.close ();
OutputStream f1 = new FileOutputStream
("file2.txt"); f1.write(buf);
f1.close();
}
ByteArrayInputStream
• ByteArrayInputStream is an implementation of an input stream that uses a byte array as the
source.
• This class has two constructors, each of which requires a byte array to provide the data source
ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start, int numBytes)
Example
import java.io.*;
class BAISDemo {
public static void main(String args[]) throws IOException
{ String tmp = "abc";
byte b[] = tmp.getBytes();
ByteArrayInputStream in = new
ByteArrayInputStream(b); for (int i=0; i<2; i++) {
int c;
while ((c = in.read()) != -1)
{ if (i == 0) {
System.out.print((char) c);
} else {
System.out.print(Character.toUpperCase((char) c));
}
}
System.out.println();
in.reset();
}
www.Vidyarthiplus.com
www.Vidyarthiplus.com
}
}
• This example first reads each character from the stream and prints it as is, in lowercase. It then
resets the stream and begins reading again, this time converting each character to uppercase
before printing. The output is:
abc
ABC
ByteArrayOutputStream
• ByteArrayOutputStream is an implementation of an output stream that uses a byte array as the
destination.
• ByteArrayOutputStream has two constructors
ByteArrayOutputStream( )
ByteArrayOutputStream(int numBytes)
• In the first constructor, a buffer of 32 bytes is created. In the second, a buffer is created with a
size equal to that specified by numBytes.
Example
import java.io.*;
class ByteArrayOutputStreamDemo {
public static void main(String args[]) throws IOException {
ByteArrayOutputStream f = new ByteArrayOutputStream();
String s = "This should end up in the array";
byte buf[] = s.getBytes();
f.write(buf);
System.out.println("Buffer as a string");
System.out.println(f.toString());
System.out.println("Into array");
byte b[] = f.toByteArray(); for
(int i=0; i<b.length; i++) {
System.out.print((char) b[i]);
}
System.out.println("\nTo an OutputStream()");
OutputStream f2 = new FileOutputStream
("test.txt"); f.writeTo(f2);
f2.close ();
System.out.println("Doing a
reset"); f.reset();
for (int i=0; i<3; i++)
f.write('X');
System.out.println(f.toString());
}
}
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• When you run the program, you will create the following output. Notice how after the call to reset (
), the three X’s end up at the beginning.
Buffer as a string
This should end up in the
array Into array
This should end up in the
array To an OutputStream ()
Doing a reset
XXX
Character Streams
• While the byte stream classes provide sufficient functionality to handle any type of I/O operation,
they cannot work directly with Unicode characters.
• Since one of the main purposes of Java is to support the ―write once, run anywhere‖
philosophy, it was necessary to include direct I/O support for characters.
Reader
• Reader is an abstract class that defines Java‘s model of streaming character input.
Methods
• abstract void close( ) Closes the input source. Further read attempts will generate an IOException.
• void mark(int numChars) Places a mark at the current point in the input stream that will remain
valid until numChars characters are read.
• boolean markSupported( ) Returns true if mark( )/reset( ) are supported on this stream.
• int read( ) Returns an integer representation of the next available character from the invoking
input stream. –1 is returned when the end of the file is encountered.
• int read(char buffer[ ]) Attempts to read up to buffer.length characters into buffer and returns the
actual number of characters that were successfully read. –1 is returned when the end of the file is
encountered.
• abstract int read(char buffer[ ], int offset, int numChars) Attempts to read up to numChars
characters into buffer starting at buffer[offset], returning the number of characters successfully
read. –1 is returned when the end of the file is encountered.
• boolean ready( ) Returns true if the next input request will not wait. Otherwise, it returns false.
• void reset( ) Resets the input pointer to the previously set mark.
• long skip(long numChars) Skips over numChars characters of input, returning the number of
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Writer
• Writer is an abstract class that defines streaming character output.
Methods
• abstract void close ( ) Closes the output stream. Further write attempts will generate an
IOException.
• abstract void flush ( ) Finalizes the output state so that any buffers are cleared. That is, it flushes
the output buffers.
• void write(int ch) Writes a single character to the invoking output stream. Note that the parameter
is an int, which allows you to call write with expressions without having to cast them back to
char.
• void write(char buffer[ ]) Writes a complete array of characters to the invoking output stream.
• abstract void write(char buffer[ ], int offset, int numChars) Writes a subrange of numChars
characters from the array buffer, beginning at buffer[offset] to the invoking output stream.
• void write(String str) Writes str to the invoking output stream.
• void write(String str, int offset, int numChars) Writes a subrange of numChars characters from
the array str, beginning at the specified offset.
FileReader
• The FileReader class creates a Reader that you can use to read the contents of a file.
• Its constructors are
FileReader (String filePath)
FileReader (File fileObj)
• Either can throw a FileNotFoundException. Here, filePath is the full path name of a file, and
fileObj is a File object that describes the file.
Example
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null)
{ System.out.println(s);
}
fr.close();
}
}
FileWriter
• FileWriter creates a Writer that you can use to write to a file.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Example
import java.io.*;
class FileWriterDemo {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good men\n"
+ " to come to the aid of their country\n"
+ " and pay their due taxes.";
char buffer[] = new char[source.length()];
source.getChars(0, source.length(), buffer, 0);
FileWriter f0 = new FileWriter("file1.txt"); for
(int i=0; i < buffer.length; i += 2) {
f0.write(buffer[i]);
}
f0.close();
FileWriter f1 = new
FileWriter("file2.txt"); f1.write(buffer);
f1.close();
FileWriter f2 = new FileWriter("file3.txt");
f2.write(buffer,buffer.length-
buffer.length/4,buffer.length/4); f2.close();
}
}
• This example creates a sample buffer of characters by first making a String and then using the
getChars( ) method to extract the character array equivalent. It then creates three files.
• The first, file1.txt, will contain every other character from the sample. The second, file2.txt, will
contain the entire set of characters. Finally, the third, file3.txt, will contain only the last quarter.
CharArrayReader
• CharArrayReader is an implementation of an input stream that uses a character array as the
source.
• This class has two constructors, each of which requires a character array to provide the data
source:
CharArrayReader (char array [ ])
CharArrayReader (char array [ ], int start, int numChars)
• Here, array is the input source. The second constructor creates a Reader from a subset of your
character array that begins with the character at the index specified by start and is numChars long.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Example
import java.io.*;
public class CharArrayReaderDemo {
public static void main(String args[]) throws IOException
{ String tmp = "abcdefghijklmnopqrstuvwxyz";
int length = tmp.length();
char c[] = new char[length];
tmp.getChars(0, length, c, 0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 0,
5); int i;
System.out.println("input1 is:");
while((i = input1.read()) != -1) {
System.out.print((char)i);
}
System.out.println();
System.out.println("input2 is:");
while((i = input2.read()) != -1) {
System.out.print((char)i);
}
System.out.println();
}
• The input1 object is constructed using the entire lowercase alphabet, while input2 contains only
the first five letters. Here is the output:
input1 is:
abcdefghijklmnopqrstuvwxyz
input2 is:
abcde
CharArrayWriter
• CharArrayWriter is an implementation of an output stream that uses an array as the destination.
• CharArrayWriter has two constructors,
CharArrayWriter ( )
CharArrayWriter (int numChars)
• In the first form, a buffer with a default size is created. In the second, a buffer is created with a
size equal to that specified by numChars. The buffer is held in the buf field of CharArrayWriter.
The buffer size will be increased automatically, if needed.
Example
import java.io.*;
www.Vidyarthiplus.com
www.Vidyarthiplus.com
class CharArrayWriterDemo {
public static void main(String args[]) throws IOException
{ CharArrayWriter f = new CharArrayWriter ();
String s = "This should end up in the array";
char buf[] = new
char[s.length()]; s.getChars(0,
s.length(), buf, 0); f.write(buf);
System.out.println ("Buffer as a string");
System.out.println (f.toString());
System.out.println ("Into array");
char c[] = f.toCharArray(); for
(int i=0; i<c.length; i++) {
System.out.print(c[i]);
}
System.out.println ("\nTo a FileWriter ()");
FileWriter f2 = new FileWriter ("test.txt");
f.writeTo(f2);
f2.close();
System.out.println ("Doing a
reset"); f.reset();
for (int i=0; i<3; i++)
f.write('X');
System.out.println(f.toString());
}
}
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Files
• A File object is used to obtain or manipulate the information associated with a disk file, such as
the permissions, time, date, and directory path, and to navigate subdirectory hierarchies.
• constructors used to create File objects:
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URI uriObj)
Example:
import java.io.File;
class FileDemo {
public static void main(String args[]) {
File f1 = new File("/ip/test");
System.out.println ("File Name: " + f1.getName());
System.out.println ("Path: " + f1.getPath());
System.out.println ("Abs Path: " + f1.getAbsolutePath());
System.out.println ("Parent: " + f1.getParent());
System.out.println (f1.exists() ? "exists" : "does not exist");
System.out.println (f1.canWrite() ? "is writeable" : "is not writeable");
System.out.println (f1.canRead() ? "is readable" : "is not readable");
System.out.println ("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
System.out.println (f1.isFile() ? "is normal file" : "might be a named
pipe"); System.out.println (f1.isAbsolute() ? "is absolute" : "is not
absolute"); System.out.println ("File last modified: " + f1.lastModified());
System.out.println ("File size: " + f1.length() + " Bytes");
}
}
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
InetAddress Class
Example
1. Program that prints the address of www.oreilly.com
import java.net.*;
public class OReillyByName {
public static void main (String[] args)
{ try {
InetAddress address = InetAddress.getByName("www.oreilly.com");
System.out.println(address);
}
catch (UnknownHostException e) { System.out.println("Could
not find www.oreilly.com");
}
}
}
% java OReillyByName
www.oreilly.com/204.148.40.9
import java.net.*;
public class OReillyByAddress {
public static void main (String[] args)
{ try {
InetAddress address = InetAddress.getByName("204.148.40.9");
System.out.println (address);
}
catch (UnknownHostException e) {
System.out.println ("Could not find 204.148.40.9");
}}}
www.Vidyarthiplus.com
www.Vidyarthiplus.com
% java OReillyByAddress
helio.ora.com/204.148.40.9
import java.net.*;
public class AllAddressesOfMicrosoft { public
static void main (String[] args) {
try {
InetAddress[] addresses =
InetAddress.getAllByName("www.microsoft.com");
for (int i = 0; i < addresses.length; i++) {
System.out.println(addresses[i]);
}
}
catch (UnknownHostException e) {
System.out.println("Could not find www.microsoft.com");
}
}
}
% java AllAddressesOfMicrosoft
www.microsoft.com/207.46.131.15
www.microsoft.com/207.46.131.137
www.microsoft.com/207.46.130.14
www.microsoft.com/207.46.130.149
www.microsoft.com/207.46.130.150
www.microsoft.com/207.46.131.13
import java.net.*;
public class MyAddress {
public static void main (String[] args)
{ try {
InetAddress address = InetAddress.getLocalHost( );
System.out.println(address);
}
catch (UnknownHostException e) {
System.out.println("Could not find this computer's address.");
}
}
}
if ran the program on titan.oit.unc.edu:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
% java MyAddress
titan.oit.unc.edu/152.2.22.14
Socket programming
Sockets for Clients
A socket is a connection between two hosts.
Operations
• The program creates a new socket with a Socket ( ) constructor.
• The socket attempts to connect to the remote host.
• Once the connection is established, the local and remote hosts get input and output
streams from the socket and use those streams to send data to each other. This connection
is full-duplex; both hosts can send and receive data simultaneously.
• When the transmission of data is complete, one or both sides close the connection.
Constructors
1. public Socket (String host, int port) throws UnknownHostException, IOException
This constructor creates a TCP socket to the specified port on the specified host
and attempts to connect to the remote host.
Example: Find out which of the Ports at or Above 1,024 Seem to Be Hosting TCP Server
import java.net.*;
import java.io.*;
public class PortScanner {
public static void main(String[] args) {
String host = "localhost";
if (args.length > 0) {
host = args[0];
}
try {
InetAddress theAddress = InetAddress.getByName(host);
for (int i = 1024; i < 65536; i++) {
try {
Socket theSocket = new Socket(theAddress, i);
System.out.println("There is a server on port "
+ i + " of " + host);
}
catch (IOException e) {
// must not be a server on this port }} // end for
www.Vidyarthiplus.com
www.Vidyarthiplus.com
} // end try
catch (UnknownHostException e)
{ System.err.println(e);
}
} // end main
} // end PortScanner
www.Vidyarthiplus.com
www.Vidyarthiplus.com
constructor.
• 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 the server.
• 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.
• The server and the client interact according to an agreed-upon protocol until it is time to
close the connection.
• The server, the client, or both close the connection.
• The server returns to step 2 and waits for the next connection.
Constructors
1. public ServerSocket(int port) throws IOException, BindException
2. public ServerSocket(int port, int queueLength) throws IOException, BindException
3. public ServerSocket(int port, int queueLength, InetAddress bindAddress)
throws IOException
import java.net.*;
import java.io.*;
public class LocalPortScanner {
public static void main(String[] args) {
for (int port = 1; port <= 65535; port++)
{ try {
// the next line will fail and drop into the catch block if
// there is already a server running on the port
ServerSocket server = new ServerSocket(port);
}
catch (IOException e) {
System.out.println("There is a server on port " + port + ".");
} // end try
} // end for
}
}
The program checks for ports on the local machine by attempting to create ServerSocket
objects on them and seeing on which ports that fails.
Datagram Packet
UDP datagram is represented by an instance of the DatagramPacket
class public final class DatagramPacket extends Object
Constructors
Receiving datagram
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Sending datagram
1. public DatagramPacket(byte[] data, int length, InetAddress destination, int port)
2. public DatagramPacket(byte[] data, int offset, int length, InetAddress destination, int port)
Each constructor creates a new DatagramPacket to be sent to another host. The packet is filled
with length bytes of the data array starting at offset or if offset is not used. If you try to construct a
DatagramPacket with a length that is greater than data.length, the constructor throws an
IllegalArgumentException.
Datagram Socket
To send or receive a Datagram Packet, need to open a datagram socket.
Constructors
1. public DatagramSocket( ) throws SocketException
This constructor creates a socket that is bound to an anonymous port.
TCPServer.java
import java.net.*;
import java.io.*;
www.Vidyarthiplus.com
www.Vidyarthiplus.com
TCPClient import
java.io.*; import
java.net.*;
public class TCPClient
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket (InetAddress.getLocalHost(),1500);
BufferedReader br = new BufferedReader (new InputStreamReader (S.getInputStream ( ) )
); String getData ;
while (getData = br.readLine ( )!= null)
{
System.out.println (get Data);
}}
}
Example: 2
• The program opens a DatagramSocket on that port and creates a DatagramPacket with a 65,507-
byte buffer—large enough to receive any possible packet.
• Then the server enters an infinite loop that receives packets and prints the contents and the
originating host on the console.
UDP Client
import java.net.*;
www.Vidyarthiplus.com
www.Vidyarthiplus.com
import java.io.*;
public class UDPClient {
public static void main(String[] args)
{ String hostname;
int port = 9;
if (args.length > 0) {
hostname = args[0];
}
else {
hostname = "localhost";
}
try {
InetAddress server = InetAddress.getByName(hostname);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket theSocket = new DatagramSocket( );
while (true) {
String theLine = userInput.readLine( );
if (theLine.equals(".")) break;
byte[] data = theLine.getBytes( );
DatagramPacket dp = new DatagramPacket(data, data.length, server,
port); theSocket.send(theOutput);
} // end while
} // end try
catch (UnknownHostException e) {
System.err.println(e);
}
catch (SocketException se) {
System.err.println(se);
}
catch (IOException e) {
System.err.println(e);
}
} // end main
}
UDPServer
import java.net.*;
import java.io.*;
public class UDPServer {
public static void main(String[] args)
{ int port = 9;
byte[] buffer = new
byte[65507]; try {
DatagramSocket server = new DatagramSocket(port);
DatagramPacket packet = new DatagramPacket(buffer,
buffer.length); while (true) {
www.Vidyarthiplus.com
www.Vidyarthiplus.com
try {
server.receive(packet);
String s = new String(packet.getData(), 0,packet.getLength( ));
System.out.println(packet.getAddress( ) + " at port " + packet.getPort( ) + "
says + s);
// reset the length for the next packet
packet.setLength(buffer.length);
}
catch (IOException e) {
System.err.println(e);
}
} // end
while } // end try
catch (SocketException se) {
System.err.println(se);
} // end catch
} // end main
}
E-mail Client
• An email client, email reader, or more formally mail user agent (MUA), is a computer program
used to manage email.
• The term email client may refer to any agent acting as a client toward an email server, regardless
of it being a mail user agent, a relaying server, or a human typing on a terminal.
• A web application providing message management, composition, and reception functionality is
sometimes considered an email client.
Retrieving messages from a mailbox
• Like most client programs, an MUA is only active when a user runs it. Messages arrive on the
Mail Transfer Agent (MTA) server.
• Unless the MUA has access to the server's disk, messages are stored on a remote server and the
MUA has to request them on behalf of the user.
• In the first case, shared disk, a user logs on a server and runs an MUA on that machine. The
MUA reads messages from a conventionally formatted storage, typically mbox, within the user's
HOME directory.
• The MTA uses a suitable mail delivery agent (MDA) to add messages to that storage, possibly in
concurrence with the MUA. This is the default setting on many UNIX systems. Web mail
applications running on the relevant server can also benefit from direct disk access to the mail
storage.
• For personal computing, and whenever messages are stored on a remote system, a mail user agent
connects to a remote mailbox to retrieve messages.
• Access to remote mailboxes comes in two flavors. On the one hand, the Post Office Protocol
(POP) allows the client to download messages one at a time and only delete them from the server
after they have been successfully saved on local storage. It is possible to leave messages on the
server in order to let another client download them. However, there is no provision for flagging a
www.Vidyarthiplus.com
www.Vidyarthiplus.com
specific message as seen, answered, or forwarded, thus POP is not convenient for users who
access the same mail from different machines or clients.
• On the other hand, the Internet Message Access Protocol (IMAP) allows users to keep messages
on the server, flagging them as appropriate. IMAP provides sub-folders. Typically, the Sent,
Drafts, and Trash folders are created by default.
• Both POP and IMAP clients can be configured to access more mailboxes at the same time, as
well as to check each mailbox every given number of minutes. IMAP features an idle extension
for real time updates, providing faster notification than polling where long lasting connections are
feasible.
• Client settings require the server's name or IP address, and the user name and password for each
remote incoming mailbox.
Formatting messages
• Mail user agents usually have built-in the ability to display and edit text. Editing HTML text is a
popular feature. Invoking an external editor may be an alternative.
• MUAs responsibilities include proper formatting according to RFC 5322 for headers and body,
and MIME for non-textual content and attachments.
• Headers include the destination fields, To, Cc, and Bcc, and the originator fields from which is
the message's author(s), Sender in case there are more authors and Reply-To in case responses
should be addressed to a different mailbox.
• To better assist the user with destination fields, many clients maintain one or more address books
and/or are able to connect to an LDAP directory server. For originator fields, clients may support
different identities.
• Client settings require the user's real name and email address for each user's identity, and possibly
a list of LDAP servers.
Submitting messages to a server
• An MUA is able to introduce new messages in the transport system. Typically, it does so by
connecting to either an MSA or an MTA, two variations of the SMTP protocol.
• The client needs to put a message quickly without worrying about where the message eventually
will be delivered: that's why a transport system exists. Thus it always connects to the same
preferred server, however, how does that server know that it should accept and relay submissions
from that client.
• There are two ways. The older method recognizes the client's IP address, e.g. because the client is
on the same machine and uses internal address 127.0.0.1, or because the client's IP address is
controlled by the same internet service provider that provides both internet access and mail
services.
• The newer method, since the SMTP protocol has an authentication extension, is to authenticate.
The latter method eases modularity and nomadic computing.
• Client settings require the name or IP address of the preferred outgoing mail server, the port
number (25 for MTA, 587 for MSA), and the user name and password for the authentication, if
any.
• There is a non-standard port 465 for SSL encrypted SMTP sessions, that many clients and servers
support for backward compatibility. Transport Layer Security encryption can be configured for
the standard ports, if both the client and the server support it.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Encryption
• Email encryption enables to safeguard privacy by encrypting the mail sessions, the body of the
message, or both.
• Without it, anyone (examples: the government (warrantless wiretapping, great firewall of China),
fellow wireless network users such as at an Internet cafe or other public network, whether the
network is open or not) with network access and the right tools can monitor email and obtain
login passwords.
Port numbers
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• Email servers and client use the following TCP port numbers by default, unless configured for
specialized installations:
• An application that runs on a personal computer or workstation and enables you to send, receive
and organize e-mail. It's called a client because e-mail systems are based on a client-server
architecture. Mail is sent from many clients to a central server, which re-routes the mail to its
intended destination.
SMTP
• Simple Mail Transfer Protocol is a protocol for sending e-mail messages between servers or
between a mail client and a server.
• Most e-mail systems that send mail over the Internet use SMTP to send messages from one server
to another; the messages can then be retrieved with an e-mail client using either POP or IMAP.
• It works on port 25.
• SMTP is a text-based protocol, in which a mail sender communicates with a mail receiver by
issuing command strings and supplying necessary data over a reliable ordered data stream
channel, typically a Transmission Control Protocol (TCP) connection.
• An SMTP session consists of commands originated by an SMTP client (the initiating agent,
sender, or transmitter) and corresponding responses from the SMTP server (the listening agent, or
receiver) so that the session is opened, and session parameters are exchanged. A session may
include zero or more SMTP transactions.
• An SMTP transaction consists of three command/reply sequences. They are:
1. MAIL command, to establish the return address, a.k.a. Return-Path, 5321.From, mfrom, or
envelope sender. This is the address for bounce messages.
2. RCPT command, to establish a recipient of this message. This command can be issued
multiple times, one for each recipient. These addresses are also part of the envelope.
3. DATA to send the message text. This is the content of the message, as opposed to its envelope.
It consists of a message header and a message body separated by an empty line. DATA is actually
a group of commands, and the server replies twice: once to the DATA command proper, to
acknowledge that it is ready to receive the text, and the second time after the end-of-data
sequence, to either accept or reject the entire message.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• A typical example of sending a message via SMTP to two mailboxes (alice and theboss) located
in the same mail domain (example.com) is reproduced in the following session exchange.
• The protocol exchanges are prefixed for the server (S:) and the client (C:). After the message
sender (SMTP client) establishes a reliable communications channel to the message receiver
(SMTP server), the session is opened with a greeting by the server, usually containing its fully
qualified domain name (FQDN), in this case smtp.example.com.
• The client initiates its dialog by responding with a HELO command identifying itself in the
command's parameter with its FQDN (or an address literal if none is available)
S: 220 smtp.example.com ESMTP
Postfix C: HELO relay.example.org
S: 250 Hello relay.example.org, I am glad to meet
you C: MAIL FROM:<bob@example.org>
S: 250 Ok
C: RCPT TO:<alice@example.com>
S: 250 Ok
C: RCPT TO:<theboss@example.com>
S: 250 Ok
C: DATA
S: 354 End data with <CR><LF>.<CR><LF> C:
From: "Bob Example" <bob@example.org> C:
To: "Alice Example" <alice@example.com> C:
Cc: theboss@example.com
C: Date: Tue, 15 Jan 2008 16:02:43 -0500
C: Subject: Test message
C:
C: Hello Alice.
C: This is a test message with 5 header fields and 4 lines in the message
body. C: Your friend,
C: Bob
C: .
S: 250 Ok: queued as 12345
C: QUIT
S: 221 Bye
{The server closes the connection}
• The client notifies the receiver of the originating email address of the message in a MAIL FROM
command. In this example, the email message is sent to two mailboxes on the same SMTP
server: one each for each recipient listed in the To and Cc header fields.
• The corresponding SMTP command is RCPT TO. Each successful reception and execution of a
command is acknowledged by the server with a result code and response message (e.g., 250 Ok).
• The transmission of the body of the mail message is initiated with a DATA command after which
it is transmitted verbatim line by line and is terminated with an end-of-data sequence. This
consists of a new-line (<CR><LF>), a single full stop (period), followed by another new-line.
• Since a message body can contain a line with just a period as part of the text, the client sends two
periods every time a line starts with a period; correspondingly, the server replaces every sequence
www.Vidyarthiplus.com
www.Vidyarthiplus.com
of two periods at the beginning of a line with a single one. Such escaping method is called dot-
stuffing.
• The server's positive reply to the end-of-data, as exemplified, implies that the server has taken the
responsibility of delivering the message. A message can be doubled if there is a communication
failure at this time, e.g. due to a power shortage: Until the sender has not received that 250 reply,
it must assume the message was not delivered.
• After the receiver has decided to accept the message, it must assume the message has been
delivered to it. Thus, during this time span, both agents have active copies of the message that
they will try to deliver.
• The probability that a communication failure occurs exactly at this step is directly proportional to
the amount of filtering that the server performs on the message body, most often for anti-spam
purposes. The limiting timeout is specified to be 10 minutes.
• The QUIT command ends the session. If the second recipient were located elsewhere, the client
would QUIT and connect to the appropriate SMTP server after the first message had been
queued. The information that the client sends in the HELO and MAIL FROM commands are
added (not seen in example code) as additional header fields to the message by the receiving
server. It adds a Received and Return-Path header field, respectively.
POP3 programs
• POP3 (Post Office Protocol 3) is the most recent version of a standard protocol for receiving e-
mail. POP3 is a client/server protocol in which e-mail is received and held for you by your Internet
server.
• Periodically, client e-mail receiver checks your mail-box on the server and downloads any mail,
probably using POP3.
• This standard protocol is built into most popular e-mail products, such as Eudora and Outlook
Express. It's also built into the Netscape and Microsoft Internet Explorer browsers.
• POP3 is designed to delete mail on the server as soon as the user has downloaded it. However,
some implementations allow users or an administrator to specify that mail be saved for some period
of time. POP can be thought of as a "store-and-forward" service.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Example
A program that downloads and prints out the contents of a specified POP mailbox. Messages
are simply dumped on System.out in the default encoding. The servers, usernames, and so forth are
all hard coded.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
public class POP3Client {
public static void main(String[] args) {
Properties props = new Properties( );
String host = "utopia.poly.edu";
String username = "myuser";
String password =
"mypwd"; String provider =
"pop3"; try {
// Connect to the POP3 server
Session session = Session.getDefaultInstance(props,
null); Store store = session.getStore(provider);
store.connect(host, username, password);
www.Vidyarthiplus.com
www.Vidyarthiplus.com
);}
}
}
• The first is to set up the properties for the mail session. Properties you might want to set include
mail.host, mail.store.protocol, mail.user, mail.pop3.user, and mail.pop3.host. However, you don't
absolutely need to set any of these. If the Session will be used only to retrieve mail, then an empty
Properties object will be enough.
• To create an instance of the javax.mail.Authenticator class (more properly, an instance of a
concrete subclass of the abstract Authenticator class) that can ask the user for her password. For now,
we'll simply hardcode those values and pass null instead of an actual Authenticator.
• Use Properties and Authenticator objects to get a Session instance.
• Now the store is connected and ready to open a folder in the store.
• The Message class provides many methods for working with individual messages. It has methods
to get the various header fields of the message, to get the content of the message, to reply to the
message, and more. Now print each message on System.out using the message's writeTo( ) method:
import java.net.*;
import java.io.*;
public class RetrieveWebpage {
public static void main (String[] args)
{ if (args.length > 0) {
try {
//Open the URL for reading
URL u = new URL(args[0]);
InputStream in = u.openStream( );
// buffer the input to increase performance
BufferedInputStream bis = new BufferedInputStream(in);
// chain the InputStream to a Reader
Reader r = new
InputStreamReader(bis); int c;
while ((c = r.read( )) != -1) {
System.out.print((char) c);
}
}
catch (MalformedURLException e) { System.err.println(args[0]
+ " is not a parseable URL");
}
catch (IOException e) {
www.Vidyarthiplus.com
www.Vidyarthiplus.com
System.err.println(e);
}
} // end if
} // end main
} // end RetrieveWebpage
• The program reads a URL from the command line, opens an InputStream from that URL, chains
the resulting InputStream to an InputStreamReader using the default encoding.
• Then uses InputStreamReader's read ( ) method to read successive characters from the file, each
of which is printed on System.out. That is, it prints the raw data located at the URL:
• If the URL references an HTML file, the program's output is raw HTML.
Protocol handlers
• Handling a protocol means taking care of the interaction between a client and a server: generating
requests in the correct format, interpreting the headers that come back with the data,
acknowledging that the data has been received.
• Java divides the task of handling protocols into a number of pieces. As a result, there is no single
class called Protocol Handler. Instead, pieces of the protocol handler mechanism are
implemented by four different class es in the java.net package: URL, URLStreamHandler,
URLConnection, and URLStreamHandlerFactory. URL is the only concrete class in this group.
• URLStreamHandler and URLConnection are both abstract classes, and
URLStreamHandlerFactory is an interface. Therefore, if you are going to implement a new
protocol handler, you have to write concrete subclasses for the URLStreamHandler and the
URLConnection. To use these classes, you may also have to write a class that implements the
URLStreamHandlerFactory interface.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
URLStreamHandler Class
• The abstract URLStreamHandler class is a superclass for classes that handle specific protocols—
for example, HTTP. We rarely call the methods of the URLStreamHandler class directly; they are
called by other methods in the URL and URLConnection classes.
• By overriding the URLStreamHandler methods in our own subclass, we teach the URL class how
to handle new protocols. Therefore, we'll focus on overriding the methods of URLStreamHandler
rather than on calling the methods.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• If your URL looks somewhat like a standard URL, you can implement a parseURL( ) method
that handles the nonstandard portion of your URL and then calls super.parseURL( ) to do the rest of
the work, setting the offset and limit arguments to indicate the portion of the URL that you didn't
parse.
• For example, a mailto URL looks like mailto:elharo@metalab.unc.edu. First, you need to
figure out how to map this into the URL class's protocol, host, port, file, and ref fields. The protocol
is clearly mailto. Everything after the @ can be the host. The hard question is what to do with the
username. Since a mailto URL really doesn't have a file portion, we will use the URL class's file
field to hold the username. The ref can be set to the empty string or null. The parseURL( )
method that follows implements this scheme:
• Rather than borrowing an unused field from the URL object, it's possibly a better idea to store
protocol-specific parts of the URL, such as the username, in fields of the URLStreamHandler
subclass.
• The disadvantage of this approach is that such fields can be seen only by your own code; in this
example, you couldn't use the getFile( ) method in the URL class to retrieve the username. Here's
a version of parseURL( ) that stores the username in a field of the Handler subclass.
• When the connection is opened, the username can be copied into the Mailto URLConnection
object that results. That class would provide some sort of getUserName( ) method:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Example
A mailto URLStreamHandler
package com.macfaq.net.www.protocol.mailto;
import java.net.*;
import java.io.*;
import java.util.*;
public class Handler extends URLStreamHandler {
protected URLConnection openConnection(URL u) throws IOException
{ return new MailtoURLConnection(u);
}
public void parseURL(URL u, String spec, int start, int limit)
{ String protocol = u.getProtocol( );
www.Vidyarthiplus.com
www.Vidyarthiplus.com
host = address.substring(atSign+1);
file = address.substring(0, atSign);
}
}
// For Java 1.2 comment out this next line
this.setURL(u, protocol, host, port,
authority, userInfo, file, query, ref);
// In Java 1.2 and earlier uncomment the following line:
// this.setURL(u, protocol, host, port, file, ref);
}
protected String toExternalForm(URL u) {
return "mailto:" + u.getFile() + "@" + u.getHost( );;
}
}
Content handlers
• Handling the content means converting the raw data into a format Java understands, for example,
an InputStream or an AudioClip. A content handler is an instance of a subclass of
java.net.ContentHandler:
public abstract class ContentHandler extends Object
• Java can already download classes from the Internet. Thus, there isn't much magic to getting it to
download a class that can understand a new content type.
• A content handler is just a .class file like any other. The magic is all inside the web browser,
which knows when and where to request a .class file to view a new content type. Of course, some
browsers are more magical than others.
• The only way to make this work in a browser is in conjunction with an applet that knows how to
request the content handler explicitly.
• A content handler reads data from a URLConnection and constructs an object appropriate for the
content type from the data. Each subclass of ContentHandler handles a specific MIME type and
subtype, such as text/plain or image/gif. Thus, an image/gif content handler returns a
URLImageSource object (a class that implements the ImageProducer interface), while a text/plain
content handler returns a String. A database content handler might return a java.sql.ResultSet
object.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Example
The full package-qualified name is com.macfaq.net.www.content.text.tab_separated_values. This
unusual class name follows the naming convention for a content handler for the MIME type text/tab-
separated-values. Since MIME types often contain hyphens, as in this example, a convention exists to
replace these with the underscore (_). Thus text/tab-separated-values becomes
text.tab_separated_values. To install this content handler, all that's needed is to put the compiled
.class file somewhere the class loader can find it and set the java.content.handler.pkgs property to
com.macfaq.net.www.content.
package com.macfaq.net.www.content.text;
import java.net.*;
import java.io.*;
import java.util.*;
import com.macfaq.io.SafeBufferedReader;
www.Vidyarthiplus.com
www.Vidyarthiplus.com
int numFields = 1;
for (int i = 0; i < line.length( ); i++) {
if (line.charAt(i) == '\t') numFields++;
}
String[] fields = new
String[numFields]; int position = 0;
for (int i = 0; i < numFields; i++) {
StringBuffer buffer = new StringBuffer( );
while (position < line.length( ) && line.charAt(position) !='\t')
{ buffer.append(line.charAt(position));
position++;
}
fields[i] = buffer.toString( );
position++;
}
return fields;
}
}
Applets
• An applet is a program written in the Java programming language that can be included in an
HTML page, much in the same way an image is included in a page.
• When you use a Java technology-enabled browser to view a page that contains an applet, the
applet's code is transferred to your system and executed by the browser's Java Virtual Machine
(JVM).
Life Cycle
• Applet runs in the browser and its lifecycle method are called by JVM when it is loaded
and destroyed. Here are the lifecycle methods of an Applet:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
init () method:
• The life cycle of an applet is begin on that time when the applet is first loaded into the browser
and called the init() method.
• The init() method is called only one time in the life cycle on an applet. The init() method is
basically called to read the PARAM tag in the html file. The init () method retrieve the passed
parameter through the PARAM tag of html file using get Parameter() method
• All the initialization such as initialization of variables and the objects like image, sound file are
loaded in the init () method .After the initialization of the init() method user can interact with
the Applet and mostly applet contains the init() method.
Start () method:
• The start method of an applet is called after the initialization method init().
• This method may be called multiples time when the Applet needs to be started or restarted. For
Example if the user wants to return to the Applet, in this situation the start Method() of an
Applet will be called by the web browser and the user will be back on the applet.
• In the start method user can interact within the applet.
Stop () method:
• The stop() method can be called multiple times in the life cycle of applet like the start () method.
Or should be called at least one time.
• There is only miner difference between the start() method and stop () method. Example the stop()
method is called by the web browser on that time When the user leaves one applet to go another
applet and the start() method is called on that time when the user wants to go back into the first
program or Applet.
destroy() method:
• The destroy() method is called only one time in the life cycle of Applet like init() method.
• This method is called only on that time when the browser needs to Shut down.
Image handling
• The basic manner of displaying an Image in an applet/application is to call the drawImage()
method of the Graphics class in the paint() method of the component to display the image.
• There are six varieties of the method that deal with scaling and background colors for transparent
images. The basic manner of calling is as follows:
g.drawImage(image, xPosition, yPosition, this);
• The last argument is what's called an ImageObserver and helps deal with the asynchronous
loading of image data. Generally speaking, you just pass a reference to the applet as the image
observer so that as more data is loaded the applet (the observer) is notified and redraws itself.
‖ To make matters simpler for an applet, allowing you to move an applet between hosts without
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• having to hardcode where the images come from, you can use a second variety of the method:
Image image = getImage(baseURL, file);
• Provide the base URL and filename separately. The two are combined to form the specific URL
to get the image file from. The getDocumentBase() method allows you to start with a base URL
of where the HTML file is located. And, the getCodeBase() method allows you to start with a
base URL of where the .class file is located. Using one of the two you can find an image in the
same directory as either with something like this:
Image image = getImage(getDocumentBase(), "image.jpg");
• Most contexts also understand JPEG though JPEG support was omitted from some vendors' early
alpha and beta releases. The applet that loads and displays the image referenced by the IMAGE
parameter, which comes from a <PARAM> tag in the HTML file.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• This is similar to the previous method, except that it uses the path argument (a URL) to find the
image's directory and the filename argument (a String) to get the name of the image file. For
example:
Image logo = this.getImage(new URL("http://metalab.unc.edu/java/"),"cup.gif");
• This version of getImage( ) is frequently used with getCodeBase( ) or
getDocumentBase( ). You would use getCodeBase ( ) in an applet that might be used on many
different web servers but whose images would always be in the same directory as the applet.
• For example:
Image logo = this.getImage(this.getCodeBase( ), "logo.gif"));
If the applet exists on only one web server but is embedded on many different pages, each of
which loads different images, you would use getDocumentBase( ) to locate the images:
Image logo = this.getImage( this.getDocumentBase( ), "logo.gif"));
• This technique would be useful in an animator applet; the applet would probably read the names
of some image files from parameters included in the HTML. You can use the filename argument
to add to the path you get from the URL component. For example, if the pictures are in a
directory called images, which is in the same directory as the HTML page, you would load the
file logo.gif like this:
Image logo = this.getImage(this.getDocumentBase( ), "images/logo.gif"));
• RMI is a distributed object system that enables you to easily develop distributed Java
applications. Developing distributed applications in RMI is simpler than developing with sockets
since there is no need to design a protocol, which is an error-prone task.
• In RMI, the developer has the illusion of calling a local method from a local class file, when in
fact the arguments are shipped to the remote target and interpreted, and the results are sent back
to the callers.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
FileInterface.java import
java.rmi.Remote;
import java.rmi.RemoteException;
FileImpl.java
import java.io.*;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
www.Vidyarthiplus.com
www.Vidyarthiplus.com
}
}
}
FileServer.java
import java.io.*;
import java.rmi.*;
System.out.println("FileServer:
"+e.getMessage()); e.printStackTrace();
}
}
}
4. Develop a client
The client remotely invokes any methods specified in the remote interface (FileInterface). To
do so however, the client must first obtain a reference to the remote object from the RMI registry.
Once a reference is obtained, the downloadFile method is invoked. In this implementation, the client
accepts two arguments at the command line: the first one is the name of the file to be downloaded
and the second one is the address of the machine from which the file is to be downloaded, which is
the machine that is running the file server.
FileClient.java
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• To start the server you need a copy of all the classes (including stubs and skeletons) except the
client class (FileClient.class). To start the server use the following command, assuming that the
security policy is in a file named policy.txt:
prompt> java -Djava.security.policy=policy.txt FileServer
• To start the client on a different machine, you need a copy of the remote interface
(FileInterface.class) and stub (FileImpl_Stub.class). To start the client use the command:
prompt> java FileClient fileName machineName
where fileName is the file to be downloaded and machineName is the machine where the file is
located (the same machine runs the file server
• To run the client we mentioned that you need a copy of the interface and stub. A more
appropriate way to do this is to use RMI dynamic class loading. The idea is you do not need copies of
the interface and the stub. Instead, they can be located in a shared directory for the server and the
client, and whenever a stub or a skeleton is needed, it is downloaded automatically by the RMI class
loader. To do this you run the client, for example, using the following command:
java -Djava.rmi.server.codebase=http://hostname/locationOfClasses FileClient
fileName machineName.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
UNIT-III
SCRIPTING ELEMENTS
HTML
HTML is a language for describing web pages.
• HTML stands for Hyper Text Markup Language
• HTML is not a programming language, it is a markup language
• A markup language is a set of markup tags
• HTML uses markup tags to describe web pages
HTML Tags
HTML markup tags are usually called HTML tags
• HTML tags are keywords surrounded by angle brackets like <html>
• HTML tags normally come in pairs like <b> and </b>
• The first tag in a pair is the start tag, the second tag is the end tag
• Start and end tags are also called opening tags and closing tags
The purpose of a web browser (like Internet Explorer or Firefox) is to read HTML documents
and display them as web pages. The browser does not display the HTML tags, but uses the tags to
interpret the content of the page.
Examples:
<html>
<body>
<h1>My First
Heading</h1> <p>My first
paragraph.</p> </body>
</html>
1. HTML Headings
HTML headings are defined with the <h1> to <h6>
tags. <h1>This is a heading</h1>
<h2>This is a heading</h2>
2. HTML Paragraphs
HTML paragraphs are defined with the <p>
tag. <p>This is a paragraph.</p>
<p>This is another
paragraph.</p> 3. HTML Links
HTML links are defined with the <a> tag.
<a href="http://www.internetprogramming.com">This is a
link</a> 4. HTML Images
HTML images are defined with the <img> tag.
<img src="ip.jpg" width="154" height="182" />
Forms
• HTML forms are used to pass data to a server.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons
and more. A form can also contain select lists, textarea, fieldset, legend, and label elements.
The <form> tag is used to create an HTML
form: <form>
.
input elements
.
</form>
Input Element
• The input element is used to select user information. An input element can vary in many ways,
depending on the type attribute.
• An input element can be of type text field, checkbox, password, radio button, submit button, and
more.
Text Fields
<input type="text" /> defines a one-line input field that a user can enter text into:
<form>
First name: <input type="text" name="firstname" /><br
/> Last name: <input type="text" name="lastname" />
</form>
Password Field
<input type="password" /> defines a password field:
<form>
Password: <input type="password" name="pwd"
/> </form>
Radio Buttons
<input type="radio" /> defines a radio button. Radio buttons let a user select ONLY ONE of
a limited number of choices:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
<form>
<input type="radio" name="sex" value="male" /> Male<br
/> <input type="radio" name="sex" value="female" />
Female </form>
Checkboxes
<input type="checkbox" /> defines a checkbox. Checkboxes let a user select ONE or
MORE options of a limited number of choices.
<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br
/> <input type="checkbox" name="vehicle" value="Car" /> I have a car
</form>
Submit Button
<input type="submit" /> defines a submit button. A submit button is used to send form data to
a server. The data is sent to the page specified in the form's action attribute. The file defined in the
action attribute usually does something with the received input:
Frames
With frames, we can display more than one HTML document in the same browser
window. Each HTML document is called a frame, and each frame is independent of the others.
Frameset Tag
• The <frameset> tag defines how to divide the window into frames
• Each frameset defines a set of rows or columns
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• The values of the rows/columns indicate the amount of screen area each row/column
will occupy
Frame Tag
• The <frame> tag defines what HTML document to put into each frame
In the example below we have a frameset with two columns. The first column is set to 25% of the
width of the browser window. The second column is set to 75% of the width of the browser window.
The HTML document "frame_a.htm" is put into the first column, and the HTML document
"frame_b.htm" is put into the second column:
<frameset cols="25%,75%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>
Note:
• The frameset column size value can also be set in pixels (cols="200,500"), and one of
the columns can be set to use the remaining space (cols="25%,*").
• You cannot use the <body></body> tags together with the <frameset></frameset> tags!
Tables
• Tables are defined with the <table> tag.
• A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the
<td> tag). td stands for "table data," and holds the content of a data cell. A <td> tag can contain
text, links, images, lists, forms, other tables, etc.
Border Attribute
• If you do not specify a border attribute, the table will be displayed without borders. Sometimes
this can be useful, but most of the time, we want the borders to show.
• To display a table with borders, specify the border attribute:
<table border="1">
Table Headers
Header information in a table is defined with the <th> tag.
Example:
<table
border="1"> <tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
www.Vidyarthiplus.com
www.Vidyarthiplus.com
<td>row 1, cell
1</td> <td>row 1,
cell 2</td> </tr>
<tr>
<td>row 2, cell
1</td> <td>row 2,
cell 2</td> </tr>
</table>
Header 1 Header 2
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2
JavaScript
Purpose
• JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone
can put small "snippets" of code into their HTML pages
• JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
• JavaScript can react to events - A JavaScript can be set to execute when something happens, like
when a page has finished loading or when a user clicks on an HTML element
• JavaScript can read and write HTML elements - A JavaScript can read and change the content of
an HTML element
• JavaScript can be used to validate data - A JavaScript can be used to validate form data before it
is submitted to a server. This saves the server from extra processing
• JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the
visitor's browser, and - depending on the browser - load another page specifically designed for
that browser
• JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer
Example
<html>
<body>
www.Vidyarthiplus.com
www.Vidyarthiplus.com
<script type="text/javascript">
document.write("<h1>Hello
World!</h1>"); </script>
</body>
</html>
Control Structures
Conditional Statements
In JavaScript we have the following conditional statements:
• if statement - use this statement to execute some code only if a specified condition is true
• if...else statement - use this statement to execute some code if the condition is true and
another code if the condition is false
• if...else if....else statement - use this statement to select one of many blocks of code to be
executed
• switch statement - use this statement to select one of many blocks of code to be executed
Example:
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>
Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Example:
<script type="text/javascript">
//You will receive a different greeting
based //on what day it is. Note that
Sunday=0, //Monday=1, Tuesday=2, etc.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
}
</script>
Functions
• To keep the browser from executing a script when the page loads, put script into a function. A
function contains code that will be executed by an event or by a call to the function.
• You may call a function from anywhere within a page (or even from other pages if the function is
embedded in an external .js file).
• Functions can be defined both in the <head> and in the <body> section of a document. However,
to assure that a function is read/loaded by the browser before it is called, it could be wise to put
functions in the <head> section.
Syntax
function functionname(var1,var2,...,varX)
{
some code
}
Note: The word function must be written in lowercase letters, otherwise a JavaScript error occurs!
Also note that call a function with the exact same capitals as in the function name.
Example
<html>
<head>
<script type="text/javascript">
function displaymsg()
{
alert("Hello World!");
}
</script>
</head>
www.Vidyarthiplus.com
www.Vidyarthiplus.com
<body>
<form>
<input type="button" value="Click me!" onclick="displaymsg()"
/> </form>
</body>
</html>
Arrays
Declaring and Allocating Arrays
• Arrays occupy space in memory. An array in JavaScript is an Array object. The programmer uses
operator new to allocate dynamically the number of elements required by each array.
• The process of creating new objects is also known as creating an instance, or instantiating an
object, and operator new is known as the dynamic memory allocation operator. Array objects are
allocated with new because arrays are considered to be objects, and all objects must be created
with new. To allocate 12 elements for integer array c, use the statement
var c = new Array( 12 );
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Multiple-Subscripted Arrays
‖ Multiple-subscripted arrays with two subscripts often are used to represent tables of values
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• The names of the elements in the first row all have a first subscript of 0; the names of the
elements in the fourth column all have a second subscript of 3. Multiple-subscripted arrays can be
initialized in declarations like a single-subscripted array. Array b with two rows and two columns
could be declared and initialized with the statement
var b = [ [ 1, 2 ], [ 3, 4 ] ];
• The values are grouped by row in square brackets. So, 1 and 2 initialize b[0][0] and b[0][1], and 3
and 4 initialize b[1][0] and b[1][1]. The interpreter determines the number of rows by counting
the number of sub-initializer lists (represented by sets of square brackets) in the main initializer
list. The interpreter determines the number of columns in each row by counting the number of
initializer values in the sub-initializer list for that row. Multiple-subscripted arrays are maintained
as arrays of arrays. The declaration
var b = [ [ 1, 2 ], [ 3, 4, 5 ] ];
creates array b with row 0 containing two elements (1 and 2) and row 1 containing
three elements (3, 4 and 5).
Objects
The built-in objects available in java script are,
String object
The String object is used to manipulate a stored piece of text.
Example:
1. var txt="Hello world!";
document.write(txt.length);
output: 12
Date Object
The Date object is used to work with dates and times. Date objects are created with the
Date() constructor. There are four ways of instantiating a date:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Example:
today = new Date()
d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)
The Date object is also used to compare two dates. The following example compares
today's date with the 15th August 2012:
Array Object
An array is a special variable, which can hold more than one value, at a time. An array can be
defined in three ways. The following code creates an Array object called myCars:
1. var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab"; // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";
2. var myCars=new Array("Saab","Volvo","BMW"); // condensed array
3. var myCars=["Saab","Volvo","BMW"]; // literal array
Math Object
The Math object allows you to perform mathematical tasks. The Math object includes
several mathematical constants and methods.
Syntax output
var sqrt_value=Math.sqrt(16); 4
document.write(Math.round(8.7)); 9
www.Vidyarthiplus.com
www.Vidyarthiplus.com
UNIT IV
DYNAMIC HTML
Dynamic HTML – introduction – cascading style sheets – object model and collections –
event model – filters and transition – data binding – data control – ActiveX control – handling
of multimedia data
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• Attribute style specifies the style for an element. Each CSS property (the font-size property in this
case) is followed by a colon and a value. We declare the p element to have 20-point text size.
• Element em to ―emphasize‖ text, which most browsers do by making the font italic. The two
properties, font-size and color are separated by a semicolon. Set the text‘s color to blue, using the
hexadecimal code #0000ff.Color names may be used in place of hexadecimal codes.
color: white }
h1 { font-family: arial, sans-serif
} p { font-size: 14pt }
.special { color: blue
} </style>
</head>
<body>
<h1 class = "special">Deitel & Associates, Inc.</h1>
<p>Deitel & Associates, Inc. is an internationally recognized corporate training and publishing
organization specializing in programming languages, Internet/World Wide Web technology
and object technology education. Deitel & Associates, Inc. is a member of the World Wide
Web Consortium. The company provides courses on Java, C++, Visual Basic, C, Internet
and World Wide Web programming, and Object Technology.</p>
<h1>Clients</h1>
<p class = "special"> The company's clients include many
<em>Fortune 1000 companies</em>, government agencies, branches of the military and business
organizations. Through its publishing partnership with Prentice Hall, Deitel & Associates, Inc.
publishes leading-edge programming textbooks, professional books, interactive CD-ROM-based
multimedia Cyber Classrooms, satellite courses and World Wide Web courses.</p>
</body>
</html>
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Dynamic Styles
• An element‘s style can be changed dynamically. Often such a change is made in response to user
events. We refer to the background color as document. body.style.backgroundColor—the body
property of the document object refers to the body element.
• Then use the style object (a property of most XHTML elements) to set the background-color CSS
property. (This is referred to as backgroundColor in JavaScript, to avoid confusion with the
subtraction (-) operator. This naming convention is consistent for most of the CSS properties.
Dynamic Positioning
• XHTML elements can be positioned with scripting. This is done by declaring an element‘s CSS
position property to be either absolute or relative, and then moving the element by manipulating
any of the top, left, right or bottom CSS properties.
• vary the position of the element on the page by accessing its CSS left attribute, we use scripting
to vary the color, fontFamily and fontSize attributes, and we use the element‘s innerHTML
property to alter the content of the element.
Event model
Event onclick
<head>
<title>DHTML Event Model - onclick</title>
<!-- The for attribute declares the script for -->
<!-- a certain element, and the event for a -->
<!-- certain event. -->
<script type = "text/javascript" for =
"para" event = "onclick">
<!--
alert( "Hi there" ;
</script></head><body>
<!-- The id attribute gives a unique identifier -->
<p id = "para">Click on this text!</p>
<!-- You can specify event handlers inline
--> <input type = "button" value =
"Click Me!" onclick = "alert( 'Hi again' )" />
</body></html>
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Event onload
• The onload event fires whenever an element finishes loading successfully.
• Frequently, this event is used in the body element to initiate a script after the page loads into the
client.
• The script called by the onload event, updates a timer that indicates how many seconds have
elapsed since the document has been loaded.
onmousemove
<head>
<title>DHTML Event Model - onmousemove
event</title> <script type = "text/javascript">
<!--
function updateMouseCoordinates()
{
coordinates.innerText = event.srcElement.tagName
+ " (" + event.offsetX + ", " + event.offsetY + ")";
}
// -->
</script>
</head>
<body style = "back-groundcolor: wheat"
onmousemove = "updateMouseCoordinates()">
<span id = "coordinates">(0, 0)</span><br />
<img src = "deitel.gif" style = "position:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
"server-side script",
"This button clears the form",
"This textarea provides context-sensitive " + "help. Click on any input field or use the Tab " +
"key to get more information about " +
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Filters
Flip filters: flipv and fliph
<head>
<title>The flip filter</title>
<style type = "text/css">
body { background-color: #CCFFCC
} table { font-size: 3em;
font-family: Arial, sans-serif;
background-color: #FFCCCC;
border-style: ridge ; border-
collapse: collapse }
td { border-style:
groove; padding: 1ex }
</style>
</head>
<body>
<table>
<tr>
<!-- Filters are applied in style declarations --
> <td style = "filter: fliph">Text</td>
<td>Text</td>
</tr>
<tr>
www.Vidyarthiplus.com
www.Vidyarthiplus.com
<!-- More than one filter can be applied at once --> <td style = "filter: flipv fliph">Text</td>
<head>
<title>Mask
Filter</title> </head>
<body>
<h1>Mask Filter</h1>
<!-- Filter parameters are specified in parentheses, . --> <!-
- in the form param1 = value1, param2 = value2, etc. -->
<div style = "position: absolute; top: 125; left: 20; filter: mask( color = #CCFFFF
)"> <h1 style = "font-family: Courier, monospace">
AaBbCcDdEeFfGgHhIiJj<br
/> KkLlMmNnOoPpQqRrSsTt
</h1>
</div>
<img src = "gradient.gif" width = "400" height = "200" alt = "Image with Gradient Effect"
/> </body>
</html>
www.Vidyarthiplus.com
www.Vidyarthiplus.com
<head>
<title>Misc. Image filters</title>
<style type = "text/css">
.cap { font-weight: bold;
background-color: #DDDDAA;
text-align: center }
</style>
</head>
<body>
<table class =
"cap"> <tr>
<td>Normal</td>
<td>Grayscale</td>
</tr>
<tr>
<td><img src = "hc.jpg" alt = "normal scenic view" /></td>
<td><img src = "hc.jpg" style = "filter: gray" alt = "gray scenic
view"/> </td>
</tr>
<tr>
<td>Xray</td>
<td>Invert</td>
</tr>
<tr>
<td><img src = "hc.jpg" style = "filter: xray" alt = "xray scenic
view"/> </td>
<td><img src = "hc.jpg" style = "filter: invert" alt = "inverted scenic
view"/> </td>
</tr>
www.Vidyarthiplus.com
www.Vidyarthiplus.com
</table>
</body>
</html>
Transitions
Filter blendTrans
<head>
<title>Using blendTrans</title>
<script type =
"text/javascript"> <!--
function blendOut()
{
textInput.filters( "blendTrans" ).apply();
textInput.style.visibility = "hidden";
textInput.filters( "blendTrans" ).play();
}
// -->
</script>
</head>
<body>
<div id = "textInput" onclick = "blendOut()" style
= "width: 300; filter: blendTrans( duration = 3 )">
<h1>Some fading text</h1>
</div>
</body>
</html>
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
function reNumber()
{
if ( !recordSet.EOF )
recordNumber.innerText =
recordSet.absolutePosition; else
recordNumber.innerText = " ";
}
function forward()
{
recordSet.MoveNext();
if ( recordSet.EOF )
recordSet.MoveFirst();
colorSample.style.backgroundColor = 46
colorRGB.innerText; reNumber();
}
// -->
</script>
</head>
<body onload = "reNumber()" onclick =
"forward()"> <h1>XHTML Color Table</h1>
<h3>Click to move forward in the recordset.</h3>
<p><strong>Color Name: </strong>
<span id = "colorId" style = "font-family: monospace"
datasrc = "#Colors" datafld = "ColorName"></span><br
/> <strong>Color RGB Value: </strong>
<span id = "colorRGB" style = "font-family: monospace" datasrc = "#Colors" datafld =
"ColorHexRGBValue">
</span><br />
Currently viewing record number
<span id = "recordNumber" style = "font-weight: 900">
</span><br />
<span id = "colorSample" style = "background-color:
aqua; color: 888888; font-size: 30pt">Color Sample
</span></p>
</body>
</html>
• Data in each field is enclosed in text qualifiers (@) and each field is separated with a field
delimiter (|).
• The object element here inserts the Tabular Data Control is one of the Microsoft ActiveX controls
built into Internet Explorer 5.5.
• Attribute classid specifies the ActiveX control to add to the Web page—here we use the classid
of the Tabular Data Control.
• The param tag specifies parameters for the object in the object element. Attribute name is the
parameter name and attribute value is the value. Parameter DataURL is the URL of the data
www.Vidyarthiplus.com
www.Vidyarthiplus.com
source (HTMLStandardColors.txt). Parameter UseHeader, when set to true, specifies that the first
line of our data file has a header row.
• The datasrc attribute refers to the id of the TDC object (Colors, in this case) preceded with a hash
mark (#), and the datafld attribute specifies the name of the field to bind it to (ColorName, in this
case). This place the data contained in the first record (i.e., row) of the ColorName column into
the span element.
• MoveNext method moves the current recordset forward by one row, automatically updating the
span to which we bound our data.
Binding to an img
Many different types of XHTML elements can be bound to data sources. One of the
more interesting elements in which to bind data is the img element.
recordSet.MoveFirst();
break;
case "last": recordSet.MoveLast();
break;
www.Vidyarthiplus.com
www.Vidyarthiplus.com
}
}
// -->
</script>
</head>
<body>
<img datasrc = "#Images" datafld = "image" alt = "Image" style = "position: relative; left:
45px" /><br />
<input type = "button" value = "First" onclick = "move( 'first' );" />
<input type = "button" value = "Previous" onclick = "move( 'previous' );" />
<input type = "button" value = "Next" onclick = "move( 'next' );" />
<input type = "button" value = "Last" onclick = "move( 'last' );" />
</body>
Binding to a table
Binding data to a table element is perhaps the most important feature of data binding.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
</tr>
</tbody>
• Bind the table by adding the datasrc attribute to the opening table tag. We complete the data
binding by adding the datafld attribute to span tags that reside in the table cells.
ActiveX control
• ActiveX controls are small program building blocks that can serve to create distributed
applications that work over the internet through web browsers.
• An ActiveX control can be automatically downloaded and executed by a web browser. ActiveX is
not a programming language, but rather a set of rules for how applications should share
information. Programmers can develop ActiveX controls in a variety of languages including C,
C++, visual basic, and java.
• Examples include customized applications for gathering data, viewing certain kinds of files, and
displaying animation.
• An ActiveX control is similar to a Java applet. Unlike Java applets, however, ActiveX controls
have full access to the Windows operating system. This gives them much more power than Java
applets, but with this power comes a certain risk that the applet may damage software or data on
your machine.
• To control this risk, Microsoft developed a registration system so that browsers can identify and
authenticate an ActiveX control before downloading it.
• Another difference between Java applets and ActiveX controls is that Java applets can be written
to run on all platforms, whereas ActiveX controls are currently limited to Windows
environments.
UNIT V
SERVER SIDE PROGRAMMING
Though it is technically feasible to implement almost any business logic using client side
programs, logically or functionally it carries no ground when it comes to enterprise applications
(e.g. banking, air ticketing, e-shopping etc.). To further explain, going by the client side
programming logic; a bank having 10,000 customers would mean that each customer should have a
copy of the program(s) in his or her PC which translates to 10,000 programs! In addition, there are
issues like security, resource pooling, concurrent access and manipulations to the database which
simply cannot be handled by client side programs. The answer to most of the issues cited above is –
―Server Side Programming‖.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Example: import
java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter pw = response.getWriter();
pw.println("Hello World");
www.Vidyarthiplus.com
www.Vidyarthiplus.com
}
}
Servlet API (refer java complete ref)
Two packages contain the classes and interfaces that are required to build servlets. These are
javax.servlet and javax.servlet.http. They constitute the Servlet API. Keep in mind that these
packages are not part of the Java core packages. Instead, they are standard extensions. Therefore,
they are not included in the Java Software Development Kit. You must download Tomcat to obtain
their functionality.
The Servlet API has been in a process of ongoing development and enhancement. The
current servlet specification is version is 2.3 and that is the one used in this book. However, because
changes happen fast in the world of Java, you will want to check for any additions or alterations.
This chapter discusses the core of the Servlet API, which will be available to most readers.
The javax.servlet package contains a number of interfaces and classes that establish
the framework in which servlets operate. The following table summarizes the core interfaces that are
provided in this package. The most significant of these is Servlet. All servlets must implement this
interface or extend a class that implements the interface. The ServletRequest and ServletResponse
interfaces are also very important.
Interface Description
• Servlet Declares life cycle methods for a servlet.
• ServletConfig Allows servlets to get initialization parameters.
• ServletContext Enables servlets to log events and access
information about their environment.
• ServletRequest Used to read data from a client request.
• ServletResponse Used to write data to a client response.
• SingleThreadModel Indicates that the servlet is thread safe.
The following table summarizes the core classes that are provided in the javax.servlet package.
Class Description
• GenericServlet Implements the Servlet and ServletConfig
interfaces.
• ServletInputStream Provides an input stream for reading requests from
a client.
• ServletOutputStream Provides an output stream for writing responses to
a client.
• ServletException Indicates a servlet error occurred.
Deployment
• Write the servlet class.
• Compile the Servlet class.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• You just need to create war file of our web application and copy it to webapp directory under
your tomcat installation to deploy application to tomcat. Open command prompt and go to root
directory of our application (welcomeServlet). Create a war file using following command.
jar -cvf welcomeservlet.war *
• It will create formexample.war file under FormExample directory. Copy the war file to
webapp directory under tomcat installation.
Web Server
• A web server is a computer programs that delivers (serves) content, such as web pages, using the
Hypertext Transfer Protocol (HTTP), over the World Wide Web.
• The term web server can also refer to the computer or virtual machine running the program.
• Apache Tomcat (or Jakarta Tomcat or simply Tomcat) is an open source servlet container
developed by the Apache Software Foundation (ASF). Tomcat implements the Java Servlet and
the JavaServer Pages (JSP) specifications from Sun Microsystems, and provides a "pure Java"
HTTP web server environment for Java code to run.
• 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.
• For the developer that dabbles in Java programming, servlets can be used to turn the Java Web
Server into their own personal Web processor.
• BEA Systems' WebLogic is a server software application that runs on a middle tier, between
back-end databases and related applications and browser-based thin clients.
• WebLogic is a leading e-commerce online transaction processing (OLTP) platform, developed to
connect users in a distributed computing environment and to facilitate the integration of
mainframe applications with distributed corporate data and applications.
• 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.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
GET
• The Get is one the simplest Http method. Its main job is to ask the server for the resource.
• If the resource is available then it will given back to the user on your browser. That resource may
be a HTML page, a sound file, a picture file (JPEG) etc.
• We can say that get method is for getting something from the server. It doesn't mean that you
can't send parameters to the server. But the total amount of characters in a GET is really limited.
• In get method the data we send get appended to the URL so whatever you will send will be seen
by other user so can say that it is not even secure.
POST
• The Post method is more powerful request. By using Post we can request as well as send some
data to the server.
• We use post method when we have to send a big chunk of data to the server, like when we have
to send a long enquiry form then we can send it by using the post method.
Example
<html>
<head><title>Using Post Method in
Form.</title></head> <body>
<form method="post">
Enter your name: <input type="text‖ size="20" name="txtName" />
<input type="submit" name="B1" value="Submit"
/> <input type="reset" name="B2" value="Reset" />
</form>
</body>
</html>
Session Tracking
A Session refers to the entire request that a single client makes to a server. A session is
specific to the user and for each user a new session is created to track all the request from that user.
Every user has a separate session and separate session variable is associated with that session.
HTTP is stateless protocol and it does not maintain the client state. But there exist a
mechanism called "Session Tracking" which helps the servers to maintain the state to track the series
of requests from the same user across some period of time.
A session ID is an unique identification string usually a long, random and alpha-numeric
string, that is transmitted between the client and the server. Session IDs are usually stored in the
cookies, URLs (in case url rewriting) and hidden fields of Web pages.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
For example, when clients at an online store add an item to their shopping carts, how does the
server know what‘s already in the carts? Similarly, when clients decide to proceed to checkout, how
can the server determine which previously created shopping carts are theirs?
There are three typical solutions to this problem:
• cookies,
• URL rewriting
• Hidden form fields.
• User Authorization
Obtaining a Session
The getSession method of the HttpServletRequest object returns a user's session. When you
call the method with its create argument as true, the implementation creates a session if necessary.
The Duke's Bookstore example uses session tracking to keep track of the books in the user's
shopping cart. Here is an example of theCatalogServlet obtaining a session for a user:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
...
}
}
www.Vidyarthiplus.com
www.Vidyarthiplus.com
...
// Check for pending adds to the shopping cart String bookId = request.getParameter("Buy");
//If the user wants to add a book, add it and print the
result String bookToAdd = request.getParameter("Buy");
if (bookToAdd != null) {
BookDetails book = database.getBookDetails(bookToAdd);
cart.add(bookToAdd, book);
out.println("<p><h3>" + ...);
}
}
...
scart = (ShoppingCart)session.getValue(session.getId());
...
// Clear out shopping cart by invalidating the
session session.invalidate();
Methods
1. public void setAttribute(java.lang.String name, java.lang.Object value)
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Binds an object to this session, using the name specified. If an object of the same name is
already bound to the session, the object is replaced.
Example:
Orderform.html
<HTML>
<HEAD>
<TITLE>Order
Form</TITLE> </HEAD>
<BODY >
www.Vidyarthiplus.com
www.Vidyarthiplus.com
<H1>Order Form</H1>
<FORM ACTION="show-items" METHOD="POST">
New Item to Order:
<INPUT TYPE="TEXT" NAME="newItem" VALUE="CompleteRef"><P>
<INPUT TYPE="SUBMIT" VALUE="Order and Show All Purchases">
</FORM>
</BODY>
</HTML>
ShowItems.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n"
+ "<BODY BGCOLOR=\"#FDF5E6\">\n" );
if (previousItems.size() == 0) {
out.println("<I>No items</I>");
} else {
out.println("<UL>");
Enumeration e = Collections.enumeration(previousItems);
while(e.hasMoreElements())
out.println(e.nextElement());
out.println("</UL>");
}
www.Vidyarthiplus.com
www.Vidyarthiplus.com
out.println("</BODY></HTML>");
}
}
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Cookies
A cookie is a bit of information sent by a web server to a browser that can later be read back
from that browser. When a browser receives a cookie, it saves the cookie and thereafter sends the
cookie back to the server each time it accesses a page on that server, subject to certain rules. Because
a cookie's value can uniquely identify a client, cookies are often used for session tracking.
• Cookies were first introduced in Netscape Navigator.
• Version 2.0 of the Servlet API provides the javax.servlet.http.Cookie class for working with
cookies. The HTTP header details for the cookies are handled by the Servlet API.
• create a cookie with the Cookie() constructor:
public Cookie(String name, String value)
This creates a new cookie with an initial name and value.
A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of
HttpServletResponse:
public void HttpServletResponse.addCookie(Cookie cookie)
This method adds the specified cookie to the response. Additional cookies can be added with
subsequent calls to addCookie() . Because cookies are sent using HTTP headers, they should be
added to the response before you send any content. Browsers are only required to accept 20
cookies per site, 300 total per user, and they can limit each cookie's size to 4096 bytes.
This method returns an array of Cookie objects that contains all the cookies sent by the browser
as part of the request or null if no cookies were sent. The code to fetch cookies looks like this:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
www.Vidyarthiplus.com
www.Vidyarthiplus.com
}
}
}
www.Vidyarthiplus.com
www.Vidyarthiplus.com
out.println("</BODY></HTML>");
}
Advantages of cookies:
1. Cookies do not require any server resources since they are stored on the client.
2. Cookies are easy to implement.
3. You can configure cookies to expire when the browser session ends (session cookies) or they
can exist for a specified length of time on the client computer (persistent cookies).
Disadvantages:
• The biggest problem with cookies is that browsers don't always accept cookies. Sometimes this is
because the browser doesn't support cookies.
• Due to limited memory space WAP gateways doesn‘t use cookies.
• Any intruder (unauthorized person) using client‘s machine can change value of cookies.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
In the two-tier model, a Java application talks directly to the data source. This requires a
JDBC driver that can communicate with the particular data source being accessed. A user's
commands are delivered to the database or other data source, and the results of those statements are
sent back to the user. The data source may be located on another machine to which the user is
connected via a network. This is referred to as a client/server configuration, with the user's machine
as the client, and the machine housing the data source as the server. The network can be an intranet,
which, for example, connects employees within a corporation, or it can be the Internet.
In the three-tier model, commands are sent to a "middle tier" of services, which then sends the
commands to the data source. The data source processes the commands and sends the results back to
the middle tier, which then sends them to the user. MIS directors find the three-tier model very
attractive because the middle tier makes it possible to maintain control over access and the kinds of
updates that can be made to corporate data. Another advantage is that it simplifies the deployment of
applications. Finally, in many cases, the three-tier architecture can provide performance advantages.
Until recently, the middle tier has often been written in languages such as C or C++, which
offer fast performance. However, with the introduction of optimizing compilers that translate Java
bytecode into efficient machine-specific code and technologies such as Enterprise JavaBeans™, the
Java platform is fast becoming the standard platform for middle-tier development. This is a big plus,
making it possible to take advantage of Java's robustness, multithreading, and security features.
With enterprises increasingly using the Java programming language for writing server code,
the JDBC API is being used more and more in the middle tier of a three-tier architecture. Some of the
features that make JDBC a server technology are its support for connection pooling, distributed
transactions, and disconnected rowsets. The JDBC API is also what allows access to a data source
from a Java middle tier.
JDBC drivers
JDBC is an API for the Java programming language that defines how a client may access a
database. It provides methods for querying and updating data in a database. JDBC is oriented towards
relational databases. JDBC was first introduced in the Java 2 Platform, together with a reference
implementation JDBC-to-ODBC bridge, enabling connections to any ODBC-accessible data source
in the JVM host environment.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
JDBC Steps
Before create a java jdbc connection to the database, you must first import the java.sql package.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
instance of itself. A client can connect to Database Server through JDBC Driver. Since most of the
Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.
The return type of the Class.forName (String ClassName) method is ―Class‖. Class is a class in
java.lang package.
try {
Class.forName(‖sun.jdbc.odbc.JdbcOdbcDriver‖); //Or any other driver
}
catch(Exception x){
System.out.println( ―Unable to load the driver class!‖ );
}
www.Vidyarthiplus.com
www.Vidyarthiplus.com
4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.
Statement interface defines methods that are used to interact with database via the
execution of SQL statements. The Statement class has three methods for executing statements:
executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is
executeQuery . For statements that create or modify tables, the method to use is executeUpdate.
Note: Statements that create a table, alter a table, or drop a table are all examples of DDL statements
and are executed with the method executeUpdate. execute() executes an SQL statement that is written
as String object.
ResultSet provides access to a table of data generated by executing a Statement. The table rows are
retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next()
method is used to successively step through the rows of the tabular results.
ResultSetMetaData Interface holds information on the types and properties of the columns in a
ResultSet. It is constructed from the Connection object.
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
// Load (and therefore register) the Oracle Driver
Class.forName("oracle.jdbc.driver.OracleDriver");
www.Vidyarthiplus.com
www.Vidyarthiplus.com
out.println("<BODY>");
out.println("<UL>");
while(rs.next()) {
out.println("<LI>" + rs.getString("name") + " " + rs.getString("phone"));
}
out.println("</UL>");
out.println("</BODY></HTML>");
}
catch(ClassNotFoundException e) {
out.println("Couldn't load database driver: " + e.getMessage());
}
catch(SQLException e) {
out.println("SQLException caught: " + e.getMessage());
}}}
www.Vidyarthiplus.com