You are on page 1of 167

CS6501/ CS6501 internet programming

M.I.E.T. ENGINEERING COLLEGE


(Approved by AICTE and Affiliated to Anna University Chennai)
TRICHY – PUDUKKOTTAI ROAD, TIRUCHIRAPPALLI – 620 007

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING

COURSE MATERIAL
CS6501 - INTERNET PROGRAMMING

III YEAR - V SEMESTER

M.I.E.T./CSE/III/Internet Programming
CS6501/ CS6501 internet programming

M.I.E.T. ENGINEERING COLLEGE


(Approved by AICTE and Affiliated to Anna University Chennai)
TRICHY – PUDUKKOTTAI ROAD, TIRUCHIRAPPALLI – 620 007
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
SYLLABUS (THEORY)
Sub. Code : CS6501 Branch / Year / Sem : CSE/III/V
Sub.Name : INTERNET PROGRAMMING Staff Name : P.RAMESH

SYLLABUS
CS6501 INTERNET PROGRAMMING

LTPC
3 1 0 4
UNIT I JAVA PROGRAMMING 9
An overview of Java – Data Types – Variables and Arrays – Operators – Control
Statements – Classes – Objects – Methods – Inheritance - Packages – Abstract classes –
Interfaces and Inner classes – Exception handling - Introduction to Threads – Multithreading –
String handling – Streams and I/O – Applets.

UNIT II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 8


Web 2.0: Basics-RIA Rich Internet Applications - Collaborations tools - Understanding websites
and web servers: Understanding Internet – Difference between websites and web server-
Internet technologies Overview –Understanding the difference between internet and intranet;
HTML and CSS: HTML 5.0 , XHTML, CSS 3

UNIT II I CLIENT SIDE AND SERVER SIDE PROGRAMMING 11


Java Script: An introduction to JavaScript–JavaScript DOM Model-Date and Objects,-
Regular Expressions- Exception Handling-Validation-Built-in objects-Event Handling- DHTML
with JavaScript. Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and
POST actions- Session Handling- Understanding Cookies- Installing and Configuring
Apache Tomcat Web Server;- DATABASE CONNECTIVITY: JDBC perspectives, JDBC
program example - JSP: Understanding Java Server Pages-JSP Standard Tag Library(JSTL)-
Creating HTML forms by embedding JSP code.

UNIT IV PHP and XML 8


An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in functions-
Connecting to Database – Using Cookies-Regular Expressions; XML: Basic XML- Document
Type Definition- XML Schema DOM and Presenting XML, XML Parsers and
Validation, XSL and XSLT Transformation, News Feed (RSS and ATOM).

M.I.E.T./CSE/III/Internet Programming
CS6501/ CS6501 internet programming

UNIT V INTRODUCTION TO AJAX and WEB SERVICES 9


AJAX: Ajax Client Server Architecture-XML Http Request Object-Call Back Methods; Web
Services: Introduction- Java web services Basics – Creating, Publishing ,Testing and
Describing a Web services (WSDL)- Consuming a web service, Database Driven web service
from an application – SOAP

TOTAL (L:45+T:15): 60
PERIODS
TEXT BOOKS:
1. Deitel and Deitel and Nieto, ―Internet and World Wide Web - How to Program‖, Prentice
Hall,
5th Edition, 2011.
2. Herbert Schildt, ―Java-The Complete Reference‖, Eighth Edition, Mc Graw Hill
Professional,
2011.
REFERENCES:
1. Stephen Wynkoop and John Burke ―Running a Perfect Website‖, QUE, 2nd Edition,1999.
2. Chris Bates, Web Programming – Building Intranet Applications, 3rd Edition, Wiley
Publications, 2009.
3. Jeffrey C and Jackson, ―Web Technologies A Computer Science Perspective‖,
Pearson Education, 2011.

M.I.E.T./CSE/III/Internet Programming
CS6501/ CS6501 internet programming

M.I.E.T. ENGINEERING COLLEGE


(Approved by AICTE and Affiliated to Anna University Chennai)
TRICHY – PUDUKKOTTAI ROAD, TIRUCHIRAPPALLI – 620 007

Sub. Code : CS6501 Branch/Year/Sem : CSE/III/V

Sub Name : Internet programming Staff Name :P.Ramesh

COURSE OBJECTIVE

Students will be able to:


1. Learn Java Programming.
2. Understand different Internet Technologies
3. Design and implement dynamic web page with validation using JavaScript objects and
by applying different event handling mechanisms.
4. Learn server side programs using Servlets and JSP.
5. Be exposed to java specific web services architecture

COURSE OUTCOMES

On completion of course the students will be able to:


1. .Demonstrate how the real time logics are applied to basic java programs.
2. Understand, analyze and apply the role languages like HTML, CSS and protocols in the
workings of web and web applications.
3. Create and communicate between client and server using Java and create a good, effective
and dynamic website.
4. Understand about network and security programming using Java and know about the
application of dynamic page functionality in web pages using Servlets, and JSP.
5. Design and implement simple web page in PHP, and to present data in XML format
6. Make clear a web services and client presentation using AJAX.

Prepared by Verified By

STAFF NAME HOD

P.RAMESH

Approved by

PRINCIPAL

M.I.E.T./CSE/III/Internet Programming
CS6501/ CS6501 internet programming

UNIT I

JAVA PROGRAMMING
1.1 AN OVERVIEW OF JAVA
Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java
supports the following fundamental concepts:

1.1.1 C++ Vs Java


Object - Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors -wagging, barking, eating. An object is an instance of a class. Class - A
class can be defined as a template/blue print that describes the behaviors/states that object of
its type support.

Objects in Java:
Let us now look deep into what are objects. If we consider the real- world we can find many
objects around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging, running
If you compare the software object with a real world object, they have very similar
characteristics.
Software objects also have a state and behavior. A software object's state is stored in fields and
behavior is shown via methods.

So in software development, methods operate on the internal state of an object and the object-to-
object communication is done via methods.

Classes in Java:
A class is a blue print from which individual objects are created. A sample of a class isgiven below

public class Dog{


String breed; int
age; String color;
void barking(){
}
void hungry(){
}
void sleeping(){

}
}

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

1.2 Data Types and Variables

Type Capacity Range Default


value

byte 1B ( 8 bits) -27 to 27 - 1 0

short 2B (16 bits) -215 to 215 – 1 0

int 4B (32 bits) -231 to 231 – 1 0

long 8B (64 bits) -263 to 263 – 1 0.0L

float 32 bits IEEE 754 floating point 0.0f

double 64 bits IEEE 754 floating point 0.0D

boolea
n 1 bit True / False False

‗\u0000‘ to
char 16 bits ‗\uffff‘ NA

A class can contain any of the following variable types.


Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable will
be destroyed when the method has completed.

Instance variables: Instance variables are variables within a class but outside any method.
These variables are instantiated when the class is loaded. Instance variables can be accessed
from inside any method, constructor or blocks of that particular class. Class variables: Class
variables are variables declared with in a class, outside any method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods. In the above
example, barking(), hungry() and sleeping() are methods.
Below mentioned are some of the important topics that need to be discussed when looking into classes
of the Java Language.

1.3 Array

Normally, array is a collection of similar type of elements that have contiguous memory location.

Java array is an object the contains elements of similar data type. It is a data structure where we store
similar elements. We can store only fixed set of elements in a java array.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java Array

 Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
 Random access: We can get any data located at any index position.

Disadvantage of Java Array

 Size Limit: We can store only fixed size of elements in the array. It doesn't grow its sizeat
runtime. To solve this problem, collection framework is used in java.

Example:
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;

a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}

}
Output: 10
20
70
40
50

1.4 OPERATORS AND CONTROL STATEMENTS


M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the
following groups −

 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators

The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
The following table lists the arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

Adds values on either side of the


+ (Addition) A + B will give 30
operator.

Subtracts right-hand operand from left-


- (Subtraction) A - B will give -10
hand operand.

Multiplies values on either side of the


* (Multiplication) A * B will give 200
operator.

Divides left-hand operand by right-hand


/ (Division) B / A will give 2
operand.

Divides left-hand operand by right-hand


% (Modulus) B % A will give 0
operand and returns remainder.

++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B-- gives 19

The Relational Operators

There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Checks if the values of two operands are equal or


== (equal to) (A == B) is not true.
not, if yes then condition becomes true.

Checks if the values of two operands are equal or


!= (not equal to) not, if values are not equal then condition (A != B) is true.
becomes true.

Checks if the value of left operand is greater than


> (greater than) the value of right operand, if yes then condition (A > B) is not true.
becomes true.

Checks if the value of left operand is less than the


< (less than) value of right operand, if yes then condition (A < B) is true.
becomes true.

Checks if the value of left operand is greater than


>= (greater than or equal
or equal to the value of right operand, if yes then (A >= B) is not true.
to)
condition becomes true.

Checks if the value of left operand is less than or


<= (less than or equal
equal to the value of right operand, if yes then (A <= B) is true.
to)
condition becomes true.

The Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char,
and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in
binary format they will be as follows −

a = 0011 1100

b = 0000 1101

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

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators −

Assume integer variable A holds 60 and variable B holds 13 then −

Show Examples

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Operator Description Example

Binary AND Operator copies a bit to the result (A & B) will give 12 which is
& (bitwise and)
if it exists in both operands. 0000 1100

Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is


| (bitwise or)
either operand. 0011 1101

Binary XOR Operator copies the bit if it is set (A ^ B) will give 49 which is
^ (bitwise XOR)
in one operand but not both. 0011 0001

(~A ) will give -61 which is


Binary Ones Complement Operator is unary 1100 0011 in 2's complement
~ (bitwise compliment)
and has the effect of 'flipping' bits. form due to a signed binary
number.

Binary Left Shift Operator. The left operands


A << 2 will give 240 which is
<< (left shift) value is moved left by the number of bits
1111 0000
specified by the right operand.

Binary Right Shift Operator. The left operands


A >> 2 will give 15 which is
>> (right shift) value is moved right by the number of bits
1111
specified by the right operand.

Shift right zero fill operator. The left operands


value is moved right by the number of bits A >>>2 will give 15 which is
>>> (zero fill right shift)
specified by the right operand and shifted 0000 1111
values are filled up with zeros.

The Logical Operators

The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds false, then −

Show Examples

Operator Description Example

Called Logical AND operator. If both the operands are


&& (logical and) (A && B) is false
non-zero, then the condition becomes true.

Called Logical OR Operator. If any of the two


|| (logical or) operands are non-zero, then the condition becomes (A || B) is true
true.

Called Logical NOT Operator. Use to reverses the


! (logical not) logical state of its operand. If a condition is true then !(A && B) is true
Logical NOT operator will make false.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

The Assignment Operators

Following are the assignment operators supported by Java language −

Show Examples

Operator Description Example

Simple assignment operator. Assigns values from C = A + B will assign value of A + B into
=
right side operands to left side operand. C

Add AND assignment operator. It adds right


+= operand to the left operand and assign the result to C += A is equivalent to C = C + A
left operand.

Subtract AND assignment operator. It subtracts


-= right operand from the left operand and assign the C -= A is equivalent to C = C – A
result to left operand.

Multiply AND assignment operator. It multiplies


*= right operand with the left operand and assign the C *= A is equivalent to C = C * A
result to left operand.

Divide AND assignment operator. It divides left


operand with the right operand and assign the result
/= to left operand. C /= A is equivalent to C = C / A

Modulus AND assignment operator. It takes


%= modulus using two operands and assign the result to C %= A is equivalent to C = C % A
left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Miscellaneous Operators

There are few other operators supported by Java Language.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Conditional Operator ( ? : )

Conditional operator is also known as the ternary operator. This operator consists of three operands and
is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be
assigned to the variable. The operator is written as −

variable x = (expression) ? value if true : value if false

Following is an example −

Example

public class Test {

public static void main(String args[]) {


int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}

This will produce the following result −

Output

Value of b is : 30
Value of b is : 20

instanceof Operator

This operator is used only for object reference variables. The operator checks whether the object is of a
particular type (class type or interface type). instanceof operator is written as −

( Object reference variable ) instanceof (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true. Following is an example −

Example

public class Test {

public static void main(String args[]) {

String name = "James";

// following will return true since name is type of String


M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

boolean result = name instanceof String;


System.out.println( result );
}
}

This will produce the following result −

Output

true

This operator will still return true, if the object being compared is the assignment compatible with the
type on the right. Following is one more example −

Example

class Vehicle {}

public class Car extends Vehicle {

public static void main(String args[]) {

Vehicle a = new Car();


boolean result = a instanceof Car;
System.out.println( result );
}
}

This will produce the following result −

Output

true

Precedence of Java Operators

Operator precedence determines the grouping of terms in an expression. This affects how an expression
is evaluated. Certain operators have higher precedence than others; for example, the multiplication
operator has higher precedence than the addition operator −

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than
+, so it first gets multiplied with 3 * 2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix >() [] . (dot operator) Left toright

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Unary >++ - - ! ~ Right to left

Multiplicative >* / Left to right

Additive >+ - Left to right

Shift >>> >>> << Left to right

Relational >> >= < <= Left to right

Equality >== != Left to right

Bitwise AND >& Left to right

Bitwise XOR >^ Left to right

Bitwise OR >| Left to right

Logical AND >&& Left to right

Logical OR >|| Left to right

Conditional ?: Right to left

Assignment >= += -= *= /= %= >>= <<= &= ^= |= Right to left

CONTROL STATEMENTS
There may be a situation when we need to execute a block of code several number of times, and is often
referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop do...while
Loop for Loop

As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:


A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{

//Statements
}

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true.

Here, key point of the while loop is that the loop might not ever run. When the expression is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.

Example:
public class Test {

public static void main(String args[]) { int x =


10;
while( x < 20 ) { System.out.print("value of x :
" + x ); x++;
System.out.print("\n");
}
}
}
This would produce the following result:
value of x : 10 value of
x : 11 value of x : 12
value of x : 13 value of
x : 14 value of x : 15
value of x : 16 value of
x : 17 value of x : 18
value of x : 19

The do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least
one time.
Syntax:

The syntax of a do...while loop is:


do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute
once before the Boolean is tested.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the
loop execute again. This process repeats until the Boolean expression is false.

Example:
public class Test {
public static void main(String args[]){ int x =
10;

do{
System.out.print("value of x : " + x ); x++;
System.out.print("\n");
}while( x < 20 )
}

}
This would produce the following result:
value of x : 10 value of
x : 11 value of x : 12
value of x : 13 value of
x : 14 value of x : 15
value of x : 16 value of
x : 17 value of x : 18
value of x : 19

The for Loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute
a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.

Syntax:
The syntax of a for loop is:
for(initialization; Boolean_expression; update)

{
//Statements
}
Here is the flow of control in a for loop:
The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

The Boolean expression is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then update step, then Boolean expression). After the Boolean
expression is false, the for loop terminates.

Example:
public class Test {
public static void main(String args[]) {

for(int x = 10; x < 20; x = x+1) {


System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
This would produce the following result:
value of x : 10 value of
x : 11 value of x : 12
value of x : 13 value of
x : 14 value of x : 15
value of x : 16 value of
x : 17 value of x : 18
value of x : 19

Enhanced for loop in Java:


As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{

//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for block and
its value would be the same as the current array element.
Expression: This evaluates to the array you need to loop through. The expression can be an
array variable or method call that returns an array.

Example:
public class Test {
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

public static void main(String args[]){ int []


numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"}; for(
String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}

This would produce the following result:


10,20,30,40,50,

James,Larry,Tom,Lacy,

The break Keyword:


The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or
a switch statement.

The break keyword will stop the execution of the innermost loop and start executing the next line of code
after the block.

Syntax:
The syntax of a break is a single statement inside any loop:

break;

Example:
public class Test {
public static void main(String args[]) { int []
numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) { if( x ==
30 ) {
break;
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

}
System.out.print( x );
System.out.print("\n");

}
}
This would produce the following result:
10

20

The continue Keyword:


The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.

In a for loop, the continue keyword causes flow of control to immediately jump to the update
statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.
Syntax: The syntax of a continue is a single statement inside any loop:
continue;

Example:
public class Test {

public static void main(String args[]) { int []


numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) { if( x ==
30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");

}
}
}
This would produce the following result:
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

10
20
40
50

1.5 CLASSES – OBJECTS – METHODS


The object-oriented extension of Objective CAML is integrated with the functional and imperative
kernels of the language, as well as with its type system. Indeed, this last point is unique to the language.
Thus we have an object-oriented, statically typed language, with type inference. This extension allows
definition of classes and instances, class inheritance (including multiple inheritance), parameterized
classes, and abstract classes. Class interfaces are generated from their definition, but may be made more
precise through a signature, similarly to what is done for modules.

Object-Oriented Terminology
We summarize below the main object-oriented programming terms.
class:
a class describes the contents of the objects that belong to it: it describes an aggregate of data
fields (called instance variables), and defines the operations (called methods).
object:
an object is an element (or instance) of a class; objects have the behaviors of their class. The
object is the actual component of programs, while the class specifies how instances are created
and how they behave.
method:
a method is an action which an object is able to perform.

sending a message
sending a message to an object means asking the object to execute or invoke one of its methods.

Class Declaration
The simplest syntax for defining a class is as follows. We shall develop this definition throughout this
chapter.

Syntax

class name p1 ...pn =

object

instance variables

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

methods

end

p1, ..., pn are the parameters for the constructor of the class; they are omitted if the class has no
parameters.

An instance variable is declared as follows:

Syntax

val name = expr

or

val mutable name = expr

When a data field is declared mutable, its value may be modified. Otherwise, the value is always the one
that was computed when expr was evaluated during object creation.

Methods are declared as follows:

Syntax

method name p1 ...pn = expr

Other clauses than val and method can be used in a class declaration: we shall introduce them as needed.

Our first class example.


We start with the unavoidable class point:

 the data fields x and y contain the coordinates of the point,


 two methods provide access to the data fields (get_x and get_y),
 two displacement methods (moveto: absolute displacement) and (rmoveto: relative displacement),
 one method presents the data as a string (to_string),
 one method computes the distance to the point from the origin (distance).

# class point (x_init, y_init) =


object
val mutable x = x_init
val mutable y = y_init
method get_x = x
method get_y = y
method moveto (a,b) = x <- a ; y <- b
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

method rmoveto (dx,dy) = x <- x + dx ; y <- y + dy


method to_string () =
"( " ^ (string_of_int x) ^ ", " ^ (string_of_int y) ^")"
method distance () = sqrt (float(x*x + y*y))
end ;;

Note that some methods do not need parameters; this is the case for get_x and get_y. We usually access
instance variables with parameterless methods.

After we declare the class point, the system prints the following text:
class point :
int * int ->
object
val mutable x : int
val mutable y : int
method distance : unit -> float
method get_x : int
method get_y : int
method moveto : int * int -> unit
method rmoveto : int * int -> unit
method to_string : unit -> string
end

This text contains two pieces of information. First, the type for objects of the class; this type will be
abbreviated as point. The type of an object is the list of names and types of methods in its class. In our
example, point is an abbreviation for:

< distance : unit -> unit; get_x : int; get_y : int;


moveto : int * int -> unit; rmoveto : int * int -> unit;
to_string : unit -> unit >

Next, we have a constructor for instances of class point, whose type is int*int -> oint. The constructor
allows us to construct point objects (we´ll just say ``points'' to be brief) from the initial values provided as
arguments. In this case, we construct a point from a pair of integers (meaning the initial position). The
constructor point is used with the keyword new.
It is possible to define class types:

# type simple_point = < get_x : int; get_y : int; to_string : unit -> unit > ;;
type simple_point = < get_x : int; get_y : int; to_string : unit -> unit >

1.6 INHERITANCE
Inheritance can be defined as the process where one object acquires the properties of another. With
the use of inheritance the information is made manageable in a hierarchical order.
When we talk about inheritance, the most commonly used keyword would be extends and
implements. These words would determine whether one object IS-A type of another. By using these
keywords we can make one object acquire the properties of another object

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

IS-A Relationship:
IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used
to achieve inheritance.
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{

}
public class Dog extends Mammal{
}
Now, based on the above example, In Object Oriented terms, the following are true:
Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.

Mammal and Reptile are subclasses of Animal class.


Dog is the subclass of both Mammal and Animal classes.
if we consider the IS-A relationship, we can say:
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence : Dog IS-A Animal as well
With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.

Example:
public class Dog extends Mammal{
public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This would produce the following result:

true true
true
Since we have a good understanding of the extends keyword let us look into how the
implements keyword is used to get the IS-A relationship.
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be
extended by the classes.

Example:
public interface Animal {}
public class Mammal implements Animal{
}
public class Dog extends Mammal{
}

The instanceof Keyword:


Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and
dog is actually an Animal
interface Animal{}

class Mammal implements Animal{}


public class Dog extends Mammal{ public static
void main(String args[]){
Mammal m = new Mammal();

Dog d = new Dog();


System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This would produce the following result:

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

true true
true

HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class HAS-A
certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:

public class Vehicle{} public


class Speed{}
public class Van extends Vehicle{ private
Speed sp;
}In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To
achieve this, the Van class hides the implementation details from the users of the Van class. So basically
what happens is the users would ask the Van class to do a certain action and the Van class will either do
the work by itself or ask another class to perform the action.

A very important fact to remember is that Java only supports only single inheritance. This means that a
class cannot extend more than one class. Therefore following is illegal:
public class extends Animal, Mammal{}
However, a class can implement one or more interfaces. This has made Java get rid of the
impossibility of multiple inheritance.

1.7 PACKAGES and ABSTRACT CLASSES


Java Package:
In simple, it is a way of categorizing the classes and interfaces. When developing applications in Java,
hundreds of classes and interfaces will be written, therefore categorizing these classes is a must as well
as makes life much easier.

Import statements:
In Java if a fully qualified name, which includes the package and the class name, is given then the
compiler can easily locate the source code or classes. Import statement is a way of giving the proper
location for the compiler to find that particular class.
For example, the following line would ask compiler to load all the classes available in directory
java_installation/java/io :

import java.io.*;
For our case study, we will be creating two classes. They are Employee and EmployeeTest.
First open notepad and add the following code. Remember this is the Employee class and the class is
a public class. Now, save this source file with the name Employee.java.

The Employee class has four instance variables name, age, designation and salary. The class has one
explicitly defined constructor, which takes a parameter.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

import java.io.*; public class


Employee{

String name; int age;


String designation; double
salary;
// This is the constructor of the class Employee public
Employee(String name){
this.name = name;
}
// Assign the age of the Employee to the variable age. public
void empAge(int empAge){
age = empAge;
}
/* Assign the designation to the variable designation.*/ public
void empDesignation(String empDesig){
designation = empDesig;
}
/* Assign the salary to the variable salary.*/ public
void empSalary(double empSalary){
salary = empSalary;
}
/* Print the Employee details */ public
void printEmployee(){

System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + salary);
}

Given below is the EmployeeTest class, which creates two instances of the class Employee and
invokes the methods for each object to assign values for each variable.

Save the following code in EmployeeTest.java file

import java.io.*;

public class EmployeeTest{

public static void main(String args[]){

/* Create two objects using constructor */

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Employee empOne = new Employee("James Smith");


Employee empTwo = new Employee("Mary Anne");

// Invoking methods for each object created


empOne.empAge(26); empOne.empDesignation("Senior
Software Engineer"); empOne.empSalary(1000);

empOne.printEmployee();

empTwo.empAge(21);
empTwo.empDesignation("Software Engineer");
empTwo.empSalary(500); empTwo.printEmployee();
}
}
Now, compile both the classes and then run EmployeeTest to see the result as follows:

C :> javac Employee.java


C :> vi EmployeeTest.java
C :> javac EmployeeTest.java
C :> java EmployeeTest
Name:James Smith
Age:26

Designation:Senior Software Engineer


Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0

Abstraction
Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be
instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are
all accessed in the same manner. You just cannot create an instance of the abstract class.

If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclass.
This is typically how abstract classes come about during the design phase. A parent class contains the
common functionality of a collection of child classes, but the parent class itself is too abstract to be used
on its own.

Abstract Class:
Use the abstract keyword to declare a class abstract. The keyword appears in the class
declaration somewhere before the class keyword.

/* File name : Employee.java */ public


abstract class Employee
{
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

private String name; private


String address; private int
number;
public Employee(String name,
String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name; this.address
= address; this.number =
number;
}
public double computePay()
{

System.out.println("Inside Employee computePay"); return


0.0;
}

public void mailCheck()


{
System.out.println("Mailing a check to " + this.name + " " +
this.address);
}

public String toString()


{
return name + " " + address + " " + number;
}

public String getName()


{

return name;
}
public String getAddress()
{

return address;
}

public void setAddress(String newAddress)


{
address = newAddress;
}

public int getNumber()

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

{
return number;
}
}

Notice that nothing is different in this Employee class. The class is now abstract, but it still has three
fields, seven methods, and one constructor.
Now if you would try as follows:
/* File name : AbstractDemo.java */ public
class AbstractDemo
{
public static void main(String [] args)
/* Following is not allowed and would raise error */

Employee e = new Employee("George W.", "Houston, TX", 43);

System.out.println("\n Call mailCheck using Employee reference--");


e.mailCheck();

}
}
When you would compile above class then you would get the following error:

Employee.java:46: Employee is abstract; cannot be instantiated Employee e


= new Employee("George W.", "Houston, TX", 43)

1.8 INTERFACES AND INNER CLASSES

An interface is a collection of abstract methods. A class implements an interface, thereby


inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two
different concepts. A class describes the attributes and behaviors of an object. An interface contains
behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be
defined in the class.

An interface is similar to a class in the following ways:

An interface can contain any number of methods.

An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.

The bytecode of an interface appears in a .class file.


M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Interfaces appear in packages, and their corresponding bytecode file must be in a


directory structure that matches the package name.

Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:

Example:

Let us look at an example that depicts encapsulation:

/* File name : NameOfInterface.java */ import


java.lang.*;

//Any number of import statements

public interface NameOfInterface

{
//Any number of final, static fields

//Any number of abstract method declarations\


}

Interfaces have the following properties:


An interface is implicitly abstract. You do not need to use the abstract keyword when
declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
Methods in an interface are implicitly public.

Example:

/* File name : Animal.java */


interface Animal {

public void eat(); public


void travel();

Implementing Interfaces:

When a class implements an interface, you can think of the class as signing a contract, agreeing to
perform the specific behaviors of the interface. If a class does not perform all the behaviors of the
interface, the class must declare itself as abstract.

A class uses the implements keyword to implement an interface. The implements keyword appears
in the class declaration following the extends portion of the declaration.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

/* File name : MammalInt.java */


public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");

public void travel(){


System.out.println("Mammal travels");

public int noOfLegs(){ return


0;

public static void main(String args[]){


MammalInt m = new MammalInt(); m.eat();
m.travel();
}

This would produce the following result:

Mammal eats

Mammal travels

When overriding methods defined in interfaces there are several rules to be followed:

Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.

The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.

An implementation class itself can be abstract and if so interface methods need not be
implemented.

When implementation interfaces there are several rules:

A class can implement more than one interface at a time.

A class can extend only one class, but implement many interfaces.

An interface can extend another interface, similarly to the way that a class can extend another
class.

Extending Interfaces:
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

An interface can extend another interface, similarly to the way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods of
the parent interface.

The following Sports interface is extended by Hockey and Football interfaces.


//Filename: Sports.java public
interface Sports
{
public void setHomeTeam(String name); public
void setVisitingTeam(String name);
}

//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points); public
void visitingTeamScored(int points);
public void endOfQuarter(int quarter);

}
//Filename: Hockey.jav
public interface Hockey extends Sports
{
public void homeGoalScored(); public void
visitingGoalScored(); public void
endOfPeriod(int period); public void
overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from Sports.

Extending Multiple Interfaces:


A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not
classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as:
public interface Hockey extends Sports, Event

Tagging Interfaces:
The most common use of extending interfaces occurs when the parent interface does not contain any
methods. For example, the MouseListener interface in the java.awt.event package extended
java.util.EventListener, which is defined as:
package java.util;
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

public interface EventListener {}


An interface with no methods in it is referred to as a tagging interface. There are two basic design
purposes of tagging interfaces:
Creates a common parent: As with the EventListener interface, which is extended by dozens of other
interfaces in the Java API, you can use a tagging interface to create a common parent among a group of
interfaces. For example, when an interface extends EventListener, the JVM knows that this particular
interface is going to be used in an event delegation scenario.

1.9 EXCEPTION HANDLING

Exception

An exception is a problem that arises during the execution of a program. An exception can occur for
many different reasons, including the following:
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run out of
memory.

Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following:

try

{
//Protected code
}catch(ExceptionName e1)
{

//Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an exception
occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of
exception that occurred is listed in a catch block, the exception is passed to the catch block much as an
argument is passed into a method parameter.
Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd element
of the array which throws an exception.

// File Name : ExcepTest.java import


java.io.*;

public class ExcepTest{

public static void main(String args[]){ try{


M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

int a[] = new int[2];


System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);

}
System.out.println("Out of the block");
}
}

This would produce the following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


Out of the block
Multiple catch Blocks:
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the
following:

try
{
//Protected code
}catch(ExceptionType1 e1)
{

//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of them after a
single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in
the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the
exception passes down to the second catch statement. This continues until the exception either is caught
or falls through all catches, in which case the current method stops execution and the exception is
thrown down to the previous method on the call stack.

Example:
Here is code segment showing how to use multiple try/catch statements.
Try
{
file = new FileInputStream(fileName); x =
(byte) file.read();

}catch(IOException i)
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

{
i.printStackTrace(); return -
1;

}catch(FileNotFoundException f) //Not valid!


{

f.printStackTrace(); return -
1;

1.10 INTRODUCTION TO THREADS


1.10.1 Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and
then dies. Following diagram shows complete life cycle of a thread.
New: A new thread begins its life cycle in the new state. It remains in this state until the program starts
the thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is
considered to be executing its task.

Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to
perform a task.A thread transitions back to the runnable state only when another thread signals the
waiting thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time.
A thread in this state transitions back to the runnable state when that time interval expires or when
the event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state when it completes its task or otherwise
terminates.

Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in which threads
are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time
before lower-priority threads. However, thread priorities cannot guarantee the order in which threads
execute and very much platform dependentant.

Create Thread by Implementing Runnable Interface:


If your class is intended to be executed as a thread then you can achieve this by implementing
Runnable interface. You will need to follow three basic steps:

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Step 1:
As a first step you need to implement a run() method provided by Runnable interface. This method
provides entry point for the thread and you will put you complete business logic inside this method.
Following is simple syntax of run() method:
public void run( )

Step 2:
At second step you will instantiate a Thread object using the following constructor:
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and
threadName is the name given to the new thread.

Step 3
Once Thread object is created, you can start it by calling start( ) method, which executes a call to run(
) method. Following is simple syntax of start() method:
void start( );

Example:
Here is an example that creates a new thread and starts it running:
class RunnableDemo implements Runnable { private
Thread t;

private String threadName;


RunnableDemo( String name){ threadName = name;
System.out.println("Creating " + threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);

// Let the thread sleep for a while.


Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");

}
System.out.println("Thread " + threadName + " exiting.");
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

public void start ()

{
System.out.println("Starting " + threadName ); if (t ==
null)
{
t = new Thread (this, threadName); t.start
();
}

public class TestThread {

public static void main(String args[]) {

RunnableDemo R1 = new RunnableDemo( "Thread-1");

R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();

}
}

This would produce the following result:


Creating Thread-1

Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3

Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2

Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

1.11 MULTITHREADING

Create Thread by Extending Thread Class:


The second way to create a thread is to create a new class that extends Thread class using the following
two simple steps. This approach provides more flexibility in handling multiple threads created using
available methods in Thread class.

Step 1
You will need to override run( ) method available in Thread class. This method provides entry point for
the thread and you will put you complete business logic inside this method. Following is simple syntax
of run() method:
public void run( )

Step 2
Once Thread object is created, you can start it by calling start( ) method, which executes a call to run(
) method. Following is simple syntax of start() method:
void start( );
Here is the preceding program rewritten to extend Thread:

class ThreadDemo extends Thread { private


Thread t;
private String threadName;
ThreadDemo( String name){ threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName ); try {

for(int i = 4; i > 0; i--)


System.out.println("Thread: " + threadName + ", " + i); // Let
the thread sleep for a while.
Thread.sleep(50);

}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

public void start ()


{
System.out.println("Starting " + threadName ); if (t ==
null)
{
t = new Thread (this, threadName); t.start
();
}
}
}

public class TestThread {

public static void main(String args[]) {

ThreadDemo T1 = new ThreadDemo( "Thread-1");

T1.start();

ThreadDemo T2 = new ThreadDemo( "Thread-2");


T2.start();

}
}

This would produce the following result:

Creating Thread-1

Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4

Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread:Thread-1,2
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

1.12 STRING HANDLING


String Handling in Java
The basic aim of String Handling concept is storing the string data in the main memory (RAM),
manipulating the data of the String, retrieving the part of the String etc. String Handling provides a lot
of concepts that can be performed on a string such as concatenation of string, comparison of string, find
sub string etc.

Character
It is an identifier enclosed within single quotes (' ').
Example: 'A', '$', 'p'

String:
String is a sequence of characters enclosed within double quotes (" ") is known as String.
Example: "Java Programming".

In java programming to store the character data we have a fundamental datatype called char. Similarly to
store the string data and to perform various operation on String data, we have three predefined classes
they are:

 String
 StringBuffer
 StringBuilder

How to create String object?


There are two ways to create String object:
1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string already
exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

In the above example only one object will be created. Firstly JVM will not find any string object with the
value "Welcome" in string constant pool, so it will create a new object. After that it will find the string
with the value "Welcome" in the pool, it will not create new object but will return the reference to the
same instance.

2) By new keyword

1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non
pool).

Java String Example

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

OUTPUT:
java
strings
example

1.13 STREAMS AND I/O


IO Stream
The java.io package contains nearly every class you might ever need to perform input and output (I/O) in
Java. All these streams represent an input source and an output destination. The stream in the java.io
package supports many data such as primitives, Object, localized characters, etc.

A stream can be defined as a sequence of data. The InputStream is used to read data from a source
and the OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers
very basic functionality related to streams and I/O. We would see most commonly used example one
by one:

Byte Streams
Java byte streams are used to perform input and output of 8 -bit bytes. Though there are many classes
related to byte streams but the most frequently used classes are , FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an input
file into an output file:
import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException


{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt"); out = new
FileOutputStream("output.txt");
int c;

while ((c = in.read()) != -1) {


out.write(c);
}
}finally {

if (in != null) {
in.close();
}
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

if (out != null) {
out.close();

}
}}

now let's have a file input.txt with the following content:

This is test for copy file.

As a next step, compile above program and execute it, which will result in creating output.txt file with
the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the
following:

$javac CopyFile.java

$java CopyFile

Character Streams

Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character streams
are used to perform input and output for 16-bit unicode. Though there are many classes related to
character streams but the most frequently used classes are , FileReader and FileWriter.. Though
internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here major
difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

We can re-write above example which makes use of these two classes to copy an input file (having
unicode characters) into an output file:

import java.io.*;

public class CopyFile {

public static void main(String args[]) throws IOException


{
FileReader in = null;
FileWriter out = null;

try {

in = new FileReader("input.txt"); out =


new FileWriter("output.txt");

int c;

while ((c = in.read()) != -1) {


out.write(c);
}

}finally {
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

if (in != null) {
in.close();
}

if (out != null) {
out.close();
}

}
}

Now let's have a file input.txt with the following content:

This is test for copy file.


As a next step, compile above program and execute it, which will result in creating output.txt file with
the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the
following:
$javac CopyFile.java
$java CopyFile

Standard Streams
All the programming languages provide support for standard I/O where user's program can take input
from a keyboard and then produce output on the computer screen. If you are aware if C or C++
programming languages, then you must be aware of three standard devices STDIN, STDOUT and
STDERR. Similar way Java provides following three standard streams
Standard Input: This is used to feed the data to user's program and usually a keyboard is used as
standard input stream and represented as System.in.
Standard Output: This is used to output the data produced by the user's program and usually
a computer screen is used to standard output stream and represented as
System.out.

Standard Error: This is used to output the error data produced by the user's program and
usually a computer screen is used to standard error stream and represented as
System.err.

Following is a simple program which creates InputStreamReader to read standard input stream until
the user types a "q":

import java.io.*;

public class ReadConsole {

public static void main(String args[]) throws IOException


M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

InputStreamReader cin = null;

try {

cin = new InputStreamReader(System.in);


System.out.println("Enter characters, 'q' to quit."); char c;
do {
c = (char) cin.read();
System.out.print(c);

} while(c != 'q'); }finally


{

if (cin != null) {
cin.close();
}
}
}
}

Let's keep above code in ReadConsole.java file and try to compile and execute it as below. This
program continues reading and outputting same character until we press 'q':

$javac ReadConsole.java $java


ReadConsole

Enter characters, 'q' to quit. 1 1

eeqq

1.14 APPLETS

An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java application,
including the following:

An applet is a Java class that extends the java.applet.Applet class.

A main() method is not invoked on an applet, and an applet class will not define main().
Applets are designed to be embedded within an HTML page.

Applets have strict security rules that are enforced by the Web browser. The security of an
applet is often referred to as sandbox security, comparing the applet to a child playing in a
sandbox with various rules that must be followed.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Life Cycle of an Applet:


Four methods in the Applet class give you the framework on which you build any serious applet:

init: This method is intended for whatever initialization is needed for your applet. It is called
after the param tags inside the applet tag have been processed.
start: This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to other
pages.
stop: This method is automatically called when the user moves off the page on which the applet
sits. It can, therefore, be called repeatedly in the same applet.
destroy: This method is only called when the browser shuts down normally. Because applets
are meant to live on an HTML page, you should not normally leave resources behind after a
user leaves the page that contains the applet.
paint: Invoked immediately after the start() method, and also any time the applet needs to repaint
itself in the browser. The paint() method is actually inherited from the java.awt.

A "Hello, World" Applet:

The following is a simple applet named HelloWorldApplet.java:

import java.applet. *; import


java.awt.*;

public class HelloWorldApplet extends Applet

{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}

These import statements bring the classes into the scope of our applet class:

java.applet.Applet.

java.awt.Graphics.

without those import statements, the Java compiler would not recognize the classes Applet and
Graphics, which the applet class refers to.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

The Applet CLASS:

Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that
a derived Applet class may call to obtain information and services from the browser context.

These include methods that do the following:

Get applet parameters

Get the network location of the HTML file that contains the applet
Get the network location of the applet class directory
Print a status message in the browser
Fetch an image
Fetch an audio clip

Play an audio clip


Resize the applet

The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.

The "Hello, World" applet is complete as it stands. The only method overridden is the paint
method.

Invoking an Applet:

An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.

The <applet> tag is the basis for embedding an applet in an HTML file. Below is an example that invokes
the "Hello, World" applet:

<html>

<title>The Hello, World Applet</title>


<hr>

<applet code="HelloWorldApplet.class" width="320" height="120"> If your


browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>

<hr>
</html>

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

UNIT II

WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 8

WEB 2.0: BASICS-RIA RICH INTERNET APPLICATIONS

2.1 WEB 2.0: BASICS

Web 2.0 (pronounced web two point oh) describes World Wide Web websites that emphasize user-
generated content, usability (ease of use, even by non-experts), and interoperability (this means that a
website can work well with other products, systems and devices) for end users. The term was popularized
by Tim O'Reilly and Dale Dougherty at the O'Reilly Media Web 2.0 Conference in late 2004, though it
was coined by Darcy DiNucci in 1999.[1][2][3][4] Web 2.0 does not refer to an update to any technical
specification, but to changes in the way Web pages are designed and used.

A Web 2.0 website may allow users to interact and collaborate with each other in a social media dialogue
as creators of user-generated content in a virtual community, in contrast to the first generation of Web
1.0-era websites where people were limited to the passive viewing of content. Examples of Web 2.0
include social networking sites and social media sites (e.g., Facebook), blogs, wikis, folksonomies
("tagging" keywords on websites and links), video sharing sites (e.g., YouTube), hosted services, Web
applications ("apps"), collaborative consumption platforms, and mashup applications.

Whether Web 2.0 is substantively different from prior Web technologies has been challenged by World
Wide Web inventor Tim Berners-Lee, who describes the term as jargon.[5] His original vision of the Web
was "a collaborative medium, a place where we [could] all meet and read and write". [6][7] On the other
hand, the term Semantic Web (sometimes referred to as Web 3.0)[8] was coined by Berners-Lee to refer to
a web of content where the meaning can be processed by machines

Advantages of Web 2.0:

 Available at any time, any place.


 Variety of media.
 Ease of usage.
 Learners can actively be involved in knowledge building.
 Can create dynamic learning communities.
 Everybody is the author and the editor, every edit that has been made can be tracked.
 User friendly.
 Updates in wiki are immediate and it offers more sources for researchers.
 Provides real-time discussion.

2.1.1 Web 2.0 features:

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

It allows users to collectively classify and find dynamic information that flows two ways between site
owner and site user by means of evaluation, comments and reviews. Site users can add content for others
to see. Web 2.0 sites provide APIs to allow automated usage by an app or mashup like it provides
location metadata that can be processed by a simple browser tool.

The future:

The business forecasters are all claiming that Web 2.0 is an intermediate phase between the World Wide
Web‘s existence and a more established phase they‘re calling Web 3.0.

The web as a whole can be designed more intelligently around serving a user‘s wants or needs. The
developers and authors, singly or in collaboration, can use self-descriptions or similar techniques so that
the information provided by the new context-aware program is relevant to the user.

Web 1.0 Web 2.0 Web 3.0


Content Speedy Ubiquitous

destination sites and personal more timely information and more available at any time, anywhere,
portals efficient tools to find information through any channel or device
Search Collaborative Efficient

critical mass of content drives actions of user a mass, police, and relevant and contextual information
need for search engines prioritize content findable instantly
Commerce Trust-worthy Individualized

goes mainstrean; digital good user establish trust networks and filtered and shared by friends or
rise home trust radars trust networks

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

2.1.2 Web 2.0 Technologies:

 The client-side (Web browser) technologies used in Web 2.0 development include Ajax and
JavaScript frameworks. Ajax programming uses JavaScript and the Document Object Model to
update selected regions of the page area without undergoing a full page reload.
 To allow users to continue to interact with the page, communications such as data requests going
to the server are separated from data coming back to the page (asynchronously). Otherwise, the
user would have to routinely wait for the data to come back before they can do anything else on
that page, just as a user has to wait for a page to complete the reload.
 This also increases overall performance of the site, as the sending of requests can complete
quicker independent of blocking and queueing required to send data back to the client. The data
fetched by an Ajax request is typically formatted in XML or JSON (JavaScript Object Notation)
format, two widely used structured data formats.
 Since both of these formats are natively understood by JavaScript, a programmer can easily use
them to transmit structured data in their Web application. When this data is received via Ajax, the
JavaScript program then uses the Document Object Model (DOM) to dynamically update the
Web page based on the new data, allowing for a rapid and interactive user experience. In short,
using these techniques, Web designers can make their pages function like desktop applications.
For example, Google Docs uses this technique to create a Web-based word processor.
 As a widely available plugin independent of W3C standards (the World Wide Web Consortium is
the governing body of Web standards and protocols), Adobe Flash is capable of doing many
things that were not possible pre-HTML5. Of Flash's many capabilities, the most commonly used
is its ability to integrate streaming multimedia into HTML pages.
 With the introduction of HTML5 in 2010 and growing concerns with Flash's security, the role of
Flash is decreasing. In addition to Flash and Ajax, JavaScript/Ajax frameworks have recently
become a very popular means of creating Web 2.0 sites. At their core, these frameworks use the
same technology as JavaScript, Ajax, and the DOM.
 However, frameworks smooth over inconsistencies between Web browsers and extend the
functionality available to developers. Many of them also come with customizable, prefabricated
'widgets' that accomplish such common tasks as picking a date from a calendar, displaying a data
chart, or making a tabbed panel. On the server-side, Web 2.0 uses many of the same technologies
as Web 1.0.
 Languages such as Perl, PHP, Python, Ruby, as well as Enterprise Java (J2EE) and
Microsoft.NET Framework, are used by developers to output data dynamically using information
from files and databases. This allows websites and web services to share machine readable
formats such as XML (Atom, RSS, etc.) and JSON.
 When data is available in one of these formats, another website can use it to integrate a portion of
that site's functionality.

2.1.3 Merits and Demerits:

Advantages of Web 2.0 are:

1. Web 2.0 provides large varieties of information just in one click.


2. Ability to search data and information appeared recently.
3. Web 2.0 is easy to handle.
4. Great varieties of entries is available on the internet.
5. Easy to search information in various languages.
6. Allows people to participate in discussion and forums to share their views and ideas,
7. Social media sites to share things happening around the world.
8. Web 2.0 allows people to complete and correct wrong information.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

9. Easy and fast method to communicate with people via email and other services.
10. Ability to share files or documents with friends and family.
11. Easy and cheap method to promote your business online.
12. Opportunity to stay in touch with many people by web 2.0
13. Opportunity to know different people staying around the world.
14. Easy to share lots of information simply sitting at home.
15. Good quality of images and video can also be shared.

Disadvantages of Web 2.0 are:

1. Sometimes results shown are different from what is asked.


2. Sometimes Translation of results is not of good quality.
3. Sometimes It takes too long to get answer to what is asked.
4. Risk of getting wrong information.
5. Not able to contact people if you dont know the email address or website address.
6. Risk of Spamming , Fraud and Virus attack.
7. Sometimes Lack of privacy.

2.2 RIA (Rich Internet Application):-

 RIA (Rich Internet Application) is defined as a web application that is designed to give the same
features and functions associated with desktop applications.
 HTML is not having much capability and performance in web apps
 Users need desktop type of interaction from web apps
 RIA fulfils this need, user interactivity
 It is the 3rd generation of web apps
 It runs inside a web browser and does not need any special software installation (plug&play)

2.2.1 Features of RIA:-


 Ability to work on web, presents complex info to users
 Rich set of visual elements like image, video, graphics, etc
 It works in real-time, helps business services
 Users can know how to use complex apps
 Reduce unnecessary page navigations
 Responsiveness, interactivity
 Ex: Apache Flex, Quick PHP, .NET framework, JavaFX

2.2.2 Framework of RIA:-


GUI logic is moved from server to client

 Because GUI is executed in browser, CPU time needed to generate GUI is taken off from server,
thereby making server free for more CPU cycles to run app logic
 GUI state is kept in browser

 Because GUI is separated from app logic, it is easy to implement

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 RIA communicate with servers by exchanging data, not the GUI code (HTML, CSS, JS)
 Data exchange: XML via HTTP (or) JSON via HTTP

 If server side becomes completely free, then the app logic will become very clear to understand
 App logic just need to focus on data in and data out

Technologies used in RIA:-


 HTML5+CSS3, Java script, JS framework, jQuery, jQuery Mobile, AngularJS, SmartClient,
GWT, JavaFX, Flex, MS Silverlight

2.2.3 Benefits of RIA:-


 Increased productivity, new customers
 Reduced operational costs
 No installation required
 Easy upgrade
 Available through internet
 Rich and more responsive UI
 Client/server balance
 Asynchronous communication
 Efficiency in network

Limitations of RIA:-
 Too fast in displaying contents
 Maintain balance between HTML and RIA
 GUI logic and app logic might be in different languages
 Search engines are declining
 Proprietary
 Loss of integrity

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 Complicated to develop apps, what to cache, what not to.


 Breaks web page paradigm

2.3 COLLABORATIONS TOOLS


Collaboration tools:-

 Collaboration tools allow a group of people work together virtually in real-time over the internet.

Features:-

Easy to use and set up. Clean interface

Secure Permissions control

Ability to upload documents File storage

Scalable Document locking

Examples:-

Tool Use

Google Docs Upload/modify/retrieve files anytime

Dropbox Store/share/sync files online

Blogger Blogging site of google

Wordpress Flexible, FOSS, easy blogging tool

PDFcatch e-books, PDF search engine

SlideShare PPT, PDF share/upload/download

Youtube Upload/download/view videos

Facebook Upload/download/view micro contents

Twitter Upload/doenload/view thoughts

Advantages of Collaboration tools:-

 Reduces distance between employees


 Work in same room, together in same documents
 No need to send documents back and forth between offices
 Communication between employees is improved
 Increases team work and transparency
 Easy to keep track of projects
 Easy to generate reports
 Team members can be present anywhere
 Online chatting
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 IRC (Internet relay Chat)


 Video conferencing

2.4 UNDERSTANDING WEBSITES AND WEB SERVERS

A website is a collection of related web pages, including multimedia content, typically identified with a
common domain name, and published on at least one web server. A website may be accessible via a
public Internet Protocol (IP) network, such as the Internet, or a private local area network (LAN), by
referencing a uniform resource locator (URL) that identifies the site.

Websites have many functions and can be used in various fashions; a website can be a personal website, a
commercial website for a company, a government website or a non-profit organization website. Websites
are typically dedicated to a particular topic or purpose, ranging from entertainment and social networking
to providing news and education. All publicly accessible websites collectively constitute the World Wide
Web, while private websites, such as a company's website for its employees, are typically a part of an
intranet.

Web pages, which are the building blocks of websites, are documents, typically composed in plain text
interspersed with formatting instructions of Hypertext Markup Language (HTML, XHTML). They may
incorporate elements from other websites with suitable markup anchors. Web pages are accessed and
transported with the Hypertext Transfer Protocol (HTTP), which may optionally employ encryption
(HTTP Secure, HTTPS) to provide security and privacy for the user. The user's application, often a web
browser, renders the page content according to its HTML markup instructions onto a display terminal.

Hyperlinking between web pages conveys to the reader the site structure and guides the navigation of the
site, which often starts with a home page containing a directory of the site web content. Some websites
require user registration or subscription to access content. Examples of subscription websites include
many business sites, news websites, academic journal websites, gaming websites, file-sharing websites,
message boards, web-based email, social networking websites, websites providing real-time stock market
data, as well as sites providing various other services. As of 2016 end users can access websites on a
range of devices, including desktop and laptop computers, tablet computers, smartphones and smart TVs.

Static website

A static website is one that has web pages stored on the server in the format that is sent to a client web
browser. It is primarily coded in Hypertext Markup Language (HTML); Cascading Style Sheets (CSS)
are used to control appearance beyond basic HTML. Images are commonly used to effect the desired
appearance and as part of the main content. Audio or video might also be considered "static" content if it
plays automatically or is generally non-interactive. This type of website usually displays the same
information to all visitors. Similar to handing out a printed brochure to customers or clients, a static
website will generally provide consistent, standard information for an extended period of time. Although
the website owner may make updates periodically, it is a manual process to edit the text, photos and other
content and may require basic website design skills and software. Simple forms or marketing examples of
websites, such as classic website, a five-page website or a brochure website are often static websites,
because they present pre-defined, static information to the user. This may include information about a
company and its products and services through text, photos, animations, audio/video, and navigation
menus.

Static websites can be edited using four broad categories of software:

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 Text editors, such as Notepad or TextEdit, where content and HTML markup are manipulated
directly within the editor program
 WYSIWYG offline editors, such as Microsoft FrontPage and Adobe Dreamweaver (previously
Macromedia Dreamweaver), with which the site is edited using a GUI and the final HTML
markup is generated automatically by the editor software
 WYSIWYG online editors which create media rich online presentation like web pages, widgets,
intro, blogs, and other documents.
 Template-based editors such as iWeb allow users to create and upload web pages to a web server
without detailed HTML knowledge, as they pick a suitable template from a palette and add
pictures and text to it in a desktop publishing fashion without direct manipulation of HTML code.

Static websites may still use server side includes (SSI) as an editing convenience, such as sharing a
common menu bar across many pages. As the site's behaviour to the reader is still static, this is not
considered a dynamic site.

Dynamic website

A dynamic website is one that changes or customizes itself frequently and automatically. Server-side
dynamic pages are generated "on the fly" by computer code that produces the HTML (CSS are
responsible for appearance and thus, are static files). There are a wide range of software systems, such as
CGI, Java Servlets and Java Server Pages (JSP), Active Server Pages and ColdFusion (CFML) that are
available to generate dynamic web systems and dynamic sites. Various web application frameworks and
web template systems are available for general-use programming languages like Perl, PHP, Python and
Ruby to make it faster and easier to create complex dynamic websites.

A site can display the current state of a dialogue between users, monitor a changing situation, or provide
information in some way personalized to the requirements of the individual user. For example, when the
front page of a news site is requested, the code running on the web server might combine stored HTML
fragments with news stories retrieved from a database or another website via RSS to produce a page that
includes the latest information. Dynamic sites can be interactive by using HTML forms, storing and
reading back browser cookies, or by creating a series of pages that reflect the previous history of clicks.
Another example of dynamic content is when a retail website with a database of media products allows a
user to input a search request, e.g. for the keyword Beatles. In response, the content of the web page will
spontaneously change the way it looked before, and will then display a list of Beatles products like CDs,
DVDs and books. Dynamic HTML uses JavaScript code to instruct the web browser how to interactively
modify the page contents. One way to simulate a certain type of dynamic website while avoiding the
performance loss of initiating the dynamic engine on a per-user or per-connection basis, is to periodically
automatically regenerate a large series of static pages.

web server

A web server is a computer system that processes requests via HTTP, the basic network protocol used to
distribute information on the World Wide Web. The term can refer to the entire system, or specifically to
the software that accepts and supervises the HTTP requests. [1]

OverviewThe primary function of a web server is to store, process and deliver web pages to clients. The
communication between client and server takes place using the Hypertext Transfer Protocol (HTTP).
Pages delivered are most frequently HTML documents, which may include images, style sheets and
scripts in addition to text content.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Multiple web servers may be used for a high traffic website, here Dell servers are installed together being
used for the Wikimedia Foundation

A user agent, commonly a web browser or web crawler, initiates communication by making a request for
a specific resource using HTTP and the server responds with the content of that resource or an error
message if unable to do so. The resource is typically a real file on the server's secondary storage, but this
is not necessarily the case and depends on how the web server is implemented.

While the primary function is to serve content, a full implementation of HTTP also includes ways of
receiving content from clients. This feature is used for submitting web forms, including uploading of
files.

Many generic web servers also support server-side scripting using Active Server Pages (ASP), PHP, or
other scripting languages. This means that the behaviour of the web server can be scripted in separate
files, while the actual server software remains unchanged. Usually, this function is used to generate
HTML documents dynamically ("on-the-fly") as opposed to returning static documents. The former is
primarily used for retrieving or modifying information from databases. The latter is typically much faster
and more easily cached but cannot deliver dynamic content.

Web servers are not only used for serving the World Wide Web. They can also be found embedded in
devices such as printers, routers, webcams and serving only a local network. The web server may then be
used as a part of a system for monitoring or administering the device in question. This usually means that
no additional software has to be installed on the client computer, since only a web browser is required
(which now is included with most operating systems).

Kernel-mode and user-mode web servers

A web server can be either incorporated into the OS kernel, or in user space (like other regular
applications).

Web servers that run in user-mode have to ask the system for permission to use more memory or more
CPU resources. Not only do these requests to the kernel take time, but they are not always satisfied
because the system reserves resources for its own usage and has the responsibility to share hardware
resources with all the other running applications. Executing in user mode can also mean useless buffer
copies which are another handicap for user-mode web servers.

Load limits

A web server (program) has defined load limits, because it can handle only a limited number of
concurrent client connections (usually between 2 and 80,000, by default between 500 and 1,000) per IP
address (and TCP port) and it can serve only a certain maximum number of requests per second (RPS,
also known as queries per second or QPS) depending on:
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 its own settings,


 the HTTP request type,
 whether the content is static or dynamic,
 whether the content is cached, and
 the hardware and software limitations of the OS of the computer on which the web server runs.

When a web server is near to or over its limit, it becomes unresponsive.

2.5 UNDERSTANDING INTERNET

Understanding Internet Basics


You can program for the Web, using your skills as a Visual Basic programmer, no matter what your
level of experience with Internet technology. If you are new to the Internet or unfamiliar with its
technology, Visual Basic allows you to quickly and easily produce functional applications. If you are
more experienced with Internet technology, you can work at a more advanced level.
From one perspective, Internet technology simply provides another area for your development efforts.
When you deploy Internet applications on the Web, you may go about it differently — incorporating
HTML pages with your Visual Basic code, providing security features, and so on — but you're still
calling methods, setting properties, and handling events. In this way, all of your knowledge as a Visual
Basic developer can be carried into the Internet arena.

From another perspective, applying Internet technology enables you to extend your development skills
in exciting new ways. For example, writing Visual Basic code that manipulates HTML pages allows
you to decrease deployment costs, reduce client maintenance problems, and reach the broad audience of
the Internet.

Internet Clients and Servers


A common way to think about Internet development is in terms of client/server relationships. In this
case, the client is the browser, and the server is the Web server. Most interactions on the Internet or an
intranet can be thought of in terms of requests and responses. The browser makes a request to the Web
server (usually to display a page the user wants to see) and the Web server returns a response (usually
an HTML page, an element, or an image) to the browser.

 A network is defined as an interconnection of computing devices in order to transfer data between


them

 An internet is defined as an interconnection of networks in order to transfer data between the


networks across the globe

 It is a network connecting millions of computers across the globe.


 Internet = Network of networks
 It is a network of computers, open for all

 Unlimited number of users can participate in internet to retrieve data from unlimited number of
information sources

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 People and organizations connect into internet so that they can access its massive store of shared
information

Essentials for an internet connection:-

Applicati
Computer DSL on
software:
email
Browser, ,
etc

Connection Modem ISP

Network
Cable software: Wired/Wireless
TCP/IP line

Evolution of internet:-

 It was originated in 1969 at ARPANET (Advanced research project Agency) of DoD (Department
of Defense), USA

 It‘s prime purpose was to connect among various bodies of US government


 Initially there were only four nodes (Hosts)
 In 1972, ARPANET was spread across the globe with 23 nodes at different parts of the world

 Then all the other organizations in respective countries joined to this network in order to send and
receive data among other countries

 Thereby internet has got populated with number of networks, thus became a tech giant

 Around 1990s, Tim Berners Lee and O-Reilly had developed WWW and other internet
communication protocols

Terminologies used in internet:-


 Host: A computer that is connected to internet

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 Communication service: Protocols to send and receive data over the internet such as FTP,
HTTP, WWW, VoIP, etc.

 ISP: Internet Service providers are decentralized and those who provide internet connectivity to
its subscribers. Ex: BSNL

 Online: When a computer is connected to internet


 Hyperlink: Allows an user to move from one page to another
 Protocols: Set of rules for communication

 TCP/IP: to establish a virtual connection between source and destination. It guarantees data
delivery, reliable, ordered packet delivery, etc

 Client/Server Model: TCP/IP uses this model where a client refers to any computing device that
generates HTTP request and server refers to any computer that responds to the corresponding request

 IP address: It is the unique address assigned to a computing device that gets connected to the
internet. It is also called as logical address or software address. It is mutable.

 DNS: Domain Name Servers are used to translate the website names given by the users into
machine understandable IP addresses from a database.

 URL: Uniform Resource Locator (URL) is defined as an unique address for the file that has to be
accessed over the internet. If we want to access a website, we enter its URL in the address bar of the
web browser.

Syntax: protocol: //www.exampleDomain.com/path/filename Ex: https://www.vit.ac.in / home.aspx

 WWW: It is a standard in which all the websites are server on the internet via HTTP. It was
invented by Tim Berner‘s Lee at Switzerland on 1990s. Later HTTP and HTML were invented, In
1994, WWW was invented at MIT (Massachusetts Institute of Technology) + DARPA
Working:-
 From a web browser, user sends HTTP request to a server
 ISP finds the corresponding site from DNS and forwards it.
 The request reaches the server after a long travel
 Server responds to that request and the reply goes back
 Any file transmitted in internet will not be sent as a whole
 All the information will be chopped into chunks (data packets)
 Packets have header and footer info, useful for ordering

2.6 DIFFERENCE BETWEEN WEBSITES AND WEB SERVER

WEBSITES WEB SERVER

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

A website is a set of linked documents The web server on the other side is a computer
associated with a particular person, program, which delivers content, such as
organization or topic that is held on a computer websites or web pages, for example, over the
system and can be accessed as part of the world wide web from a web server to your
world wide web. computer.
(Not to be confused with: Web page, a
document on the world wide web written in A website is a creation from
HTML and displayed in a web browser.) webdesigners/webdevelopers, it's based on a
theme, an idea. You can navigate in it by
visiting one or a fews pages through
hyperlinks, reading and watching texts, photos,
videos players

The websites are composed by files, medias, ... The webdesigner is the person who creates
these one are stocked on hardware connected websites.
to the internet network, accessible by people in The webmaster is the person who maintains it
the world. This hardwares and the websites but it often is the same person
contained in it (the real word is "hosted") are
managed by a computer, a server we call the
"webserver". It can hosts a few websites

A web page is a simple document displayable A web server is a computer hosting one or
by a browser. Such document is written in the more websites. "Hosting" means that all the
HTML language (which we look into in more web pages and their supporting files are
detail in other articles). available on that computer. The web server
will send any web page from the website it is
hosting to any user's browser, per user request.

2.7 INTERNET TECHNOLOGIES OVERVIEW

Internet

 Internet is a world-wide global system of interconnected computer networks.


 Internet uses the standard Internet Protocol (TCP/IP).
 Every computer in internet is identified by a unique IP address.
 IP Address is a unique set of numbers (such as 110.22.33.114) which identifies a computer
location.
 A special computer DNS (Domain Name Server) is used to give name to the IP Address so that
user can locate a computer by a name.
 For example, a DNS server will resolve a name http://www.tutorialspoint.com to a particular IP
address to uniquely identify the computer on which this website is hosted.
 Internet is accessible to every user all over the world.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Internet Evoloution

The concept of Internet was originated in 1969 and has undergone several technological & Infrastructural
changes as discussed below:

 The origin of Internet devised from the concept of Advanced Research Project Agency
Network (ARPANET).
 ARPANET was developed by United States Department of Defense.
 Basic purpose of ARPANET was to provide communication among the various bodies of
government.
 Initially, there were only four nodes, formally called Hosts.
 In 1972, the ARPANET spread over the globe with 23 nodes located at different countries and
thus became known as Internet.
 By the time, with invention of new technologies such as TCP/IP protocols, DNS, WWW,
browsers, scripting languages etc.,Internet provided a medium to publish and access information
over the web.

Internet Advantages

Internet covers almost every aspect of life, one can think of. Here, we will discuss some of the
advantages of Internet:

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Internet Disadvantages

Extranet

Extranet refers to network within an organization, using internet to connect to the outsiders in controlled
manner. It helps to connect businesses with their customers and suppliers and therefore allows working in
a collaborative manner.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Extranet Issues

Apart for advantages there are also some issues associated with extranet. These issues are discussed
below:

Hosting

Where the extranet pages will be held i.e. who will host the extranet pages. In this context there are two
choices:

 Host it on your own server.


 Host it with an Internet Service Provider (ISP) in the same way as web pages.

But hosting extranet pages on your own server requires high bandwidth internet connection which is very
costly.

Extranet Benefits

Extranet proves to be a successful model for all kind of businesses whether small or big. Here are some
of the advantages of extranet for employees, suppliers, business partners, and customers:

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Security

Additional firewall security is required if you host extranet pages on your own server which result in a
complex security mechanism and increase work load.

Accessing Issues

Information can not be accessed without internet connection. However, information can be accessed in
Intranet without internet connection.

Decreased Interaction

It decreases the face to face interaction in the business which results in lack of communication among
customers, business partners and suppliers.

Extranet vs. Intranet

The following table shows differences between Extranet and Intranet:

Extranet Intranet

Internal network that can not be


Internal network that can be accessed externally.
accessed externally.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Extranet is extension of company's Intranet. Only limited users of a company.

For limited external communication between customers, Only for communication within a
suppliers and business partners. company.

2.7.1 Basic Internet Protocol:

Transmission Control Protocol (TCP)

TCP is a connection oriented protocol and offers end-to-end packet delivery. It acts as back bone for
connection.It exhibits the following key features:

 Transmission Control Protocol (TCP) corresponds to the Transport Layer of OSI Model.
 TCP is a reliable and connection oriented protocol.
 TCP offers:
o Stream Data Transfer.
o Reliability.
o Efficient Flow Control
o Full-duplex operation.
o Multiplexing.
 TCP offers connection oriented end-to-end packet delivery.
 TCP ensures reliability by sequencing bytes with a forwarding acknowledgement number that
indicates to the destination the next byte the source expect to receive.
 It retransmits the bytes not acknowledged with in specified time period.

TCP Services

TCP offers following services to the processes at the application layer:

 Stream Delivery Service


 Sending and Receiving Buffers
 Bytes and Segments
 Full Duplex Service
 Connection Oriented Service
 Reliable Service

Stream Deliver Service

TCP protocol is stream oriented because it allows the sending process to send data as stream of bytes and
the receiving process to obtain data as stream of bytes.

Sending and Receiving Buffers

It may not be possible for sending and receiving process to produce and obtain data at same speed,
therefore, TCP needs buffers for storage at sending and receiving ends.

Bytes and Segments

The Transmission Control Protocol (TCP), at transport layer groups the bytes into a packet. This packet
is called segment. Before transmission of these packets, these segments are encapsulated into an IP
datagram.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Full Duplex Service

Transmitting the data in duplex mode means flow of data in both the directions at the same time.

Connection Oriented Service

TCP offers connection oriented service in the following manner:

1. TCP of process-1 informs TCP of process – 2 and gets its approval.


2. TCP of process – 1 and TCP of process – 2 and exchange data in both the two directions.
3. After completing the data exchange, when buffers on both sides are empty, the two TCP‘s destroy
their buffers.

Reliable Service

For sake of reliability, TCP uses acknowledgement mechanism.

Internet Protocol (IP)

Internet Protocol is connectionless and unreliable protocol. It ensures no guarantee of successfully


transmission of data.

In order to make it reliable, it must be paired with reliable protocol such as TCP at the transport layer.

Internet protocol transmits the data in form of a datagram as shown in the following diagram:

Points to remember:

 The length of datagram is variable.


 The Datagram is divided into two parts: header and data.
 The length of header is 20 to 60 bytes.
 The header contains information for routing and delivery of the packet.

User Datagram Protocol (UDP)

Like IP, UDP is connectionless and unreliable protocol. It doesn‘t require making a connection with the
host to exchange data. Since UDP is unreliable protocol, there is no mechanism for ensuring that data
sent is received.

UDP transmits the data in form of a datagram. The UDP datagram consists of five parts as shown in the
following diagram:

Points to remember:

 UDP is used by the application that typically transmit small amount of data at one time.
 UDP provides protocol port used i.e. UDP message contains both source and destination port
number, that makes it possible for UDP software at the destination to deliver the message to
correct application program.

File Transfer Protocol (FTP)

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

FTP is used to copy files from one host to another. FTP offers the mechanism for the same in following
manner:

 FTP creates two processes such as Control Process and Data Transfer Process at both ends i.e. at
client as well as at server.
 FTP establishes two different connections: one is for data transfer and other is for control
information.
 Control connection is made between control processes while Data Connection is made
between <="" b="">
 FTP uses port 21 for the control connection and Port 20 for the data connection.

Trivial File Transfer Protocol (TFTP)

Trivial File Transfer Protocol is also used to transfer the files but it transfers the files without
authentication. Unlike FTP, TFTP does not separate control and data information. Since there is no
authentication exists, TFTP lacks in security features therefore it is not recommended to use TFTP.

Key points

 TFTP makes use of UDP for data transport. Each TFTP message is carried in separate UDP
datagram.
 The first two bytes of a TFTP message specify the type of message.
 The TFTP session is initiated when a TFTP client sends a request to upload or download a file.
 The request is sent from an ephemeral UDP port to the UDP port 69 of an TFTP server.

Difference between FTP and TFTP


S.N. Parameter FTP TFTP

1 Operation Transferring Files Transferring Files

2 Authentication Yes No

3 Protocol TCP UDP

4 Ports 21 – Control, 20 – Data Port 3214, 69, 4012

5 Control and Data Separated Separated

6 Data Transfer Reliable Unreliable

Telnet

Telnet is a protocol used to log in to remote computer on the internet. There are a number of Telnet
clients having user friendly user interface. The following diagram shows a person is logged in to
computer A, and from there, he remote logged into computer B.

Hyper Text Transfer Protocol (HTTP)


M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

HTTP is a communication protocol. It defines mechanism for communication between browser and the
web server. It is also called request and response protocol because the communication between browser
and server takes place in request and response pairs.

HTTP Request

HTTP request comprises of lines which contains:

 Request line
 Header Fields
 Message body

Key Points

 The first line i.e. the Request line specifies the request method i.e. Get or Post.
 The second line specifies the header which indicates the domain name of the server from where
index.htm is retrieved.

HTTP Response

Like HTTP request, HTTP response also has certain structure. HTTP response contains:

 Status line
 Headers
 Message body

2.8 UNDERSTANDING THE DIFFERENCE BETWEEN INTERNET AND INTRANET

INTERNET:
1. Internet is wide network of computers and is open for all.
2. Internet itself contains a large number of intranets.
3. The number of users who use internet is Unlimited.
4. The Visitors traffic is unlimited.
5. Internet contains different source of information and is available for all.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

INTRANET:
1. Intranet is also a network of computers designed for a specific group of users.
2. Intranet can be accessed from Internet but with restrictions.
3. The number of users is limited.
4. The traffic allowed is also limited.
5. Intranet contains only specific group information.

2.9 HTML AND CSS

Hypertext Markup Language (HTML) is the standard markup language for creating web pages and
web applications. With Cascading Style Sheets (CSS) and JavaScript it forms a triad of cornerstone
technologies for the World Wide Web.[1] Web browsers receive HTML documents from a webserver or
from local storage and render them into multimedia web pages. HTML describes the structure of a web
page semantically and originally included cues for the appearance of the document.

HTML elements are the building blocks of HTML pages. With HTML constructs, images and other
objects, such as interactive forms, may be embedded into the rendered page. It provides a means to create
structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links,
quotes and other items. HTML elements are delineated by tags, written using angle brackets. Tags such
as <img /> and <input /> introduce content into the page directly. Others such as <p>...</p>
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

surround and provide information about document text and may include other tags as sub-elements.
Browsers do not display the HTML tags, but use them to interpret the content of the page.

HTML can embed programs written in a scripting language such as JavaScript which affect the behavior
and content of web pages. Inclusion of CSS defines the look and layout of content. The World Wide Web
Consortium (W3C), maintainer of both the HTML and the CSS standards, has encouraged the use of CSS
over explicit presentational HTML since 1997. [2]

Markup

HTML markup consists of several key components, including those called tags (and their attributes),
character-based data types, character references and entity references. HTML tags most commonly come
in pairs like <h1> and </h1>, although some represent empty elements and so are unpaired, for example
<img>. The first tag in such a pair is the start tag, and the second is the end tag (they are also called
opening tags and closing tags).

Another important component is the HTML document type declaration, which triggers standards mode
rendering.

The following is an example of the classic Hello world program, a common test employed for comparing
programming languages, scripting languages and markup languages. This example is made using 9 lines
of code:

<!DOCTYPE html>
<html>
<head>
<title>This is a title</title>
</head>
<body>
<p>Hello world!</p>
</body>
</html>

(The text between <html> and </html> describes the web page, and the text between <body> and
</body> is the visible page content. The markup text "<title>This is a title</title>" defines the browser
page title.)

The Document Type Declaration <!DOCTYPE html> is for HTML5. If a declaration is not included,
various browsers will revert to "quirks mode" for rendering.[60]

Elements
Main article: HTML element

HTML documents imply a structure of nested HTML elements. These are indicated in the document by
HTML tags, enclosed in angle brackets thus: <p>[61]

In the simple, general case, the extent of an element is indicated by a pair of tags: a "start tag" <p> and
"end tag" </p>. The text content of the element, if any, is placed between these tags.

Tags may also enclose further tag markup between the start and end, including a mixture of tags and text.
This indicates further (nested) elements, as children of the parent element.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

The start tag may also include attributes within the tag. These indicate other information, such as
identifiers for sections within the document, identifiers used to bind style information to the presentation
of the document, and for some tags such as the <img> used to embed images, the reference to the image
resource.

Some elements, such as the line break <br>, do not permit any embedded content, either text or further
tags. These require only a single empty tag (akin to a start tag) and do not use an end tag.

Many tags, particularly the closing end tag for the very commonly used paragraph element <p>, are
optional. An HTML browser or other agent can infer the closure for the end of an element from the
context and the structural rules defined by the HTML standard. These rules are complex and not widely
understood by most HTML coders.

The general form of an HTML element is therefore: <tag attribute1="value1"


attribute2="value2">''content''</tag>. Some HTML elements are defined as empty elements and
take the form <tag attribute1="value1" attribute2="value2">. Empty elements may enclose no content,
for instance, the <br> tag or the inline <img> tag. The name of an HTML element is the name used in
the tags. Note that the end tag's name is preceded by a slash character, "/", and that in empty elements the
end tag is neither required nor allowed. If attributes are not mentioned, default values are used in each
case.

Element examples

Header of the HTML document: <head>...</head>. The title is included in the head, for example:

<head>
<title>The Title</title>
</head>

Headings: HTML headings are defined with the <h1> to <h6> tags:

<h1>Heading level 1</h1>


<h2>Heading level 2</h2>
<h3>Heading level 3</h3>
<h4>Heading level 4</h4>
<h5>Heading level 5</h5>
<h6>Heading level 6</h6>

Paragraphs:

<p>Paragraph 1</p> <p>Paragraph 2</p>

Line breaks:<br>. The difference between <br> and <p> is that "br" breaks a line without altering the
semantic structure of the page, whereas "p" sections the page into paragraphs. Note also that "br" is an
empty element in that, although it may have attributes, it can take no content and it may not have an end
tag.

<p>This <br> is a paragraph <br> with <br> line breaks</p>

This is a link in HTML. To create a link the <a> tag is used. The href= attribute holds the URL address
of the link.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

<a href="https://www.wikipedia.org/">A link to Wikipedia!</a>

Comments:

<!-- This is a comment -->

Comments can help in the understanding of the markup and do not display in the webpage.

CSS:

Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a
document written in a markup language.[1] Although most often used to set the visual style of web pages
and user interfaces written in HTML and XHTML, the language can be applied to any XML document,
including plain XML, SVG and XUL, and is applicable to rendering in speech, or on other media. Along
with HTML and JavaScript, CSS is a cornerstone technology used by most websites to create visually
engaging webpages, user interfaces for web applications, and user interfaces for many mobile
applications.[2]

CSS is designed primarily to enable the separation of presentation and content, including aspects such as
the layout, colors, and fonts.[3] This separation can improve content accessibility, provide more flexibility
and control in the specification of presentation characteristics, enable multiple HTML pages to share
formatting by specifying the relevant CSS in a separate .css file, and reduce complexity and repetition in
the structural content.

Separation of formatting and content makes it possible to present the same markup page in different
styles for different rendering methods, such as on-screen, in print, by voice (via speech-based browser or
screen reader), and on Braille-based tactile devices. It can also display the web page differently
depending on the screen size or viewing device. Readers can also specify a different style sheet, such as a
CSS file stored on their own computer, to override the one the author specified.

Changes to the graphic design of a document (or hundreds of documents) can be applied quickly and
easily, by editing a few lines in the CSS file they use, rather than by changing markup in the documents.

The CSS specification describes a priority scheme to determine which style rules apply if more than one
rule matches against a particular element. In this so-called cascade, priorities (or weights) are calculated
and assigned to rules, so that the results are predictable.

The CSS specifications are maintained by the World Wide Web Consortium (W3C). Internet media type
(MIME type) text/css is registered for use with CSS by RFC 2318 (March 1998). The W3C operates
a free CSS validation service for CSS documents

Syntax

CSS has a simple syntax and uses a number of English keywords to specify the names of various style
properties.

A style sheet consists of a list of rules. Each rule or rule-set consists of one or more selectors, and a
declaration block.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Selector

In CSS, selectors declare which part of the markup a style applies to by matching tags and attributes in
the markup itself.

Selectors may apply to:

 all elements of a specific type, e.g. the second-level headers h2


 elements specified by attribute, in particular:
o id: an identifier unique within the document
o class: an identifier that can annotate multiple elements in a document
 elements depending on how they are placed relative to others in the document tree.

Classes and IDs are case-sensitive, start with letters, and can include alphanumeric characters and
underscores. A class may apply to any number of instances of any elements. An ID may only be applied
to a single element.

Pseudo-classes are used in CSS selectors to permit formatting based on information that is not contained
in the document tree. One example of a widely used pseudo-class is :hover, which identifies content only
when the user "points to" the visible element, usually by holding the mouse cursor over it. It is appended
to a selector as in a:hover or #elementid:hover. A pseudo-class classifies document elements, such as
:link or :visited, whereas a pseudo-element makes a selection that may consist of partial elements, such as
::first-line or ::first-letter.[5]

Selectors may be combined in many ways to achieve great specificity and flexibility. [6] Multiple selectors
may be joined in a spaced list to specify elements by location, element type, id, class, or any combination
thereof. The order of the selectors is important. For example, div .myClass {color: red;} applies to all
elements of class myClass that are inside div elements, whereas .myClass div {color: red;} applies to
all div elements that are in elements of class myClass.

The following table provides a summary of selector syntax indicating usage and the version of CSS that
introduced it

Use

Before CSS, nearly all presentational attributes of HTML documents were contained within the HTML
markup. All font colors, background styles, element alignments, borders and sizes had to be explicitly
described, often repeatedly, within the HTML. CSS lets authors move much of that information to
another file, the style sheet, resulting in considerably simpler HTML.

For example, headings (h1 elements), sub-headings (h2), sub-sub-headings (h3), etc., are defined
structurally using HTML. In print and on the screen, choice of font, size, color and emphasis for these
elements is presentational.

Before CSS, document authors who wanted to assign such typographic characteristics to, say, all h2
headings had to repeat HTML presentational markup for each occurrence of that heading type. This made
documents more complex, larger, and more error-prone and difficult to maintain. CSS allows the
separation of presentation from structure. CSS can define color, font, text alignment, size, borders,
spacing, layout and many other typographic characteristics, and can do so independently for on-screen
and printed views. CSS also defines non-visual styles, such as reading speed and emphasis for aural text
readers. The W3C has now deprecated the use of all presentational HTML markup. [11]

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

For example, under pre-CSS HTML, a heading element defined with red text would be written as:

<h1><font color="red"> Chapter 1. </font></h1>

Using CSS, the same element can be coded using style properties instead of HTML presentational
attributes:

<h1 style="color: red;"> Chapter 1. </h1>

An "external" CSS file, as described below, can be associated with an HTML document using the
following syntax:

<link href="path/to/file.css" rel="stylesheet" type="text/css">

An internal CSS code can be typed in the head section of the code. The coding is started with the style
tag. For example,

<style>
h1 {color: red;}
</style>

Example:

Consider this HTML fragment:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
#xyz { color: red; }
</style>
</head>
<body>
<p id="xyz" style="color: blue;"> To demonstrate specificity </p>
</body>
</html>
2.10 HTML 5.0

HTML5 is a markup language used for structuring and presenting content on the World Wide Web. It is
the fifth and current version of the HTML standard.

It was published in October 2014 by the World Wide Web Consortium (W3C)[2][4] to improve the
language with support for the latest multimedia, while keeping it both easily readable by humans and
consistently understood by computers and devices such as web browsers, parsers, etc. HTML5 is
intended to subsume not only HTML 4, but also XHTML 1 and DOM Level 2 HTML.

HTML5 includes detailed processing models to encourage more interoperable implementations; it


extends, improves and rationalizes the markup available for documents, and introduces markup and
application programming interfaces (APIs) for complex web applications.[6] For the same reasons,

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

HTML5 is also a candidate for cross-platform mobile applications, because it includes features designed
with low-powered devices in mind.

Many new syntactic features are included. To natively include and handle multimedia and graphical
content, the new <video>, <audio> and <canvas> elements were added, and support for scalable vector
graphics (SVG) content and MathML for mathematical formulas. To enrich the semantic content of
documents, new page structure elements such as <main>, <section>, <article>, <header>,
<footer>, <aside>, <nav> and <figure>, are added. New attributes are introduced, some
elements and attributes have been removed, and others such as <a>, <cite> and <menu> have been
changed, redefined or standardized.

The APIs and Document Object Model (DOM) are now fundamental parts of the HTML5 specification
and HTML5 also better defines the processing for any invalid documents.

Features and APIs

The W3C proposed a greater reliance on modularity as a key part of the plan to make faster progress,
meaning identifying specific features, either proposed or already existing in the spec, and advancing them
as separate specifications. Some technologies that were originally defined in HTML5 itself are now
defined in separate specifications:

 HTML Working Group – HTML Canvas 2D Context;


 Web Apps Working Group – Web Messaging, Web Workers, Web Storage, WebSocket, Server-
sent events, Web Components[33] (this was not part of HTML5 though); Note that the Web
Applications Working Group was closed in October 2015 and its deliverables transferred to the
Web Platform Working Group (WPWG).
 IETF HyBi Working Group – WebSocket Protocol;
 WebRTC Working Group – WebRTC;
 Web Media Text Tracks Community Group – WebVTT.

After the standardization of the HTML5 specification in October 2014, [34] the core vocabulary and
features are being extended in four ways.[35] Likewise, some features that were removed from the original
HTML5 specification have been standardized separately as modules, such as Microdata and Canvas.
Technical specifications introduced as HTML5 extensions such as Polyglot Markup have also been
standardized as modules. Some W3C specifications that were originally separate specifications have been
adapted as HTML5 extensions or features, such as SVG. Some features that might have slowed down the
standardization of HTML5 will be standardized as upcoming specifications, instead. HTML 5.1 is
expected to be finalized in 2016, and it is currently on the standardization track at the W3C.

Features

Markup

HTML5 introduces elements and attributes that reflect typical usage on modern websites. Some of them
are semantic replacements for common uses of generic block (<div>) and inline (<span>) elements,
for example <nav> (website navigation block), <footer> (usually referring to bottom of web page or
to last lines of HTML code), or <audio> and <video> instead of <object>.[36][37][38] Some
deprecated elements from HTML 4.01 have been dropped, including purely presentational elements such
as <font> and <center>, whose effects have long been superseded by the more capable Cascading
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Style Sheets.[39] There is also a renewed emphasis on the importance of DOM scripting (e.g., JavaScript)
in Web behavior.

The HTML5 syntax is no longer based on SGML[40][41] despite the similarity of its markup. It has,
however, been designed to be backward compatible with common parsing of older versions of HTML. It
comes with a new introductory line that looks like an SGML document type declaration, <!DOCTYPE
html>, which triggers the standards-compliant rendering mode.[42] Since 5 January 2009, HTML5 also
includes Web Forms 2.0, a previously separate WHATWG specification.

In addition to specifying markup, HTML5 specifies scripting application programming interfaces (APIs)
that can be used with JavaScript.[46] Existing document object model (DOM) interfaces are extended and
de facto features documented. There are also new APIs, such as:

 Canvas;[47]
 Timed Media Playback;[48]
 Offline;[49]
 Editable content;[50]
 Drag-and-drop;[51]
 History;[52]
 MIME type and protocol handler registration;[53][54]
 Microdata;[55]
 Web Messaging;[56]
 Web Storage – a key-value pair storage framework that provides behaviour similar to cookies but
with larger storage capacity and improved API. [57]

Not all of the above technologies are included in the W3C HTML5 specification, though they are in the
WHATWG HTML specification.[58] Some related technologies, which are not part of either the W3C
HTML5 or the WHATWG HTML specification, are as follows. The W3C publishes specifications for
these separately:

New APIs

 Geolocation;
 Web SQL Database – a local SQL Database (no longer maintained);[59]
 IndexedDB – an indexed hierarchical key-value store (formerly WebSimpleDB);[60]
 File[61] – an API intended to handle file uploads and file manipulation;[62]
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 Directories and System – an API intended to satisfy client-side-storage use cases not well served
by databases;[63]
 File Writer – an API for writing to files from web applications;[64]
 Web Audio[65] – a high-level JavaScript API for processing and synthesizing audio in web
applications;
 ClassList.[66]
 Web Cryptography[67]
 WebRTC[68]

HTML5 cannot provide animation within web pages. Additional JavaScript or CSS3 functionality is
necessary for animating HTML elements. Animation is also possible using JavaScript and HTML 4 [69][not
in citation given]
, and within SVG elements through SMIL, although browser support of the latter remains
uneven as of 2011.

XHTML5 (XML-serialized HTML5)

XML documents must be served with an XML Internet media type (often called "MIME type") such as
application/xhtml+xml or application/xml,[70] and must conform to strict, well-formed
syntax of XML. XHTML5 is simply XML-serialized HTML5 data (e.g. not having any unclosed tags),
sent with one of XML media types. HTML that has been written to conform to both the HTML and
XHTML specifications – and which will therefore produce the same DOM tree whether parsed as HTML
or XML – is called polyglot markup.

2.11 XHTML

XHTML stands for EXtensible HyperText Markup Language. It is the next step in the evolution of the
internet. The XHTML 1.0 is the first document type in the XHTML family.

XHTML is almost identical to HTML 4.01 with only few differences. This is a cleaner and stricter
version of HTML 4.01. If you already know HTML, then you need to give little attention to learn this
latest version of HTML.

XHTML was developed by World Wide Web Consortium (W3C) to help web developers make the
transition from HTML to XML. By migrating to XHTML today, web developers can enter the XML
world with all of its benefits, while still remaining confident in the backward and future compatibility of
the content.

Why Use XHTML?

Developers who migrate their content to XHTML 1.0 get the following benefits −

 XHTML documents are XML conforming as they are readily viewed, edited, and validated with
standard XML tools.
 XHTML documents can be written to operate better than they did before in existing browsers as
well as in new browsers.
 XHTML documents can utilize applications such as scripts and applets that rely upon either the
HTML Document Object Model or the XML Document Object Model.
 XHTML gives you a more consistent, well-structured format so that your webpages can be easily
parsed and processed by present and future web browsers.
 You can easily maintain, edit, convert and format your document in the long run.
 Since XHTML is an official standard of the W3C, your website becomes more compatible with
many browsers and it is rendered more accurately.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 XHTML combines strength of HTML and XML. Also, XHTML pages can be rendered by all
XML enabled browsers.
 XHTML defines quality standard for your webpages and if you follow that, then your web pages
are counted as quality web pages. The W3C certifies those pages with their quality stamp.

Web developers and web browser designers are constantly discovering new ways to express their ideas
through new markup languages. In XML, it is relatively easy to introduce new elements or additional
element attributes. The XHTML family is designed to accommodate these extensions through XHTML
modules and techniques for developing new XHTML-conforming modules. These modules permit the
combination of existing and new features at the time of developing content and designing new user
agents.

Basic Understanding

Before we proceed further, let us have a quick view on what are HTML, XML, and SGML.

What is SGML?

This is Standard Generalized Markup Language (SGML) application conforming to International


Standard ISO 8879. HTML is widely regarded as the standard publishing language of the World Wide
Web.

This is a language for describing markup languages, particularly those used in electronic document
exchange, document management, and document publishing. HTML is an example of a language defined
in SGML.

What is XML?

XML stands for EXtensible Markup Language. XML is a markup language much like HTML and it was
designed to describe data. XML tags are not predefined. You must define your own tags according to
your needs.

What Is XHTML?

 XHTML stands for EXtensible HyperText Markup Language


 XHTML is almost identical to HTML
 XHTML is stricter than HTML
 XHTML is HTML defined as an XML application
 XHTML is supported by all major browsers

Why XHTML?

Many pages on the internet contain "bad" HTML.

This HTML code works fine in most browsers (even if it does not follow the HTML rules):

<html>
<head>
<title>This is bad HTML</title>

<body>

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

<h1>Bad HTML
<p>This is a paragraph
</body>

Today's market consists of different browser technologies. Some browsers run on computers, and some
browsers run on mobile phones or other small devices. Smaller devices often lack the resources or power
to interpret "bad" markup.

XML is a markup language where documents must be marked up correctly (be "well-formed").

If you want to study XML, please read our XML tutorial.

By combining the strengths of HTML and XML, XHTML was developed.

XHTML is HTML redesigned as XML.

Most Important Differences from HTML:

Document Structure

 XHTML DOCTYPE is mandatory


 The xmlns attribute in <html> is mandatory
 <html>, <head>, <title>, and <body> are mandatory

XHTML Elements

 XHTML elements must be properly nested


 XHTML elements must always be closed
 XHTML elements must be in lowercase
 XHTML documents must have one root element

XHTML Attributes

 Attribute names must be in lower case


 Attribute values must be quoted
 Attribute minimization is forbidden

2.12 CSS 3
 CSS3 is the latest standard for CSS.
 CSS3 is completely backwards-compatible with earlier versions of CSS.
 This section teaches you about the new features in CSS3!

CSS3 Modules

CSS3 has been split into "modules". It contains the "old CSS specification" (which has been split into
smaller pieces). In addition, new modules are added.

Some of the most important CSS3 modules are:

 Selectors
 Box Model
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 Backgrounds and Borders


 Image Values and Replaced Content
 Text Effects
 2D/3D Transformations
 Animations
 Multiple Column Layout
 User Interface

Most of the new CSS3 properties are implemented in modern browsers.

Cascading Style Sheets (CSS) is a style sheet language used for describing the look and formatting of a
document written in a markup language.CSS3 is a latest standard of css earlier versions(CSS2).The main
difference between css2 and css3 is follows

 Media Queries
 Namespaces
 Selectors Level 3
 Color

CSS3 modules

CSS3 is collaboration of CSS2 specifications and new specifications, we can called this collaboration is
module.Some of the modules are shown below

 Selectors
 Box Model
 Backgrounds
 Image Values and Replaced Content
 Text Effects
 2D Transformations
 3D Transformations
 Animations
 Multiple Column Layout
 User Interface

CSS3 is the latest evolution of the Cascading Style Sheets language and aims at extending CSS2.1. It
brings a lot of long-awaited novelties, like rounded corners, shadows, gradients, transitions or
animations, as well as new layouts like multi-columns, flexible box or grid layouts. Experimental parts
are vendor-prefixed and should either be avoided in production environments, or used with extreme
caution as both their syntax and semantics can change in the future.

Modules and the standardization process

CSS Level 2 needed 9 years, from August 2002 to June 2011 to reach the Recommendation status. This
was due to the fact that a few secondary features held back the whole specification. In order to accelerate
the standardization of non-problematic features, the CSS Working Group of the W3C, in a decision
referred as the Beijing doctrine, divided CSS in smaller components called modules . Each of these
modules is now an independent part of the language and moves towards standardization at its own pace.
While some modules are already W3C Recommendations, other still are early Working Drafts. New
modules are also added when new needs are identified.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Formally
, there is no CSS3 standard per se . Each module being standardized independently, the standard CSS
consists of CSS2.1 amended and extended by the completed modules, not necessary all with the same
level number. At each point of time, a snapshot of the CSS standard can be defined, listing CSS2.1 and
the mature modules.

The W3 consortium periodically publishes such snapshots, like in 2007, 2010, 2015 and 2017.

Though today no module with a level greater than 3 is standardized, this will change in the future. Some
modules, like Selectors 4 or CSS Borders and Backgrounds Level 4 already have an Editor's Draft,
though they haven't yet reached the First Published Working Draft status.

CSS modules status

Stable modules

A few CSS modules are already fairly stable and have reached one of the three recommendation level of
the CSSWG: Candidate Recommendation, Proposed Recommendation or Recommendation. These can
be used without prefix and are pretty stable, though a few features can still be dropped at the Candidate
Recommendation stage.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

These modules extend and amend the CSS2.1 specification which build the core of the specification.
Together with it, they are the current snapshot of the CSS specification.

2.12.1 CSS 3 Borders:


Border Style
The border-style property specifies what kind of border to display.
The following values are allowed:
 dotted - Defines a dotted border
 dashed - Defines a dashed border
 solid - Defines a solid border
 double - Defines a double border
 groove - Defines a 3D grooved border. The effect depends on the border-color value
 ridge - Defines a 3D ridged border. The effect depends on the border-color value
 inset - Defines a 3D inset border. The effect depends on the border-color value
 outset - Defines a 3D outset border. The effect depends on the border-color value
 none - Defines no border
 hidden - Defines a hidden border

The border-style property can have from one to four values (for the top border, right border, bottom
border, and the left border).

Example
p.dotted {border-style: dotted;}
p.dashed {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.mix {border-style: dotted dashed solid double;}

Result:

A dotted border.

A dashed border.

A solid border.

A double border.

A groove border. The effect depends on the border-color value.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

A ridge border. The effect depends on the border-color value.

An inset border. The effect depends on the border-color value.

An outset border. The effect depends on the border-color value.

No border.

A hidden border.

A mixed border.

2.12.2 CSS 3 Text Effects:

 The CSS3 text-overflow property specifies how overflowed content that is not displayed
should be signaled to the user.
 It can be clipped:
 This is some long text that will not fit in the box
 or it can be rendered as an ellipsis (...):
 This is some long text that will not fit in the box.
The CSS code is as follows:

Example
p.test1 {
white-space: nowrap;
width: 200px;
border: 1px solid #000000;
overflow: hidden;
text-overflow: clip;
}

p.test2 {
white-space: nowrap;
width: 200px;
border: 1px solid #000000;
overflow: hidden;
text-overflow: ellipsis;
}

2.12.3 Gradient Effects:

CSS3 gradients let you display smooth transitions between two or more specified colors.

Earlier, you had to use images for these effects. However, by using CSS3 gradients you can reduce
download time and bandwidth usage. In addition, elements with gradients look better when zoomed,
because the gradient is generated by the browser.

CSS3 defines two types of gradients:


M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 Linear Gradients (goes down/up/left/right/diagonally)


 Radial Gradients (defined by their center)

UNIT III

CLIENT SIDE AND SERVER SIDE PROGRAMMING


3.1 JAVA SCRIPT:

JavaScript is a programming language that can be included on web pages to make them more interactive.
You can use it to check or modify the contents of forms, change images, open new windows and write
dynamic page content. You can even use it with CSS to make DHTML (Dynamic HyperText Markup
Language). This allows you to make parts of your web pages appear or disappear or move around on the
page. JavaScripts only execute on the page(s) that are on your browser window at any set time. When the
user stops viewing that page, any scripts that were running on it are immediately stopped. The only
exceptions are cookies or various client side storage APIs, which can be used by many pages to store and
pass information between them, even after the pages have been closed.
Before we go any further, let me say; JavaScript has nothing to do with Java. If we are honest, JavaScript,
originally nicknamed LiveWire and then LiveScript when it was created by Netscape, should in fact be
called ECMAscript as it was renamed when Netscape passed it to the ECMA for standardisation.

3.2 AN INTRODUCTION TO JAVASCRIPT:

JavaScript is a client side, interpreted, object oriented, high level scripting language, while Java is a client
side, compiled, object oriented high level language. Now after that mouthful, here's what it means.
 Client side
o Programs are passed to the computer that the browser is on, and
that computer runs them. The alternative is server side, where the program is run on the server
and only the results are passed to the computer that the browser is on. Examples of this would
be PHP, Perl, ASP, JSP etc.
 Interpreted
o The program is passed as source code with all the programming
language visible. It is then converted into machine code as it is being used. Compiled languages
are converted into machine code first then passed around, so you never get to see the original
programming language. Java is actually dual half compiled, meaning it is half compiled (to 'byte
code') before it is passed, then executed in a virtual machine which converts it to fully compiled
code just before use, in order to execute it on the computer's processor. Interpreted languages
are generally less fussy about syntax and if you have made mistakes in a part they never use, the
mistake usually will not cause you any problems.
 Scripting
o This is a little harder to define. Scripting languages are often used
for performing repetitive tasks. Although they may be complete programming languages, they do
not usually go into the depths of complex programs, such as thread and memory management.
They may use another program to do the work and simply tell it what to do. They often do not
create their own user interfaces, and instead will rely on the other programs to create an
interface for them. This is quite accurate for JavaScript. We do not have to tell the browser
exactly what to put on the screen for every pixel (though there is a relatively new API known as
canvas that makes this possible if needed), we just tell it that we want it to change the
document, and it does it. The browser will also take care of the memory management and thread
management, leaving JavaScript free to get on with the things it wants to do.
 High level
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

o Written in words that are as close to english as possible. The


contrast would be with assembly code, where each command can be directly translated into
machine code.

3.2.1 HISTORY AND VERSIONS:

JavaScript was developed by Brendan Eich in 1995, when Eich was working for Netscape
Communications Corporation. The technology was first called Mocha, then LiveScript. Eventually it was
named JavaScript to follow the marketing of another programming language called Java. Java was
developed by Sun Microsystems and is a completely different programming language and technology.
JavaScript was a competitive technology to VBScript, a Microsoft product. While VBScript worked only
on the Internet Explorer browser, JavaScript was supported on other browsers, too. This made JavaScript
a preferred language for global applications, and it eventually pushed out VBScript from the web
development market.

3.2.2 USES OF JAVASCRIPT:

JavaScript is present in most web pages today. Chances are that the page you are looking at right now contains
the code for JavaScript. Try this activity: Right-click on a web page, then click 'View Source'. You should be able to
find the word JavaScript somewhere in the code of the page.

While HTML markup language allows web developers to format content, JavaScript allows them to make the
page dynamic. For example, HTML allows for making text bold, creating text boxes, and creating buttons,
whereas JavaScript allows for changing text on the page, creating pop-up messages, and validating text in text
boxes to make sure required fields have been filled. JavaScript makes web pages more dynamic by allowing users
to interact with web pages, click on elements, and change the pages.

3.2.3 EVENT -DRIVEN COMPUTATION:

JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the var keyword to declare variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
var x;
x = 6;

JavaScript Operators

JavaScript uses arithmetic operators ( + - * / ) to compute values:


(5 + 6) * 10

JavaScript uses an assignment operator ( = ) to assign values to variables:


var x, y;
x = 5;
y = 6;

JavaScript Expressions

An expression is a combination of values, variables, and operators, which computes to a value.


The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
5 * 10

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

3.3 JAVASCRIPT DOM MODEL

DOM is a set of platform independent and language independent API, that tells how to access and manipulate
information stored in XML, XHTML, JS

Uses:-

 To identify interface and object for representing and manipulating a document


 To find behaviour and attributes of interface & object To find relation between interface and object
3.3.1 DOM TREE

Documents in DOM are represented using a tree like structure


3.3.2 ELEMENT ACCESS USING DOM
Every element is represented as a node This tree structure is called as DOM tree
Level 0 : To access few html elements (by Netscape in 1990s)

Level 1: To change entire web page (1998)

Level 2: Platform independent, language independent---To access dynamically, update contents,


structure, style

Level 3: Platform independent, language independent---To access dynamically, update contents,


structure, style

3.4 DATE AND OBJECTS, REGULAR EXPRESSIONS

Parsing Date Strings using the Date Object


Both the Date(string) constructor and parse() method work on exactly the the same date formats. The
difference is that the constructor creates a Date object, while the static Date.parse() method returns a
number - more precisely, the number of milliseconds since Jan 1, 1970:
var d1 = new Date("March 1, 2013");
console.log(d1); //Fri Mar 1 00:00:00 EST 2013
console.log(typeof d1); //object

var d2 = Date.parse("March 1, 2013");


console.log(d2); //1332302400000
console.log(typeof d2); //number
Either of the above will also work for numeric date formats, assuming that you're dealing with a
supported format, such as yyyy/MM/dd, yyyy/M/d, yyyy/MM/dd hh:mm, or yyyy/mm/dd hh:mm:ss.
Aside from that short list, most other date formats - with the notable exception of long date formats like
Mon, January 1, 2000, which make excellent candidates for string parsing - will result in unpredictable
results at best. Oddly, according to Wikipedia, the standard Calendar date representation allows both the
YYYY-MM-DD and YYYYMMDD formats, as well as the year-month-only YYYY-MM format.
However, trying to parse a date in the YYYY-MM-DD format using JavaScript raises errors in some
browsers:
console.log(Date.parse('2009-7-12')); //results in NaN in IE
console.log(new Date('2009-7-12')); //results in 'Invalid Date' in Firefox

A regular expression is a sequence of characters that forms a search pattern.


The search pattern can be used for text search and text replace operations.
What Is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe what you are searching for.
A regular expression can be a single character, or a more complicated pattern.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Regular expressions can be used to perform all types of text search and text replace operations.
Syntax
/pattern/modifiers;

Example
var patt = /w3schools/i;

Example explained:
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
Using String Methods
In JavaScript, regular expressions are often used with the two string methods: search() and replace().
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.

Using String search() With a Regular Expression


Example
Use a regular expression to do a case-insensitive search for "w3schools" in a string:
var str = "Visit W3Schools";
var n = str.search(/w3schools/i);

The result in n will be:


6

The try...catch...finally Statement

3.5 EXCEPTION HANDLING

The latest versions of JavaScript added exception handling capabilities. JavaScript implements the
try...catch...finally construct as well as the throw operator to handle exceptions.

You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.

Here is the try...catch...finally block syntax −

<script type="text/javascript">

<!--

try {

// Code to run

[break;]

catch ( e ) {

// Code to run if an exception occurs

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

[break;]

[ finally {

// Code that is always executed regardless of

// an exception occurring

}]

//-->

</script>

The try block must be followed by either exactly one catch block or one finally block (or one of both). When an
exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally
block executes unconditionally after try/catch.

3.6 VALIDATION

JavaScript Form Validation


HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form
from being submitted:
JavaScript Example
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}

The function can be called when the form is submitted:


HTML Form Example
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">

3.7 BUILT-IN OBJECTS


</form>

JavaScript String Object


The String object is used to manipulate a stored piece of text.
Examples of use:
The following example uses the length property of the String object to find the length of a string:
var txt="Hello world!"
document.write(txt.length)
The code above will result in the following output:
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

12
The following example uses the toUpperCase() method of the String object to convert a string to
uppercase letters:
var txt="Hello world!"
document.write(txt.toUpperCase())
The code above will result in the following output:
HELLO WORLD!
Complete String Object Reference
For a complete reference of all the properties and methods that can be used with the String object, go to
our complete String object reference.
JavaScript Date Object
Defining Dates
The Date object is used to work with dates and times.
We define a Date object with the new keyword. The following code line defines a Date object called
myDate:
var myDate=new Date()
Note: The Date object will automatically hold the current date and time as its initial value!
Manipulate Dates
We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date()
myDate.setFullYear(2010,0,14)
And in the following example we set a Date object to be 5 days into the future:
var myDate=new Date()
myDate.setDate(myDate.getDate()+5)
Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the
Date object itself!
Comparing Dates
The Date object is also used to compare two dates.
The following example compares today's date with the 14th January 2010:
var myDate=new Date()
myDate.setFullYear(2010,0,14)
var today = new Date()
if (myDate>today)
alert("Today is before 14th January 2010")
else
alert("Today is after 14th January 2010")
Complete Date Object Reference
For a complete reference of all the properties and methods that can be used with the Date object, go to
our complete Date object reference.
JavaScript Array Object
Defining Arrays
The Array object is used to store a set of values in a single variable name.
We define an Array object with the new keyword. The following code line defines an Array object called
myArray:
var myArray=new Array()
There are two ways of adding values to an array (you can add as many values as you need to define as
many variables you require).
1:
var mycars=new Array()
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"
You could also pass an integer argument to control the array's size:
var mycars=new Array(3)
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"
2:
var mycars=new Array("Saab","Volvo","BMW")
Note: If you specify numbers or true/false values inside the array then the type of variables will be
numeric or Boolean instead of string.
Accessing Arrays
You can refer to a particular element in an array by referring to the name of the array and the index
number. The index number starts at 0.
The following code line:
document.write(mycars[0])
will result in the following output:
Saab
Modify Values in Existing Arrays
To modify a value in an existing array, just add a new value to the array with a specified index number:
mycars[0]="Opel"
Now, the following code line:
document.write(mycars[0])
will result in the following output:
Opel
Complete Array Object Reference
For a complete reference of all the properties and methods that can be used with the Array object, go to
our complete Array object reference.
JavaScript Boolean Object
The Boolean object is an object wrapper for a Boolean value.
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).
We define a Boolean object with the new keyword. The following code line defines a Boolean object
called myBoolean:
var myBoolean=new Boolean()
Note: If the Boolean object has no initial value or if it is 0, -0, null, "", false, undefined, or NaN, the
object is set to false. Otherwise it is true (even with the string "false")!
All the following lines of code create Boolean objects with an initial value of false:
var myBoolean=new Boolean()
var myBoolean=new Boolean(0)
var myBoolean=new Boolean(null)
var myBoolean=new Boolean("")
var myBoolean=new Boolean(false)
var myBoolean=new Boolean(NaN)
And all the following lines of code create Boolean objects with an initial value of true:
var myBoolean=new Boolean(true)
var myBoolean=new Boolean("true")
var myBoolean=new Boolean("false")
var myBoolean=new Boolean("Richard")

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Complete Boolean Object Reference


For a complete reference of all the properties and methods that can be used with the Boolean object, go to
our complete Boolean object reference.
JavaScript Math Object
The Math object allows you to perform common mathematical tasks.
The Math object includes several mathematical values and functions. You do not need to define the Math
object before using it.
Mathematical Values
JavaScript provides eight mathematical values (constants) that can be accessed from the Math object.
These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E,
and base-10 log of E.
You may reference these values from your JavaScript like this:
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
Mathematical Methods
In addition to the mathematical values that can be accessed from the Math object there are also several
functions (methods) available.
Examples of functions (methods):
The following example uses the round() method of the Math object to round a number to the nearest
integer:
document.write(Math.round(4.7))
The code above will result in the following output:
5
The following example uses the random() method of the Math object to return a random number between
0 and 1:
document.write(Math.random())
The code above can result in the following output:
0.13251054050929345
The following example uses the floor() and random() methods of the Math object to return a random
number between 0 and 10:
document.write(Math.floor(Math.random()*11))
The code above can result in the following output:
3
3.8 EVENT HANDLING

What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user or the browser
manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other
examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close
windows, messages to be displayed to users, data to be validated, and virtually any other type of response
imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set
of events which can trigger JavaScript Code.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see
a few examples to understand a relation between Event and JavaScript −
onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of his mouse.
You can put your validation, warning etc., against this event type.
Example
Try the following example.
<html>
<head>

<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>

</head>

<body>
<p>Click the following button and see result</p>

<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>

</body>
</html>

3.9 DHTML WITH JAVASCRIPT

DHTML

document.write()
can be used to display dynamic content to a web page.
Example
Using JavaScript to display the current date:
<html>
<body>

<script type="text/javascript">
document.write(Date());
</script>

</body>
</html>

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

3.10 SERVLETS

Servlets are defined as simple java programs that are dynamically loaded and run on JVM of web servers, to
respond to the requests from the clients

It acts as middle layer between browser and server

To develop sites with secure access, interact with DB, maintain unique session info of each client

Used with HTTP, hence called HttpServlet It makes use of two packages:

Javax.servlet and javax.servlet.http servlet container

The server that executes a servlet is called as servlet container or servlet engine

Browsers send an HTTP request to server, which in turn sends to servlet container

Servlet container receives the request from the server, processes appropriate servlet, sends back request

Steps:-

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the
servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet instance is
created only once in the servlet life cycle.

3) init method is invoked

The web container calls the init method only once after creating the servlet instance. The init method is used to
initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is
given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet is received. If servlet is not
initialized, it follows the first three steps as described above then calls the service method. If servlet is
initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service
method of the Servlet interface is given below:

public void service


(ServletRequest request, ServletResponse response)

throws ServletException, IOException


destroy method is invoked

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

The web container calls the destroy method before removing the servlet instance from the service. It gives the
servlet an opportunity to clean up any resource for example memory, thread etc.

3.11 JAVA SERVLET ARCHITECTURE

A Servlet is a class, which implements the javax.servlet.Servlet interface. However instead of


directly implementing the javax.servlet.Servlet interface we extend a class that has implemented the
interface like javax.servlet.GenericServlet or javax.servlet.http.HttpServlet.

Servlet Exceution
This is how a servlet execution takes place when client (browser) makes a request to the webserver.

Servlet architecture includes:


a) Servlet Interface
To write a servlet we need to implement Servlet interface. Servlet interface can be implemented directly
or indirectly by extending GenericServlet or HttpServlet class.
b)Request handling methods
There are 3 methods defined in Servlet interface: init(), service() and destroy().
The first time a servlet is invoked, the init method is called. It is called only once during the lifetime of a
servlet. So, we can put all your initialization code here.
The Service method is used for handling the client request. As the client request reaches to the container
it creates a thread of the servlet object, and request and response object are also created. These request
and response object are then passed as parameter to the service method, which then process the client
request. The service method in turn calls the doGet or doPost methods (if the user has extended the class
from HttpServlet ).
c) Number of instances

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Basic Structure of a Servlet


public class firstServlet extends HttpServlet {
public void init() {
/* Put your initialization code in this method,
* as this method is called only once */
}
public void service() {
// Service request for Servlet
}
public void destroy() {
// For taking the servlet out of service, this method is called only once
}
}
3.12 SERVLET LIFE CYCLE

Life Cycle of a Servlet (Servlet Life Cycle)

1. Life Cycle of a Servlet


1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is
in new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

state. In the ready state, servlet performs all the tasks. When the web container invokes the destroy()
method, it shifts to the end state.
3.13 FORM GET AND POST ACTIONS

What is HTTP?

The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers.

HTTP works as a request-response protocol between a client and server.

A web browser may be the client, and an application on a computer that hosts a web site may be the server.

Example: A client (browser) submits an HTTP request to the server; then the server returns a response to the
client. The response contains status information about the request and may also contain the requested content.

Two HTTP Request Methods: GET and POST

Two commonly used methods for a request-response between a client and server are: GET and POST.

 GET - Requests data from a specified resource


 POST - Submits data to be processed to a specified resource

The GET Method

Note that the query string (name/value pairs) is sent in the URL of a GET request:

/test/demo_form.php?name1=value1&name2=value2

Some other notes on GET requests:

 GET requests can be cached


 GET requests remain in the browser history
 GET requests can be bookmarked
 GET requests should never be used when dealing with sensitive data
 GET requests have length restrictions
 GET requests should be used only to retrieve data

The POST Method

Note that the query string (name/value pairs) is sent in the HTTP message body of a POST request:

POST /test/demo_form.php HTTP/1.1


Host: w3schools.com
name1=value1&name2=value2

Some other notes on POST requests:

 POST requests are never cached


 POST requests do not remain in the browser history
 POST requests cannot be bookmarked
 POST requests have no restrictions on data length
3.14 SESSION HANDLING, UNDERSTANDING COOKIES

It is a mechanism by which we can keep track of previous sessions between server and browser
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Session ID is passed between client and server

HTTP cannot have any data about precious client-server communication (stateless)

To achieve it, we use session tracking

Session Tracking Techniques

There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies in Servlet

A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a
maximum age, and a version number.

How Cookie works

 By default, each request is considered as a new request.


o In cookies technique, we add cookie with response from the servlet.
 So cookie is stored in the cache of the browser.
o After that if request is sent by the user, cookie is added with request by default. Thus, we
recognize the user as the old user.
Types of Cookie

There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time

when user closes the browser. It is removed only if user logout or signout.

Advantage of Cookies

1. Simplest technique of maintaining the state.


2. Cookies are maintained at client side.

Disadvantage of Cookies

1. It will not work if cookie is disabled from the browser.


2. Only textual information can be set in Cookie object.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.

Hidden Form Fields

A web server can send a hidden HTML form field along with a unique session ID as follows:

<input type="hidden" name="sessionid" value="12345">

This entry means that, when the form is submitted, the specified name and value are automatically included in
the GET or POST data.

Each time when web browser sends request back, then session_id value can be used to keep the track of
different web browsers.

This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link
does not result in a form submission, so hidden form fields also cannot support general session tracking.

3.15 INSTALLING AND CONFIGURING APACHE TOMCAT WEB SERVER:

What is Apache Tomcat


It is an application server or web server or servlet container developed by the Apache Software
Foundation (ASF) and released under the Apache License version 2. HTTP web servers provide an
environment for Java code to run in. It includes tools for configuration and management, but can also be
configured by editing XML configuration files. Most of the modern Java web frameworks are based on
servlets and JavaServer Pages and can run on Apache Tomcat, for example Struts, JavaServer Faces,
Spring, etcetera.
Apache Tomcat7.0.XX new released
The Apache Tomcat team has released version 7.0.40 of Apache. They removed several fixes that stop
Tomcat attempting to parse text, improved handling and reporting if a ConcurrentModificationException
occurs while checking for memory leaks, etcetera.
How to Install Tomcat 7
There are certain steps we must follow for configuring Apache Tomcat 7.
Step 1
Download and Install Tomcat
1. Go to http://tomcat.apache.org/download-70.cgi then go to the Binary Distribution/Core/ and download
the "zip" package (for example "apache-tomcat-7.0.40.zip", about 8MB).
2. Now unzip the downloaded file into a directory of our choice. Don't unzip onto the dekstop (since its path
is hard to locate). I suggest using "e:\myserver". Tomcat will be unzipped into the directory
"e:\myserver\tomcat-7.0.40".
Step 2
Check the installed directory to ensure it contains the following sub-directories:
 bin folder
 logs folder
 webapps folder
 work folder
 temp folder
 conf folder
 lib folder
Step 3
Now, we need to create an Environment Variable JAVA_HOME.
We need to create an environment variable called "JAVA_HOME" and set it to our JDK installed
directory.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

1. To create the JAVA_HOME environment variable in Windows XP/Vista/7 we need to push the "Start"
button then select "Control Panel" / "System" / "Advanced system settings". Then switch to the
"Advanced" tab and select "Environment Variables" / "System Variables" then select "New" (or "Edit" for
modification). In "Variable Name", enter "JAVA_HOME". In "Variable Value", enter your JDK installed
directory (e.g., "c:\Program Files\Java\jdk1.7.0_{xx}").
2. For ensuring that it is set correctly, we need to start a command shell (to refresh the environment) and
issue:
set JAVA_HOME
JAVA_HOME=c:\Program Files\Java\jdk1.7.0_{xx} <== Check that this is OUR JDK installed directory
3. Sometimes we need to set JRE_HOME also. So for creating JRE_HOME we need to use the same
procedure. Push the "Start" buttonthen select "Control Panel" / "System" / "Advanced system
settings". Then switch to the "Advanced" tab and select "Environment Variables" / "System
Variables" then select "New" (or "Edit" for modification). In "Variable Name", enter "JRE_HOME". In
"Variable Value", enter your JRE installed directory (e.g., "C:\Program Files\Java\jre7\").
Step 4
Configure Tomcat Server
The configuration files of the Apache Tomcat Server are located in the "conf" sub-directory of our
Tomcat installed directory, for example "E:\myserver\tomcat7.0.40\conf". There are 4 configuration
XML files:
1. context.xml file
2. tomcat-users.xml file
3. server.xml file
4. web.xml file
Before proceeding, make a BACKUP of the configuration files.
Step 4(a) "conf\web.xml"; Enabling a Directory Listing
Open the configuration file "web.xml". We shall enable the directory listing by changing "listings" from
"false" to "true" for the "default" servlet.
<param-value>true</param-value> like:

Step 4(b) "conf\server.xml file"; set the TCP Port Number


Open the file "server.xml" in a text editor.
The default port number of Tomcat is 8080. Now we need to change the TCP port number for Tomcat,
since the same port number can be used by other servers like SQL Server. We may choose any number
between 1024 and 65535. We shall choose 9999 in this article.
Locate the following lines, and change port="8080" to port="9999". Like:
<Connector port="9999" protocol="HTTP/1.1" Like
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Step 4(c) "conf\context.xml"; Enabling Automatic Reload


In that we set reloadable="true" to the <Context> element to enable automatic reload after code changes.
Add reloadable="true" as in the following:
<Context reloadable="true">
......
</Context> Like

Step 4(d) (Optional) "conf\tomcat-users.xml"


It is used to manage Tomcat by adding the highlighted lines, inside the <tomcat-users> elements.
In that we can add a password and username as an optional step.
Step 5
Now, start the tomcat server
Executable programs and scripts are kept in the "bin" sub-directory of the Tomcat installed directory,
e.g., "E:\myserver\tomcat7.0.40\bin".
Step 5(a) Start Server
Launch a command shell. Set the current directory to "<TOMCAT_HOME>\bin" like
E:\myserver\tomcat7.0.40\bin, and run "startup.bat" as follows:

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

After that a new Tomcat console window appears. Read the messages on the console. Look out for the
Tomcat's port number (double check that Tomcat is running on port 9999).......
3.16 DATABASE CONNECTIVITY

3.16.1 JDBC perspectives,

JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.
JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity
between the Java programming language and a wide range of databases.

The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with
database usage.

Making a connection to a database. Creating SQL or MySQL statements.

Executing SQL or MySQL queries in the database. Viewing & Modifying the resulting records.

JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code.

JDBC Architecture

The JDBC API supports both two-tier and three-tier processing models for database access but in general, JDBC
Architecture consists of two layers −

JDBC API: This provides the application-to-JDBC Manager connection.

JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to
heterogeneous databases.

The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is
capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.

Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC
drivers and the Java application −

Common JDBC Components

The JDBC API provides the following interfaces and classes −


M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

DriverManager: This class manages a list of database drivers. Matches connection requests from the java
application with the proper database driver using communication sub protocol. The first driver that
recognizes a certain subprotocol under JDBC will be used to establish a database Connection.

Driver: This interface handles the communications with the database server. You will interact directly
with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this
type. It also abstracts the details associated with working with Driver objects.

Connection: This interface with all methods for contacting a database. The connection object represents
communication context, i.e., all communication with database is through connection object only.

Statement: You use objects created from this interface to submit the SQL statements to the database. Some
derived interfaces accept parameters in addition to executing stored procedures.

3 . 1 6 . 2 JDBC program example

Program:- java.sql.*;
public class FirstExample
{
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL =
"jdbc:mysql://localhost/EMP"; static final String USER = "username";
static final String PASS = "password"; public static void main(String[] args)

Connection conn = null; Statement stmt = null; try

Class.forName("com.mysql.jdbc.Driver"); System.out.println("Connecting to database...");


conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement..."); stmt = conn.createStatement();
String sql;

sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql);
while(rs.next()
{

int id = rs.getInt("id");

int age = rs.getInt("age"); String first = rs.getString("first"); String last =


rs.getString("last"); System.out.print("ID: " + id);

System.out.print(", Age: " + age); System.out.print(", First: " + first);


System.out.println(", Last: " + last);

}
rs.close();

stmt.close();

conn.close();
}

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

catch(SQLException se)

{
se.printStackTrace();

}
catch(Exception e)

e.printStackTrace();
}

finally
{

try

{
if(stmt!=null) stmt.close();

catch(SQLException se2)
{

}
try

if(conn!=null) conn.close();
}

catch(SQLException se)

{
se.printStackTrace();

}
}

System.out.println("Goodbye!");

}
}

C:\>javac FirstExample.java

C:\>
When you run FirstExample, it produces the following result −

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

C:\>java FirstExample Connecting to database...


Creating statement...

ID: 100, Age: 18, First: Zara, Last: Ali

ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal

3.17 JSP

Java Server Pages is a kind of server side scripting language that enables user to embed java code with
HTML elements for the creation of dynamic, platform-independent method for building web apps

JSP = Java + HTML + servlet

JavaServer Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
platform-independent method for building Web-based applications.

JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases

JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content which
helps developers insert java code in HTML pages by making use of special JSP tags, most of which start
with <% and end with %>.

A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user
interface for a Java web application.

Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and
embedded JSP actions and commands.

Using JSP, you can collect input from users through web page forms, present records from a database or
another source, and create web pages dynamically.

JSP tags can be used for a variety of purposes, such as retrieving information from a database or
registering user preferences, accessing JavaBeans components, passing control between pages and
sharing information between requests,

pages etc.

Architecture

The web server needs a JSP engine ie. container to process JSP pages.

The JSP container is responsible for intercepting requests for JSP pages

A JSP container works with the Web server to provide the runtime environment and other services a JSP
needs.

It knows how to understand the special elements that are part of JSPs.

JSP Processing

As with a normal page, your browser sends an HTTP request to the web server.

The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is
done by using the URL or JSP page which ends with .jsp instead of .html.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

The JSP engine loads the JSP page from disk and converts it into a servlet content.

3.18 UNDERSTANDING JAVA SERVER PAGES

JSP Processing

The following steps explain how the web server creates the web page using JSP: As with a normal page, your
browser sends an HTTP request to the web server.

The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by
using the URL or JSP page which ends with .jsp instead of .html.

The JSP engine loads the JSP page from disk and converts it into a servlet content.

This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements
are converted to Java code that implements the corresponding dynamic behavior of the page,

The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet
engine.A part of the web server called the servlet engine loads the Servlet class and executes it. During execution,
the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP
response.

The web server forwards the HTTP response to your browser in terms of static HTML content.Finally web browser
handles the dynamically generated HTML page inside the HTTP response exactly as if it were a static page.

A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a
servlet life cycle with an additional step which is required to compile a JSP into servlet.

The following are the paths followed by a JSP

Compilation Initialization Execution Cleanup

The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:

JSP Compilation

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the
page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles
the page. The compilation process involves three steps:

Parsing the JSP.

JSP Initialization

When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform
JSP-

specific initialization, override the jspInit() method: public void jspInit(){

// Initialization code...

JSP Execution

This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.Whenever a
browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService()
method in the JSP.

The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows:

void _jspService(HttpServletRequest request, HttpServletResponse response)

// Service handling code...

The _jspService() method of a JSP is invoked once per a request and is responsible for generating the
response for that request and this method is also responsible for generating responses to all seven of the
HTTP methods ie. GET, POST, DELETE etc.

JSP Cleanup

The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.

The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you
need to perform any cleanup, such as releasing database connections or closing open files.

public void jspDestroy()

// Your cleanup code goes here.

Advantage of JSP over Servlet

1) Extension to Servlet

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

JSP technology is the extension to servlet technology. We can use all the features of servlet in JSP. In addition to,
we can use implicit objects, predefined tags, expression language and Custom tags in JSP, that makes JSP
development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with presentation logic. In servlet
technology, we mix our business logic with the presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code needs to be
updated and recompiled if we have to change the look and feel of the application.

4) Less code than Servlet

In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code. Moreover, we can
use EL, implicit objects etc.

3.19 JSP STANDARD TAG LIBRARY

JSP Scripting elements

Scripting elements provides the ability to insert java code inside the jsp.

scriptlet tag

expression tag declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP
Example

In this example, we have created two files index.html and welcome.jsp. The index.html file gets the username
from the user and the welcome.jsp file prints the username with the welcome message.
File: index.html
<html>

<body>

<form action="welcome.jsp"> <input type="text" name="uname">

<input type="submit" value="go"><br/> </form>

</body>

</html>
File: welcome.jsp

<html>
<body>
<%

String name=request.getParameter("uname"); out.print("welcome "+name);

%>
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

</form>
</body>
</html>

JSP expression tag The code placed within JSP expression tag is written to the output stream of the response. So
you need not write out.print() to write data. It is mainly used to print the values of variable or method.
Example of JSP expression tag that prints the user name
In this example, we are printing the username using the expression tag. The index.html file gets the username
and sends the request to the welcome.jsp file, which displays the username.
File: index.jsp

<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/> <input type="submit" value="go"> </form>
</body>
</html>

File: welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %> </body>
</html>

JSP Declaration Tag

The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service() method of auto generated
servlet.

So it doesn't get memory at each request.

<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %> </body>
</html>

JSTL (JSP Standard Tag Library)

The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.
Advantage of JSTL

1. Fast Developement JSTL provides many tags that simplifies the JSP.

2. Code Reusability We can use the JSTL tags in various pages.


3. No need to use scriptlet tag It avoids the use of scriptlet tag.

JSTL Core Tags

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

The JSTL core tag provides variable support, URL management, flow control etc.

The syntax used for including JSTL core library in your JSP is: <%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %>

3.20 CREATING HTML FORMS BY EMBEDDING JSP CODE.


A Simple HTML Form
To start off the exploration of HTML forms, it's best to start with a small form and expand from there.
Also, it's better to start with a JSP rather than a servlet, because it is easier to write out the HTML. Most
of the form handling for JSPs and servlets is identical, so after you know how to retrieve form
information from a JSP, you know how to do it from a servlet. Listing 3.1 shows an HTML file
containing a simple input form that calls a JSP to handle the form.
<html>
<body>
<h1>Please tell me about yourself</h1>
<form action="SimpleFormHandler.jsp" method="get">
Name: <input type="text" name="firstName">
<input type="text" name="lastName"><br>
Sex:
<input type="radio" checked name="sex" value="male">Male
<input type="radio" name="sex" value="female">Female
<p>
What Java primitive type best describes your personality:
<select name="javaType">
<option value="boolean">boolean</option>
<option value="byte">byte</option>
<option value="char" selected>char</option>
<option value="double">double</option>
<option value="float">float</option>
<option value="int">int</option>
<option value="long">long</option>
</select>
<br>
<input type="submit"></form></body></html>

UNIT IV

PHP AND XML


4.1 AN INTRODUCTION TO PHP
PHP
 PHP is defined as a server side scripting language that is mainly used for form handling and
database access.
 PHP stands for Hypertext Pre Processor
 It was invented in 1994 by Rasmus Lerdorf
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 It is the most popular scripting language in web It is a FOSS

Features of PHP
 Embedded inside HTML, easy to develop FOSS
 Easy to manage dynamic content, database, session tracking
 Supports many protocols such as LDAP, IMAP, POP3 Supports many databases such as MS SQL
server,
 Oracle, SyBase, PostgreSQL, MySQL, etc As much forgiving as possible
 Simple like C and HTML

List the uses of PHP


o To perform system functions such as file create, open, close, read, write, etc

o To handle forms, gather data from files, save data to a file, send email, etc

o To add, delete, modify database contents To access and set cookies and
variables To restrict users from page access

o To encrypt data

What are the rules in PHP?


o White space insensitive Case sensitive

o Each statement ends with semi colon Expressions are combination of


tokens Braces creates blocks
o $ is used before variables

o file as .php and access it from localhost server

4.2 USING PHP


These PHP functions allow you to interact with and manipulate arrays in various ways. Arrays are
essential for storing, managing, and operating on sets of variables.
Returns an array of the parameters.
The parameters can be given an index with the => operator. PHP functions are similar to other
programming languages.A function is a piece of code which takes one more input in the form of
parameter and does some processing and returns a value.In fact you hardly need to create your own
PHP function because there are already more than 1000 of built-in library functions created for
different area and you just need to call them according to your requirement.

The real power of PHP comes from its functions; it has more than 1000 built-in functions
PHP User Defined Functions
Besides the built-in PHP functions, we can create our own functions. A function is a block of statements
that can be used repeatedly in a program. A function will not execute immediately when a page loads. A
function will be executed by a call to the function.
<?php

function writeMsg() O/p:-

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

{
echo "Hello Hellow
world!"; orld
}
writeMsg();
?>
function name($fname, $dob)

echo "$fname was born on $dob <br>";


}

name("Bala","12-2-91"); name("Gopal","22-12-96");

?> o/p:-
Bala was born on 12-2-91

Gopal was born on 22-12-96

<?php
function
sum($x, $y)
{
return $x +
$y;
}
echo sum(10,20) .
"<br>";
300
echo sum(100,200) . "<br>";
?>

O/P:
30
4.3 VARIABLES
The main way to store information in the middle of a PHP program is by using a variable.

Here are the most important things to know about variables in PHP.

 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will
be used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when necessary.
 PHP variables are Perl-like.
PHP has a total of eight data types which we use to construct our variables −

 Integers − are whole numbers, without a decimal point, like 4195.


 Doubles − are floating-point numbers, like 3.14159 or 49.1.
 Booleans − have only two possible values either true or false.
 NULL − is a special type that only has one value: NULL.
 Strings − are sequences of characters, like 'PHP supports string operations.'
 Arrays − are named and indexed collections of other values.
 Objects − are instances of programmer-defined classes, which can package up both other kinds
of values and functions that are specific to the class.
 Resources − are special variables that hold references to resources external to PHP (such as
database connections).
The first five are simple types, and the next two (arrays and objects) are compound - the compound
types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.

We will explain only simple data type in this chapters. Array and Objects will be explained separately.

Integers

They are whole numbers, without a decimal point, like 4195. They are the simplest type .they
correspond to simple whole numbers, both positive and negative. Integers can be assigned to variables,
or they can be used in expressions, like so −

$int_var = 12345;

$another_int = -12345 + 12345;

Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal format is
the default, octal integers are specified with a leading 0, and hexadecimals have a leading 0x.

For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the smallest
(most negative) integer is . (2**31 . 1) (or .2,147,483,647).

Doubles

They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal places
needed. For example, the code −

<?php

$many = 2.2888800;

$many_2 = 2.2111200;

$few = $many + $many_2;

print("$many + $many_2 = $few <br>");

?>
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

It produces the following browser output −

2.28888 + 2.21112 = 4.5

Boolean

They have only two possible values either true or false. PHP provides a couple of constants especially
for use as Booleans: TRUE and FALSE, which can be used like so −

if (TRUE)

print("This will always print<br>");

else

print("This will never print<br>");

4.4 PROGRAM CONTROL


PHP supports following three decision making statements.
The if, elseif ...else and switch statements are used to take decision based on the different
condition.
You can use conditional statements in your code to make your decisions.

The If...Else Statement

If you want to execute some code if a condition is true and another code if a condition is false, use the
if....else statement.
<?php $a=10;

if ($a == 10) echo "a value is 10"; else echo "a value is not 10";

?> o/p:-

a value is 10

.The If..ElseIf..Else Statement

If one of the several conditions are true, then use elseif statement

<?php $a=10;

if ($a > 0) echo "a is positive"; elseif ($a< 0) echo "a is negative"; else echo
"a is zero"

?>

O/P:-

a is positive

The Switch Statement

If you want to select one of many blocks of code to be executed, use the Switch statement.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

The switch statement is used to avoid long blocks of if..elseif..else code.

The value of the expression is then compared with the values for each case in the structure.

If there is a match, the block of code associated with that case is executed. Use break to
prevent the code from running into the next case automatically.

The default statement is used if no match is found.

<?php

$fav = "green"; switch ($fav)

case "red":

echo "Your favorite color is red!"; break;

case "blue":

echo "Your favorite color is blue!"; break;

case "green":

echo "Your favorite color is green!"; break;

default:

echo "Your favorite color is neither red, blue, nor green!";

?>

o/p:-

Your favorite color is green!

The for loop statement

The for statement is used when you know how many times you want to execute a statement
or a block of statements.

<?php

for( $i = 0; $i<5; $i++ ) { echo $i,"\n";

?>

o/p:
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

01234

The while loop statement

The while statement will execute a block of code if and as long as a test expression is true.

If the test expression is true then the code block will be executed. After the code has executed the
test expression will again be

evaluated and the loop will continue until the test expression is found to be false.

<?php

$i = 0;

while( $i < 10)

echo $i; $i++;

?>

o/p:-

0123456789

The do...while loop statement

The do...while statement will execute a block of code at least once - it then will repeat the loop
as long as a condition is true.

<?php

$i = 0; do

echo $i; $i++;

while( $i < 10 );

?>

o/p:-

0123456789

The foreach loop statement

The foreach statement is used to loop through arrays.


M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

For each pass the value of the current array element is assigned to $value

array pointer is moved by one and in the next pass next

element will be processed.

<?php

$a = range(0,9); foreach( $a as $i )

echo $i,"<br>";

?> o/p:-

0123456789

4.5 BUILT-IN FUNCTIONS

PHP Built-in functions:-

 PHP Array Functions


 PHP Calender Functions
 PHP Class/Object Functions PHP Character Functions
 PHP Date & Time Functions PHP Directory Functions
 PHP Error Handling Functions PHP File System Functions
 PHP MySQL Functions PHP Network Functions PHP ODBC Functions PHP String Functions
 PHP SimpleXML Functions PHP XML Parsing Functions

PHP - Array Functions

<?php

$a = array("a"=>"Dog", "b"=>"Cat", "c"=>"Horse"); print_r($a);

?>

o/p
Array ( [a] => Dog [b] => Cat [c] => Horse)
array_chunk()

Chunks an array into size large chunks.

The last chunk may contain less than size elements. <?php

$input_array = array('a', 'b', 'c', 'd', 'e'); print_r(array_chunk($input_array, 2));


print_r(array_chunk($input_array, 2, true));

?>
o/p

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Array (

[0] => Array (


[0] => a

[1] => b
)

[1] => Array (


[0] => c

[1] => d
)

[2] => Array (


[0] => e

Array
(

[0] => Array (


[0] => a
[1] => b

[1] => Array (


[2] => c
[3] => d

[2] => Array (

[4] => e

)
)

array_keys() and array_values()

<?php

$array = array("a"=>"green", "b"=>"brown", "c"=>"blue", "red"); print_r(array_values($array));

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

echo "<br>"; print_r(array_keys($array));


?>

o/p

Array ( [0] => green [1] => brown [2] => blue [3] => red ) Array ( [0] => a [1] => b [2] => c [3] => 0 )
array_merge()

Merges elements of one or more arrays together so that the values of one are appended to end
of the previous one.

If the input arrays have the same string keys, then the later

value for that key will overwrite the previous one.


<?php

$array1 = array("a"=>"Horse","b"=>"Cat","c"=>"Dog"); $array2 = array("d"=>"Cow",


"e"=>"elephant"); print_r(array_merge($array1,$array2));
?>
O/p:-

Array ( [a] => Horse [b] => Cat [c] => Dog [d] => Cow [e] => elephant )

array_push()

This function treats array as a stack, and pushes the passed variables var1, var2... onto the end
of array. The length of

array increases by the number of variables pushed.


<?php

$array = array("0"=>"banana","1"=>"apple","3"=>"orange"); print_r(array_push($array,


"mango"));

print_r("<br>"); print_r($array );

?> o/p:-

4
Array ( [0] => banana [1] => apple [3] => orange [4] => mango )

array_pop()

This function pops and returns the last value of the array, shortening the array by one element.

If array is empty (or is not an array), NULL will be returned <?php

$array = array("0"=>"banana","1"=>"apple","2"=>"orange"); print_r($array);

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

print_r("<br>"); print_r(array_pop($array)); print_r("<br>");


print_r($array);

?> o/p:-

Array ( [0] => banana [1] => apple [2] => orange ) orange

Array ( [0] => banana [1] => apple )

Search() and sum()

<?php

O/
$a = array(1,2,3,4); p:-

print_r(array_sum($a)
);

10

echo "<br>";

print_r(array_search(
3, $a)); 2

?>

PHP – calendar functions

The calendar extension presents a series of functions to simplify converting between different
calendar formats.

The intermediary or standard it is based on is the Julian Day Count.

The Julian Day Count is a count of days starting from January 1st, 4713 B.C.

To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar
system of your choice.

4.6 CONNECTING TO DATABASE

PHP 5 and later can work with a MySQL database using:


 MySQLi extension (the "i" stands for improved)
 PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.

Should I Use MySQLi or PDO?


If you need a short answer, it would be "Whatever you like".
Both MySQLi and PDO have their advantages:

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

PDO will work on 12 different database systems, where as MySQLi will only work with MySQL
databases.
So, if you have to switch your project to use another database, PDO makes the process easy. You only
have to change the connection string and a few queries. With MySQLi, you will need to rewrite the entire
code - queries included.
Both are object-oriented, but MySQLi also offers a procedural API.
Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very
important for web application security.
MySQL Examples in Both MySQLi and PDO Syntax
In this, and in the following chapters we demonstrate three ways of working with PHP and MySQL:
 MySQLi (object-oriented)
 MySQLi (procedural)
 PDO
MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most cases, when php5
mysql package is installed.
For installation details, go to: http://php.net/manual/en/mysqli.installation.php
PDO Installation
For installation details, go to: http://php.net/manual/en/pdo.installation.php
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able to connect to the server:
Example (MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

PHP is an amazing and popular language!


Note on the object-oriented example above: $connect_error was broken until PHP 5.2.9 and 5.3.0. If you
need to ensure compatibility with PHP versions prior to 5.2.9 and 5.3.0, use the following code instead:

// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

Notice that in the PDO example above we have also specified a database (myDB). PDO require a valid
database to connect to. If no database is specified, an exception is thrown.
Tip: A great benefit of PDO is that it has an exception class to handle any problems that may occur in
our database queries. If an exception is thrown within the try{ } block, the script stops executing and
flows directly to the first catch(){ } block.
Close the Connection
The connection will be closed automatically when the script ends. To close the connection before, use the
following:
Example (MySQLi Object-Oriented)
$conn->close();

Example (MySQLi Procedural)


mysqli_close($conn);

Example (PDO)
$conn = null;

4.7 USING COOKIES

What is a Cookie?

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too. With
PHP, you can both create and retrieve cookie values.
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.

PHP Create/Retrieve a Cookie


The following example creates a cookie named "user" with the value "John Doe". The cookie will expire
after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select
the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the
isset() function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

4.8 REGULAR EXPRESSIONS

Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the
foundation for pattern-matching functionality.
Using regular expression you can search a particular string inside a another string, you can replace one
string by another string and you can split a string into many chunks.
PHP offers functions specific to two sets of regular expression functions, each corresponding to a certain
type of regular expression. You can use any of them based on your comfort.
 POSIX Regular Expressions
 PERL Style Regular Expressions
POSIX Regular Expressions
The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression:
various elements (operators) are combined to form more complex expressions.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

The simplest regular expression is one that matches a single character, such as g, inside strings such as g,
haggle, or bag.
Lets give explanation for few concepts being used in POSIX regular expression. After that we will
introduce you with regular expression related functions.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to
find a range of characters.
Sr.No Expression & Description

1 [0-9]
It matches any decimal digit from 0 through 9.
2 [a-z]
It matches any character from lower-case a through lowercase z.
3 [A-Z]
It matches any character from uppercase A through uppercase Z.
4 [a-Z]
It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit
ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters can be denoted by a
special character. Each special character having a specific connotation. The +, *, ?, {int. range}, and $
flags all follow a character sequence.
Sr.No Expression & Description

1 p+
It matches any string containing at least one p.
2 p*
It matches any string containing zero or more p's.
3 p?
It matches any string containing zero or more p's. This is just an alternative way to use p*.
4 p{N}
It matches any string containing a sequence of N p's
5 p{2,3}
It matches any string containing a sequence of two or three p's.
6 p{2, }
It matches any string containing a sequence of at least two p's.
7 p$
It matches any string with p at the end of it.
8 ^p
It matches any string with p at the beginning of it.

4.9 XML

XML

Extensible Markup language

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Definition:-

XML is a mark up language that defines set of rules for encoding documents in a format that is both
human readable and machine readable

 It is a text based mark up language derived from SGML


 It was introduced by W3C to overcome the problems in HTML Markup means, information
added to a document that improves its meaning
 It is not a programming language It is stored in text file
 It is parsed by XML parser

 No predefined tags in XML, only user defined tags It is stricter than HTML, case sensitive
4.10 BASIC XML

Features of XML / Advantages / Uses

o Simplify the creation of HTML documents for large sites To exchange information
between organizations
o Offload and reload databases Store and arrange data
o Any type of data can be expressed in XML
o Suits well for commerce applications, scientific purposes, mathematics, chemical
formulae
o It can be used in handheld devices, smartphones, etc Hardware, software and
language independent
Syntax rules

XML declaration References

Tags and elements Attributes

Text

XML declaration

< ? xml version = “1.0” ?>

“xml” should be in lower case

Every XML document should begin with <?xml…>

It must be the root element in all XML files

Tags and elements

Tags are the building blocks of XML document It is also called XML nodes

<name>Bala</name>

<person>

<name>Bala</name>

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

<phone>1234</phone>

</person>

Attributes

To specify a property of an element

It is a “name-value” pair

An element can have more than 1 attributes

<phone available=”yes”>1234</phone>

References

To add additional information Begin with &

o Entity reference

o Character Reference

Text

XML elements and attributes are case sensitive Start and end tag needs to be in
same case

To avoid encoding problems, use UTF-8 or UTF-16 It is whitespace insensitive

Example:-

<?xml version=”1.0”?>

<person>

<name>Bala</name>

<cell>1234</cell>

<company>TCS</company>

</person> Rules for XML

If any XML declaration is present, put it in the first line Mention the version of XML

Parameters and values are case sensitive Names are always in lower case

Either “ or ‘ can be used

<?xml…?> has no close tag

Only - , _ and . are allowed in elements

Comment inside < ! - - this is a comment - - >


M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

No comments should be made before <?xml…..?>

XML tags

Start tag End tag

Empty tag (has no close tag)

XML attributes

XML HTML

Software and Software and


hardware hardware

independent dependent

To send and store


data To display data

Focus on what data Focus on how data


is looks

present

It is a Framework It is a mark up
for language

markup language

definition

Case sensitive Case insensitive

Transport data Design client side


between web

app and database programs

Custom tags Only predefined


allowed tags

Open and close tags


are Not strict

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

strict

White space White space


insensitive insensitive

Carry information Display information

Dynamic static

4.11 DOCUMENT TYPE DEFINITION

DTD in XML

Document Type Definition

To define the type of the document A DTD is attached to a document To


describe the XML

Syntax:-

The DTD starts with <!DOCTYPE delimiter.

An element tells the parser to parse the document from the specified root element.

DTD identifier is an identifier for the document type definition, which may be the path to a file
on the system or URL to a file on the internet. If the DTD is pointing to external path, it is called
External Subset.

The square brackets [ ] enclose an optional list of entity declarations called Internal Subset.

Internal DTD

Elements are declared within XML

DTD is stored within the XML file itself.

Set stand alone attribute = “yes”

sample.xml

<? xml version = “1.0” encoding = “utf-8” standalone=”yes”?>

< ! DOCTYPE address

< ! ELEMENT address(name, phone,

company)>
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

< ! ELEMENT name(#PCDATA)>


< ! ELEMENT phone(#PCDATA)>
< ! ELEMENT company(#PCDATA)>
><address>

<name>Bala</name>

<phone>1234</phone>

<company>TCS</company>

</address>

Note:-

CDATA Character Data, this data is parsed by the XML parser PCDATA Parsed Character Data,
plain text

# Delimiter

External DTD

DTD is stored in a separate file called “sample.dtd” Set stand alone attribute = “no”

sample.xml

<? xml version = “1.0” encoding = “utf-8” standalone=”yes”?>

< ! DOCTYPE address SYSTEM “address.dtd”>

<address>

<name>Bala</name>

<phone>1234</phone>

<company>TCS</company>

</address>

address.dtd

< ! DOCTYPE address


[

< ! ELEMENT address(name, phone, company)>


< ! ELEMENT name(#PCDATA)>
< ! ELEMENT phone(#PCDATA)>
< ! ELEMENT company(#PCDATA)>
]

>

Advantages of DTD

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

XML processor enforces structure, as defined in DTD Application is accessed easily in


document structure DTD gives hint to XML processor

Reduces size of document

4.12 XML SCHEMA DOM AND PRESENTING XML

XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe and validate the
structure and the content of XML data. XML schema defines the elements, attributes and data types.
Schema element supports Namespaces. It is similar to a database schema that describes the data in a
database.An XML Schema describes the structure of an XML document, just like a DTD.

Definition Types

You can define XML schema elements in following ways:

i) Simple Type - Simple type element is used only in the context of the text. Some of predefined
simple types are: xs:integer, xs:boolean, xs:string, xs:date. For example:
<xs:element name="phone_number" type="xs:int" />

ii) Complex Type - A complex type is a container for other element definitions. This allows you to
specify which child elements an element can contain and to provide some structure within your
XML documents. For example:
<xs:element name="Address"> <xs:complexType>

<xs:sequence>

<xs:element name="name" type="xs:string" />

<xs:element name="company" type="xs:string" />

<xs:element name="phone" type="xs:int" />

</xs:sequence>

</xs:complexType>

</xs:element>

iii) Global Types - With global type, you can define a single type in your document, which can be
used by all other references. For example, suppose you want to generalize the person and
company for different addresses of the company. In such case, you can define a general type as
below:
<xs:element name="AddressType"> <xs:complexType>

<xs:sequence>

<xs:element name="name" type="xs:string"

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

/>

<xs:element name="company" type="xs:string" />

</xs:sequence>

</xs:complexType>

</xs:element>

Now let us use this type in our example as below:

<xs:element name="Address1"> <xs:complexType>

<xs:sequence>

<xs:element name="address" type="AddressType" />

<xs:element name="phone1" type="xs:int" /> </xs:sequence>

</xs:complexType>

</xs:element>

<xs:element name="Address2"> <xs:complexType>

<xs:sequence>

<xs:element name="address" type="AddressType" />

<xs:element name="phone2" type="xs:int" /> </xs:sequence>

</xs:complexType>

</xs:element>

Instead of having to define the name and the company twice (once for Address1 and once for
Address2), we now have a single definition.

This makes maintenance simpler, i.e., if you decide to add "Postcode" elements to the address, you
need to add them at just one place.

Step 2: student.xml

<?xml version="1.0" encoding="UTF-8"?>

<contact xmlns:xs="http://www.w3.org/2001/XMLSchema-instance”
SchemaLocation=”student.xsd”>

<name>Bala></name>

<company>TCS</company>

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

<phone>1234</phone>

<contact>

Step 3: Open the Xml file in browser

o/p:-

<contact>

<name>Bala></name>

<company>TCS</company>

<phone>1234</phone>

<contact>

XML Schemas are More Powerful than DTD

XML Schemas are written in XML

XML Schemas are extensible to additions XML Schemas support data types

XML Schemas support namespaces

Purpose of XML Schema

With XML Schema, your XML files can carry a description of its own format.

With XML Schema, independent groups of people can agree on a standard for interchanging
data.

With XML Schema, you can verify data.

XML Schemas Support Data Types

It is easier to describe document content It is easier to define restrictions on


data

It is easier to validate the correctness of data

It is easier to convert data between different data types

XML Schemas use XML Syntax

You don't have to learn a new language

You can use your XML editor to edit your Schema files

You can use your XML parser to parse your Schema files You can manipulate your Schemas
with the XML DOM

You can transform your Schemas with XSLT

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

data types in XML Schema

o String
o Numeric
o Date
o Boolean

4.13 XML PARSERS AND VALIDATION

XML parser in detail with Java program code.

DOM API SAX API

Document Object
Model Simple API for XML

Tree based parsing Event based parsing

Entire XML is stored Part of Xml is stored


in in

memory memory

Requires less Requires more


memory memory

space space

Useful for small Uesful for large


apps apps

Traverse in any Top-down


direction traversing

DOM based parsing:-

dom.java

import java.io.*;

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

import javax.xml.parsers.*;

import org.w3c.dom.*;

import org.xml.sax.*;

public class dom

System.out.println(“Enter XML document name”);

BufferedReader input = new BufferedReader( new InuptStreamReader(System.in));

String filename = input.readLine(); File fp = new File(filename); if(fp.exists())

{ try

DocumentBuilderFactory dbf = new DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.new DocumentBuilder();

InputSource ips = new InputSource(filename);

Document doc = db.parse(ips);

System.out.println(filename + “is well formed”);

catch(Exception e)

System.out.println(“Not well formed”);

System.exit(1);

else

System.out.println(“File not Found”);

catch(IOException ioe)

ioe.printStackTrace();

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

User.xml

<?xml version="1.0"?> <userdata>

<user1>

<userno>001</userno>

<username>Bala</username>

<phonenumner>123456789</phonenumber>

<address>Chennai</Chennai>

</user1>

<user2>

<userno>002</userno>

<username>Suresh</username>

<phonenumner>987654321</phonenumber>

<address>madurai</Chennai>

</user2>

<user3>

<userno>003</userno>

<username>arul</username>

<phonenumner>1122334455</phonenumber>

<address>Vellore</Chennai>

</user3>

</userdata>

o/p:-

C:> javac dom.java C:> java dom Enter file name dom.xml

dom.xml is well formed

4.14 XSL AND XSLT TRANSFORMATION

i) <xsl:template>
ii) <xsl:value-of>
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

iii) <xsl:for-each>
iv) <xsl:if>
v) <xsl:sort>
vi) <xsl:choose>
<xsl:template>

to build template

match attribute is used with template element

match=”/” defines the whole document

Step-1 simple.xml

<?xml version=”1.0” encoding = UTF-8”?> <?xml-stylesheet type = “text/xsl”


href=”simple.xsl”?>

<student>

<details>

<name>bala</name>

<address>chennai</address>

<marks>62</marks>

</details>

<details>

<name>lokesh</name>

<address>vellore</address>

<marks>95</marks>

</details>

<details>

<name>Gopal</name>

<address>madurai</address>

<marks>88</marks>

</details>

</student>

Step-2: simple.xsl

<?xml version=”1.0” encoding = UTF-8”?> <xsl:stylesheet version=”1.0”


xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”>

<xsl:template match=”/”>
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

<html>

<body>

<table>

<tr><th>Name</th><th>address</th><th>mark</th></tr>

<tr><td>**</td><td>**</td><td>**</td></td>

</table>

</body>

</html>

</xsl:template>

</xsl:stylesheet>

<detail>

<xsl:value-of>

to extract value of XML elements

add that value to output stream of XSL transformation\

Step-1 simple.xml

<?xml version=”1.0” encoding = UTF-8”?> <?xml-stylesheet type = “text/xsl”


href=”simple.xsl”?>

<student>

<details>

<name>bala</name>

<address>chennai</address>

<marks>62</marks>

</details>

<details>

<name>lokesh</name>

<address>vellore</address>

<marks>95</marks>

</details>

<details>
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

<name>Gopal</name>

<address>madurai</address>

<marks>88</marks>

</details>

</student>

Step-2: simple.xsl

<?xml version=”1.0” encoding = UTF-8”?> <xsl:stylesheet version=”1.0”


xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”>

<xsl:template match=”/”>

<html>

<body>

<table>

<tr><th>Name</th><th>address</th><th>mark</th></tr> <tr><td><xsl:value-of
select=”student/details/name”/></td> <td><xsl:value-of
select=”student/details/address”/></td> <td><xsl:value-of
select=”student/details/mark”/></td>

</tr>

</table
>

</body>

</htm
l>

</xsl:templat
e>

</xsl:styleshee
t>

o/p:-

nam
e address marks

Bala Chennai 62

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

<xsl:for-each>

4.15 NEWS FEED (RSS AND ATOM)

On the World Wide Web, a web feed (or news feed) is a data format used for providing users
with frequently updated content.

Content distributors syndicate a web feed, thereby allowing users to subscribe to it.

Making a collection of web feeds accessible in one spot is known as aggregation, which is
performed by a news aggregator.

A web feed is also sometimes referred to as a syndicated feed.

A typical scenario of web-feed use might involve the following: a content provider publishes a
feed link on its site which end users can register with an aggregator program (also called a feed
reader or a news reader) running on their own machines; doing this is usually as simple as
dragging the link from the web browser to the aggregator.

When instructed, the aggregator asks all the servers in its feed list if they have new content; if
so, the aggregator either makes a note of the new content or downloads it.

One can schedule aggregators to check for new content periodically.

Advantages of Web feeds

Users do not disclose their email address when subscribing to a feed and so are not increasing
their exposure to threats associated with email: spam, viruses, phishing, and identity theft.

Users do not have to send an unsubscribe request to stop receiving news. They simply remove
the feed from their aggregator.

RSS

RSS stand for: It depends on what version of RSS you are using.

RSS Version 0.9 - Rich Site Summary RSS Version 1.0 - RDF Site Summary

RSS Versions 2.0, 2.0.1, and 0.9x - Really Simple

Syndication

RSS is a protocol that provides an open method of syndicating and aggregating web content.

RSS is a standard for publishing regular updates to web-based content.

RSS is a Syndication Standard based on a type of XML file that resides on an Internet server.

RSS is an XML application, which conforms to the W3C's RDF specification and is extensible via
XML.

You can also download RSS Feeds from other sites to display the updated news items on your
site reader to access your favorite RSS Feeds.

About 50 % of all RSS Feeds use RSS 0.91.

About 25 % use RSS 1.0.

The last 25 % is split between RSS 0.9x versions and RSS

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Working of RSS

A website willing to publish its content using RSS creates one RSS Feed and keeps it on a web
server.

RSS Feeds can be created manually or with software. A website visitor will subscribe to
read your RSS Feed. An RSS Feed will be read by an RSS Feed reader.

The RSS Feed Reader reads the RSS Feed file and displays it.

The RSS Reader displays only new items from the RSS Feed. The RSS Feed reader can be
customized to show you content

based on your own interest.

Who can Use RSS



New Homes - Realtors can provide updated Feeds of new home listings on the market.

Job Openings - Placement firms and newspapers can provide a classified Feed of job vacancies.


Auction Items - Auction vendors can provide Feeds containing items that have been recently
added to eBay, etc

Press Distribution - Listing of new releases.

Schools - Schools can relay homework assignments and quickly announce school cancellations.

News & Announcements - Headlines, notices, and any list of announcements.

Entertainment - Listings of the latest TV programs or movies
at local theatres.

Advantages for Subscribers

RSS subscribers are the people who subscribe to read a published Feed

All news at one place: You can subscribe to multiple news groups and then you can customize your
reader to have all the news on a single page. It will save you a lot of time

News when you want it: Rather than waiting for an e-mail, you go to your RSS reader when you
want to read a news. Furthermore, RSS Feeds display more quickly than information on web-
sites, and you can read them offline if you prefer.

Get the news you want: RSS Feed comes in the form of headlines and a brief description so that
you can easily scan the headlines and click only those stories that interest you.

Freedom from e-mail overload: You are not going to get any email for any news or blog update.
You just go to your reader and you will find updated news or blog automatically whenever there
is a change on the RSS server.

Easy republishing: You may be both a subscriber and a publisher. For example, you may have a
web-site that collects
news from various other sites and then republishes it. RSS allows you to easily capture that news
and display it on your site.

Advantages for Publishers

RSS publishers are the people who publish their content through RSS feed.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming


Easier publishing: RSS is really simple publishing. You don't have to maintain a database of
subscribers to send your information to them, instead they will access your Feed using a reader
and will get updated content automatically.

A simpler writing process: If you have a new content on your web site, you only need to write
an RSS Feed in the form of titles and short descriptions, and link back to your site.

An improved relationship with your subscribers: Because people subscribe from their side, they
don't feel as if you are pushing your content on them.

The assurance of reaching your subscribers: RSS is not subject to spam filters, your subscribers
get the Feeds, which they subscribe to and nothing more.

Links back to your site: RSS Feeds always include links back to a website. It directs a lot of traffic
towards your website.

Relevance and timeliness: Your subscribers always have the latest information from your site.

<?xml version="1.0" ?> <rss version="2.0"> <channel>

<title>Ajax and XUL</title> <link>http://www.xul.fr/en/</link>

<description>XML graphical interface etc...</description> <image>

<url>http://www.xul.fr/xul-icon.gif</url> <link>http://www.xul.fr/en/index.php</link>

</image>

<item>

<title>News of today</title> <link>http://www.xul.fr/en-xml-rss.html</link> <description>All


you need to know about RSS</description>

</item>

<item>

<title>News of tomorrows</title> <link>http://www.xul.fr/en-xml-rdf.html</link>


<description>And now, all about RDF</description></item>

</channel>

</rss>

How browsers know there is an RSS feed on a website

You have created an RSS feed and it is now stored at root of your website.

You must let browsers knowing the existence of this file and its location, when they enter and
display the home page (or any other page if you want).

Firefox will display the feed icon into the URL field, Internet Explorer on the bar of commands.

To activate them, insert the following line into the source code of the page, anywhere inside the
<head> </head> section:

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

<link rel="alternate" type="application/rss+xml" href="http://www.xul.fr/rss.xml"


title="Your title">

Replace the URL by your domain name with the path and filename of your RSS feed.

And if the file is in the atom format, replace rss+xml by atom+xml.

ATOM feed

Atom is the name of an XML-based Web content and metadata syndication format, and an
application-level protocol for publishing and editing Web resources belonging to periodically
updated websites.

Atom is a relatively recent spec and is much more robust and feature-rich than RSS.

For instance, where RSS requires descriptive fields such as title and link only in item breakdowns,
Atom requires these things for both items and the full Feed.

All Atom Feeds must be well-formed XML documents, and are identified with the
application/atom+xml media type.

Structure of an Atom 1.0 Feed

<?xml version="1.0"?>

<feed xmlns="http://www.w3.org/2005/Atom"> <title>...</title>

<link>...</link> <updated>...</updated>

<author> <name>...</name>

</author>

<id>...</id>

<entry> <title>...</title> <link>...</link> <id>...</id>

<updated>...</updated> <summary>...</summary>

</entry>

</feed>

Example:-

<?xml version="1.0" encoding="utf-8"?> <feed


xmlns="http://www.w3.org/2005/Atom">

<title>Example Feed</title>

<subtitle>Insert witty or insightful remark here</subtitle> <link


href="http://example.org/"/> <updated>2003-12-13T18:30:02Z</updated>

<author>
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

<name>Mohtashim</name>

<email>mohtashim@example.com</email>

</author>

<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>

<entry>

<title>Tutorial on Atom</title>

<link href="http://example.org/2003/12/13/atom03"/>

<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-
13T18:30:02Z</updated> <summary>Some text.</summary>

</entry>

</feed>

RSS ATOM

Contains either plain Contains html, xml,


text or dhtml,

documents, audio,
escaped sequence as video, etc

payload as payload

Shows timestamp of Shows timestamp of


data data

when feed was last when it was last


created updated

or updated

Uses blogger and It has only one


meta standard

weblog protocols protocols

Loose approach on Strict approach on


data data

More complicated
process Easier process

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Not a standard
feature Standard feature

More robust,
Less robust, scalable, scalable,

efficient efficient

UNIT V
INTRODUCTION TO AJAX AND WEB SERVICES

5.1.AJAX
o AJAX is an acronym for asynchronous JavaScript and XML

o It is a set of web development techniques using many web technologies on the client-side
to create asynchronous Web applications.

o With Ajax, web applications can send data to and retrieve from a server asynchronously
(in the background) without interfering with the display and behavior of the existing page.

o Ajax is not a technology, but a group of technologies.

o HTML and CSS can be used in combination to mark up and style information.

o The DOM is accessed with JavaScript to dynamically display and allow the user to
interact with the information presented.

o JavaScript and the XMLHttpRequest object provide a method for exchanging data
asynchronously between browser and server to avoid full page reloads.

o Browser-based presentation using HTML and Cascading Style Sheets (CSS).

o Data is stored in XML format and fetched from the server.

o Behind-the-scenes data fetches using XMLHttpRequest objects in the browser.

o JavaScript to make everything happen.

5.2 AJAX CLIENT SERVER ARCHITECTURE

 AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating
better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java
Script.
 Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and
JavaScript for dynamic content display.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 Conventional web applications transmit information to and from the server using synchronous
requests. It means you fill out a form, hit submit, and get directed to a new page with new
information from the server.
 With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the
results, and update the current screen. In the purest sense, the user would never know that
anything was even transmitted to the server.
 XML is commonly used as the format for receiving server data, although any format, including
plain text, can be used.
 AJAX is a web browser technology independent of web server software.
 A user can continue to use the application while the client program requests information from the
server in the background.
 Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient
event trigger.
 Data-driven as opposed to page-driven.
Rich Internet Application Technology
AJAX is the most viable Rich Internet Application (RIA) technology so far. It is getting tremendous
industry momentum and several tool kit and frameworks are emerging. But at the same time, AJAX has
browser incompatibility and it is supported by JavaScript, which is hard to maintain and debug.
AJAX is Based on Open Standards
AJAX is based on the following open standards:
 Browser-based presentation using HTML and Cascading Style Sheets (CSS).
 Data is stored in XML format and fetched from the server.
 Behind-the-scenes data fetches using XMLHttpRequest objects in the browser.
 JavaScript to make everything happen.

5.3 XML HTTP REQUEST OBJECT

XMLHttpRequest object with example.



The XMLHttpRequest object can be used to request data from a web server.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming


The XMLHttpRequest object is a developers dream, because you can:
Update a web page without reloading the page
Request data from a server - after the page has loaded Receive data from a server - after the page has
loaded Send data to a server - in the background

The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet
Explorer 5.5 was released in July 2000, but was not fully discovered until AJAX and Web
2.0 in 2005 became popular.

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript, and
other web browser scripting languages to transfer and manipulate XML data to and from a
webserver using HTTP, establishing an independent connection channel between a
webpage's Client-Side and Server-Side.

The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides
XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text
XMLHttpRequest Methods

abort() : Cancels the current request.

getAllResponseHeaders() : Returns the complete set of HTTP headers as a string.

getResponseHeader( headerName ) : Returns the value of the specified HTTP header.

open( method, URL )

XMLHttpRequest Properties

onreadystatechange : An event handler for an event that fires at every state change.

readyState : The readyState property defines the current state of the XMLHttpRequest object.

State Description

The request is not initialized.

The request has been set up.

The request has been sent.

The request is in process.

The request is completed.

readyState = 0 After you have created the XMLHttpRequest object, but before you have
called the open() method

readyState = 1 After you have called the open() method, but before you have called send().

readyState = 2 After you have called send().

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

readyState = 3 After the browser has established a communication with the server, but
before the server has completed the response.

readyState = 4 After the request has been completed, and the response data has been
completely received from the server.

responseText :Returns the response as a string. responseXML :Returns the


response as XML.

status : Returns the status as a number (e.g., 404 for "Not Found" and 200 for "OK").

statusText :Returns the status as a string (e.g., "Not Found" or "OK").


Example:-

<!DOCTYPE html> <html>


<body>
<h2>Using the XMLHttpRequest Object</h2> <div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button> </div>
<script>
function loadXMLDoc()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true); xhttp.send();
}
</script>
</body>
</html>

The onreadystatechange property specifies a function to be executed every time the status of the
XMLHttpRequest object changes.

When readyState property is 4 and the status property is 200, the response is ready.

responseText property returns the server response as a text string.

The text string can be used to update a web page

5.4 CALL BACK METHODS

jQuery Callback Functions


JavaScript statements are executed line by line. However, with effects, the next line of code can be run
even though the effect is not finished. This can create errors.
To prevent this, you can create a callback function.
A callback function is executed after the current effect is finished.
Typical syntax: $(selector).hide(speed,callback);
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Examples
The example below has a callback parameter that is a function that will be executed after the hide effect
is completed:
Example with Callback
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
The example below has no callback parameter, and the alert box will be displayed before the hide effect
is completed:
Example without Callback
$("button").click(function(){
$("p").hide(1000);

Type: PlainObject
A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for
any option with $.ajaxSetup().
 accepts (default: depends on DataType)
Type: PlainObject
A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the
Accept request header. This header tells the server what kind of response it will accept in return.
For example, the following defines a custom type mycustomtype to be sent with the request:
$.ajax({
accepts: {
mycustomtype: 'application/x-some-custom-type'
},

// Instructions for how to deserialize a `mycustomtype`


converters: {
'text mycustomtype': function(result) {
// Do Stuff
return newresult;
}
},

// Expect a `mycustomtype` back from server


dataType: 'mycustomtype'
});
5.5 WEB SERVICES

 A web service is any piece of software that makes itself available over the internet and uses a
standardized XML messaging system. XML is used to encode all communications to a web
service. For example, a client invokes a web service by sending an XML message, then waits for
a corresponding XML response. As all communication is in XML, web services are not tied to
any one operating system or programming language--Java can talk with Perl; Windows
applications can talk with Unix applications.
 Web services are self-contained, modular, distributed, dynamic applications that can be described,
published, located, or invoked over the network to create products, processes, and supply chains.
These applications can be local, distributed, or web-based. Web services are built on top of open
standards such as TCP/IP, HTTP, Java, HTML, and XML.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 Web services are XML-based information exchange systems that use the Internet for direct
application-to-application interaction. These systems can include programs, objects, messages, or
documents.
 A web service is a collection of open protocols and standards used for exchanging data between
applications or systems. Software applications written in various programming languages and
running on various platforms can use web services to exchange data over computer networks like
the Internet in a manner similar to inter-process communication on a single computer. This
interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the
use of open standards.

5.6 INTRODUCTION
To summarize, a complete web service is, therefore, any service that:
 Is available over the Internet or private (intranet) networks
 Uses a standardized XML messaging system
 Is not tied to any one operating system or programming language
 Is self-describing via a common XML grammar
 Is discoverable via a simple find mechanism
Components of Web Services
The basic web services platform is XML + HTTP. All the standard web services work using the
following components
 SOAP (Simple Object Access Protocol)
 UDDI (Universal Description, Discovery and Integration)
 WSDL (Web Services Description Language)
All these components have been discussed in the Web Services Architecture chapter.
How Does a Web Service Work?
A web service enables communication among various applications by using open standards such as
HTML, XML, WSDL, and SOAP. A web service takes the help of:
 XML to tag the data
 SOAP to transfer a message
 WSDL to describe the availability of service.
You can build a Java-based web service on Solaris that is accessible from your Visual Basic program that
runs on Windows.
You can also use C# to build new web services on Windows that can be invoked from your web
application that is based on JavaServer Pages (JSP) and runs on Linux.
Example
Consider a simple account-management and order processing system. The accounting personnel use a
client application built with Visual Basic or JSP to create new accounts and enter new customer orders.
The processing logic for this system is written in Java and resides on a Solaris machine, which also
interacts with a database to store information.
The steps to perform this operation are as follows:
 The client program bundles the account registration information into a SOAP message.
 This SOAP message is sent to the web service as the body of an HTTP POST request.
 The web service unpacks the SOAP request and converts it into a command that the application
can understand.
 The application processes the information as required and responds with a new unique account
number for that customer.
 Next, the web service packages the response into another SOAP message, which it sends back to
the client program in response to its HTTP request.
 The client program unpacks the SOAP message to obtain the results of the account registration
process.

5.7 JAVA WEB SERVICES BASICS


M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Java Web Services API


There are two main API's defined by Java for developing web service applications since JavaEE 6.
1) JAX-WS: for SOAP web services. The are two ways to write JAX-WS application code: by RPC style
and Document style.
2) JAX-RS: for RESTful web services. There are mainly 2 implementation currently in use for creating
JAX-RS application: Jersey and RESTeasy.

5.7.1 CONCEPT OF RPC


Definition

Remote Procedure Call (RPC)

Remote Procedure Call (RPC) is a protocol that one program can use to request a service from a program
located in another computer on a network without having to understand the network's details.
A procedure call is also sometimes known as a function call or a subroutine call.

RPC uses the client-server model. The requesting program is a client and the service providing program
is the server. Like a regular or local procedure call, an RPC is a synchronous operation requiring the
requesting program to be suspended until the results of the remote procedure are returned. However, the
use of lightweight processes or threads that share the same address space allows multiple RPCs to be
performed concurrently.
RPC message procedure
When program statements that use RPC framework are compiled into an executable program, a stub is
included in the compiled code that acts as the representative of the remote procedure code. When the
program is run and the procedure call is issued, the stub receives the request and forwards it to a
client runtime program in the local computer.
The client runtime program has the knowledge of how to address the remote computer and server
application and sends the message across the network that requests the remote procedure. Similarly, the
server includes a runtime program and stub that interface with the remote procedure itself. Response-
request protocols are returned the same way.
RPC models and alternative methods for client-server communication
There are several RPC models and distributed computing implementations. A popular model and
implementation is the Open Software Foundation's Distributed Computing Environment (DCE). The
Institute of Electrical and Electronics Engineers defines RPC in its ISO Remote Procedure Call
Specification, ISO/IEC CD 11578 N6561, ISO/IEC, November 1991.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

5.7.2 JAX-RPC CONCEPT

AX-RPC: Concepts
Service Definition
A JAX-RPC service endpoint is defined and deployed using the Java platform. A JAX-RPC service
endpoint is capable of use by service clients deployed on any platform. A JAX-RPC service endpoint
definition makes no assumption that the service be only used by a Java-based service client. The converse
is also true. A Java service client is capable of invoking an XML-based RPC service endpoint deployed
on any non-Java platform.
We illustrate an example stock quote service endpoint that defines and implements the following Java
interface.
Service Definition Interface: StockQuoteProvider
package com.example;
public interface StockQuoteProvider extends java.rmi.Remote {
public float getLastTradePrice (String tickerSymbol) throws java.rmi.RemoteException;
// .. Other remote method
}
In this example, the stock quote service endpoint definition starts with a Java interface as shown in the
above code example. This interface is called a service definition interface. Note that the service developer
could have started from the stock quote service description in a WSDL document and mapped it to the
corresponding Java service definition interface. JAX-RPC specifies the standard mapping of the WSDL
definitions to Java representation and mapping of the XML data types to the Java types. JAX-RPC also
specifies the standard mapping from the Java definitions to the XML and WSDL definitions.
A JAX-RPC service endpoint can be realized (or implemented) using the Java 2 Platform, Enterprise
Edition (J2EE) component model. This example uses a stateless session bean for realizing the stock quote
service. A servlet based endpoint is another possible implementation of a JAX-RPC service endpoint
JAX-RPC specifies the service endpoint model for a JAX-RPC service developed and deployed on a
servlet container based JAX-RPC implementation. The JAX-RPC also specifies the Java 2 Platform,
Standard Edition (J2SE) based service endpoint model. The JAX-RPC specification does not specify the
service endpoint model for a JAX-RPC service developed using the Enterprise JavaBeans (EJB)
component model. The EJB endpoint model for JAX-RPC services would be specified in the JSR-109
and EJB 2.1 specifications.
Service Deployment
Once a JAX-RPC service endpoint has been defined and implemented, the JAX-RPC deployer deploys
the service on a server-side container based JAX-RPC runtime system. The deployment step depends on
the type of component that has been used to realize a JAX-RPC service endpoint.
The example stock quote service endpoint is realized as a stateless session bean and is deployed on an
EJB container. The deployment step includes the generation of container specific artifacts based on the
service definition interface. A container provided deployment tool provides support for the deployment
of the JAX-RPC service endpoints.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

During the deployment of a JAX-RPC service endpoint, the deployment tool configures one or more
protocol bindings for this service endpoint. A binding ties an abstract service endpoint definition to a
specific protocol and transport. An example of a binding is SOAP 1.1 protocol binding over HTTP.
Next, the deployment tool creates one or more service endpoints for this JAX-RPC service. Each service
endpoint is bound to a specific protocol and transport, and has an assigned endpoint address based on this
protocol binding.
Service Description
The deployment tool exports the stock quote service as a WSDL document. The WSDL description of the
stock quote service enables service clients (on any platform) to access this service and its endpoints.
A Java-to-WSDL mapping tool (typically part of a container provided deployment tool) maps the
example StockQuoteProvider service definition interface to the following service description in a WSDL
document:
WSDL description of the Stock Quote Service
<?xml version="1.0"?>
<definitions name="StockQuote" targetNamespace="http://example.com/stockquote.wsdl"

<xmlns:tns="http://example.com/stockquote.wsdl"
<xmlns:xsd="http://www.w3.org/2001/XMLSchema"
<xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
<xmlns="http://schemas.xmlsoap.org/wsdl/">

<message name="GetLastTradePriceInput">
<part name="tickerSymbol" type="xsd:string"/>
</message>
<message name="GetLastTradePriceOutput">
<part name="return" type="xsd:float"/>
</message>

<portType name="StockQuoteProvider">
<operation name="GetLastTradePrice">
<input message="tns:GetLastTradePriceInput"/>
<output message="tns:GetLastTradePriceOutput"/>
</operation>
</portType>

<binding name="StockServiceSoapBinding"
type="tns:StockQuoteProvider">
<soap:binding style="rpc"
transport="http:/schemas.xmlsoap.org/soap/http">
<operation name="GetLastTradePrice">
<soap:operation
soapAction="http://example.com/GetLastTradePrice"/>
<input>soap:body use="encoded"
namespace="http://example.com/stockquote"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding">
</input>
<output><soap:body use="encoded"
namespace="http://example.com/stockquote"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding">
</output>
</operation>
</binding>
<service name="StockQuoteService">
<port name="StockQuoteProviderPort"
binding="tns:StockServiceSoapBinding">
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

<soap:address location="http://example.com/StockQuoteService">
</port>
</service>
</definitions>

5.8 CREATING, PUBLISHING WEB SERVICES

Publishing a Web service

The Web service, also known as the business service, describes a Web service's endpoint and where its
WSDL file resides. The WSDL file lists the operations that service provides.
Prerequisites:
1. Register with a registry.
2. Launch the Web Services Explorer.
3. Add the registry to the Web Services Explorer.
4. Create a Web service.
5. Deploy the Web service.
6. Publish a Business Entity.
You can publish a business service using two different publication formats: simple and advanced.
Publish a business service using the simple option
To publish a Web service using the simple option:
1. In the Web Services Explorer, select UDDI Main and select the registry to which you want to
publish the business entity.
2. In the Actions pane toolbar, click the Publish icon .
3. Select Service and select the Simple radio button.
4. Enter the publish URL, your user ID, password, WSDL URL, service name, and service
description in the respective fields.
5. Click Go to publish your business entity.

5.8.1 INSTALLATION OF JWSDP

System Requirements
The Java WSDP software is supported on Microsoft Windows 2000, Microsoft Windows XP, and
Microsoft Windows 2003 Server Professional Editions. In addition, the Java WSDP software can also be
installed, but is unsupported, on Windows 95, 98, ME, and NT 4.0.
To install the Java WSDP software, you need the J2SE 5.0 JDK software already installed on your
computer. Download J2SE 5.0 JDK from here.
You should have at least 140 megabytes of free disk space and 140 megabytes of free temporary disk
space before attempting to install the Java WSDP software.
Installation Instructions
Before you download and install Java WSDP, download and install a Web container to use. Get the Web
containers (Sun Java System Application Server 8.1 Platform Edition 2005Q2 UR2 or Tomcat 5 for Java
WSDP) here. You can use Glassfish as your Web container if you want to install JAX-WSA and an
experimental version of JAX-WS. You can also use later versions of Tomcat (versions 5.x or 6.x) as your
Web container. However, note that these containers have only been tested minimally.
Run the self-installing executable to unpack and install the Java WSDP software bundle. If you have any
difficulties, see the Troubleshooting section at the end of this document.
Note: After the Java WSDP software has been installed, you may be asked to reboot your system. To
continue using these instructions after rebooting, you should print them now.
1. Check the download file size.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

2. If you saved the self-installing executable to disk without running it from the download
page at the Java Software web site, check to see that you have the complete file:
jwsdp-2_0-windows-i586.exe 23,789,469 bytes
3. Uninstall previous versions of the Java WSDP.
4. If you have installed a previous version of the Java WSDP, uninstall it (Start --> Programs
--> Java(TM) Web Services Developer Pack 1. x --> Uninstall).
5. Run the Java WSDP installer.
6. The file jwsdp-2_0-windows-i586.exe is the Java WSDP installer. If you downloaded it
instead of running it directly from the website, double-click on the installer's icon. Then
follow the instructions that the installer provides.
You can also install the Java WSDP from the command line, by using the console option,
as shown:
C:\>
jwsdp-2_0-windows-i586.exe -console

Select either no Web container or the Web container into which you will install or have
installed and integrate the Java WSDP software. Follow the instructions that are displayed.
If did not install a Web container, you can get one here or select the "no Web Container"
option. Then, after you obtain and install a supported container, run the jwsdpon container
integration script for that container to integrate your Java WSDP installation into your
Web container installation. See the Integration Notes for more information.
The Java WSDP installer places the Java WSDP technologies under < jwsdp.home> and
the integration scripts copy the appropriate JAR files to the container directories.
In addition, there will be an entry for Java TM Web Services Developer Pack 2.0 in the
Start --> Programs menu.
7. Delete the downloaded file. (Optional)
8. To recover disk space, delete the file (or files) you originally downloaded.
9. Update the PATH variable.
10. You can run the Java WSDP without setting the PATH variable, or you can optionally set
it as a convenience.
Should I set the PATH variable?
Set the PATH variable if you want to be able to conveniently run the Java WSDP
executables ( startup.bat, shutdown.bat, ant.bat, etc.) from any directory without having to
type the full path of the command. If you don't set the PATH variable, you need to specify
the full path to the executable every time you run it, such as:
C:>
c:\jwsdp-2.0\jwsdp-shared\bin\startup.bat

It is useful to set the PATH permanently, so it persists after rebooting.


How do I set the PATH permanently?
To set the PATH permanently, add the full path of the bin directory in the Java WSDP
installation directory to the PATH variable. Typically, with the Sun Java System
Application Server Platform Edition 8.1 2005Q2 UR1, this full path looks something like
C:\Sun\AppServer\jwsdp-2.0\jwsdp-shared\\bin. To set the PATH permanently:
a. Choose Start, Settings, Control Panel, and double-click System. Select the
Advanced tab and then Environment Variables. Look for "Path" in the User
Variables and System Variables. If you're not sure where to add the path, add it to
the right end of the "Path" in the User Variables. A typical value for PATH is:
b. C:\Sun\AppServer\jwsdp-2.0\jwsdp-shared\bin
c. Capitalization doesn't matter. Click "Set", "OK" or "Apply".
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

The PATH can be a series of directories separated by semi-colons (;). Microsoft


Windows looks for programs in the PATH directories in order, from left to right.
You should only have one bin directory for a Java WSDP installation in the path at
a time (those following the first are ignored), so if one is already present, you can
update it.

d. The new path takes effect in each new Command Prompt window you open after
setting the PATH variable.
11. Start using the Java WSDP.
12. Your computer system should now be ready to use the Java WSDP.
To verify that the installation was successful, start (or restart) your Web container. If you
are using Tomcat 5 for Java WSDP, browse to http://localhost:8080/index.html; if you are
using the Application Server, browse to http://localhost:8080/JWSDP.html and click on
the links for the deployed Java WSDP applications, such as the saaj-simple application.
13. Uninstall the Java WSDP.
14. If you should ever want to uninstall the Java WSDP, use the "Add/Remove Programs"
utility in the Microsoft Windows Control Panel.
You can also uninstall the Java WSDP in console mode, by executing the uninstaller.exe
file in the < JWSDP_HOME>/_uninst directory:

uninstaller.exe -console

5.8.2 WRITING WEB SERVICE

1. Open Visual Studio .NET.


2. On the File menu, click New and then click Project. Under Project types click Visual C# Projects,
then click ASP.NET Web Service under Templates. Type MathService in the Location text box to
change the default name (WebService1) to MathService.
3. Change the name of the default Web service that is created from Service1.asmx to
MathService.asmx.
4. Click Click here to switch to code view in the designer environment to switch to code view.
5. Define methods that encapsulate the functionality of your service. Each method that will be
exposed from the service must be flagged with a WebMethod attribute in front of it. Without this
attribute, the method will not be exposed from the service.
Add the following method to the MathServices class that you just created:
[WebMethod]
public int Add(int a, int b)
{
return(a + b);
}

[WebMethod]
public System.Single Subtract(System.Single A, System.Single B)
{
return (A - B);
}

[WebMethod]
public System.Single Multiply(System.Single A, System.Single B)
{
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

return A * B;
}

[WebMethod]
public System.Single Divide(System.Single A, System.Single B)
{
if(B == 0)
return -1;
return Convert.ToSingle(A / B);
}
6. Click Build on the Build menu to build the Web service.
7. Browse to the MathService.asmx Web service page to test the Web service. If you set the local
computer to host the page, the URL is http://localhost/MathService/MathService.asmx.

The ASP.NET runtime returns a Web Service Help Page that describes the Web service. This
page also enables you to test different Web service methods.

5.8.3 WRITING WEB SERVICE CLIENT


Create a Web service Client
1. Select the AreaServiceSOAP.wsdl file in AreaProject\WebContent\wsdl created in Creating top
down Web service .
Do not select the AreaService.wsdl file in AreaProject\WebContent.
2. Open File -> New -> Other... -> Web Services -> Web Service Client.
3. Select Test the Web service and Overwrite files without warning .

4. Click Next.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

5. Type in AreaProjectClient as the name of the Client project.


If you want to choose a server different from the one defaulted by the wizard, click the Edit
button to: select a server .

6. Click Finish .
.
7. It will take about one minute for the wizard to assemble the Web service client Web projects,
start Apache Tomcat, and deploy the projects to Tomcat. Once finished, the generated Sample
JSP Web application will appear in the browser view.
8. Under Methods , click on calculateRectArea .

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

9. Under Inputs , enter 2.0 and 5.0 into the height and width entry field.
10. Click on Invoke . In the Result view, you should get a response of 10.0 .

5.9 TESTING AND DESCRIBING A WEB SERVICES (WSDL)

 WSDL stands for Web Services Description Language WSDL is used to describe
web services
 WSDL is written in XML
 WSDL is a W3C recommendation from 26. June 2007 It is the standard format for
describing a web service. WSDL was developed jointly by Microsoft and IBM.

Features of WSDL

 WSDL is an XML-based protocol for information exchange in decentralized and


distributed environments.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

 WSDL definitions describe how to access a web service and what operations it will
perform.
 WSDL is a language for describing how to interface with XML-based services.
 WSDL is an integral part of Universal Description, Discovery, and Integration (UDDI), an
XML-based worldwide business registry.
 WSDL is the language that UDDI uses.
 WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.

WSDL Elements

Types– a container for data type definitions using some type system (such as XSD).

Message– an abstract, typed definition of data being communicated. Operation– an abstract


description of an action supported by service.

Port Type–an abstract set of operations supported by one or more endpoints.

Binding– a concrete protocol and data format specification for a particular port type.

Port– a single endpoint defined as a combination of a binding and a network address.

Service– a collection of related endpoints.


The WSDL Document Structure
<definitions>
<types>
definition of types........
</types>
<message>
definition of a message....
</message>
<portType>
<operation>
definition of a operation.......
</operation>
</portType>
<binding>
definition of a binding....
</binding>
<service>
definition of a service....
</service>
</definitions>

Contents of HelloService.wsdl file:

<definitions name="HelloService"
targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<message name="SayHelloRequest">
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

<part name="firstName" type="xsd:string"/> </message>


<message name="SayHelloResponse"> <part name="greeting" type="xsd:string"/>
</message>
<portType name="Hello_PortType"> <operation name="sayHello">

<input message="tns:SayHelloRequest"/> <output


message="tns:SayHelloResponse"/>
</operation>
</portType>
<binding name="Hello_Binding" type="tns:Hello_PortType"> <soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="sayHello">
<soap:operation soapAction="sayHello"/> <input>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice" use="encoded"/>
</input> <output>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice" use="encoded"/>
</output>
</operation>
</binding>
<service name="Hello_Service">
<documentation>WSDL File for HelloService</documentation> <port
binding="tns:Hello_Binding" name="Hello_Port">
<soap:address location="http://www.examples.com/SayHello/" />
</port>
</service>
</definitions>

Example Analysis
Definitions : HelloService
Type : Using built-in data types and they are defined in XMLSchema.

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

Message :
o sayHelloRequest : firstName parameter
o sayHelloresponse: greeting return value
Port Type : sayHello operation that consists of a request and a response service.
Binding : Direction to use the SOAP HTTP transport protocol. Service : Service available at
http://www.examples.com/SayHello/
Port : Associates the binding with the URI http://www.examples.com/SayHello/ where the running
service can be accessed.

5.10 CONSUMING A WEB SERVICE

Create the simple ASP.Net Web Application as:


1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
2. "File" - "New" - "Project..." then in the New Project window "C#" - "Empty Project" (to avoid
adding a master page).
3. Give the project a name, such as "Consuming web service" or another as you wish and specify the
location.
4. Then right-click on Solution Explorer and select "Add New Item" - "Default.aspx" page.
5. Then drag three Text Boxes, one Button, and one Label onto the "Default.aspx" page.
Then the <body> section of the Default.aspx page looks as in the following:

In the preceding source code, you have seen that I have taken three text boxes to get input from users
because we know that our Web Service method created as in my article Introduction to Web Service with
Example in ASP.Net takes the three input values day, month and year so I have taken the three text boxes
and button click event. We will call the Web Service method and the output will be displayed on the label
control so I have also taken one button and label control.

5.11 DATABASE DRIVEN WEB SERVICE FROM AN APPLICATION

Our prior examples accessed web services from desktop applications created in Netbeans. However, we
can just as easily use them in web applications created with Netbeans. In fact, because web-based
businesses are becoming increasingly prevalent, it is common for web applications to consume web
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

services. In this section, we present an airline reservation web service that receives information regarding
the type of seat a customer wishes to reserve and makes a reservation if such a seat is available. Later in
the section, we present a web appli-cation that allows a customer to specify a reservation request, then
uses the airline reserva-tion web service to attempt to execute the request.

1. Configuring Java DB in Netbeans and Creating the Reservation Database

In this example, our web service uses a Reservation database containing a single table named Seats to
locate a seat matching a client‘s request. To build the Reservation data-base, review the steps presented
in Section 27.2.1 for building the AddressBook database. This chapters examples directory contains a
SQL script to build the Seats table and pop-ulate it with sample data.

Creating the Reservation Web Service

You can now create a web service that uses the Reservation database (Fig). The airline reservation web
service has a single web method—reserve (lines 26–78)—which searches the Seats table to locate a seat
matching a user‘s request. The method takes two arguments—a String representing the desired seat type
(i.e., "Window", "Middle" or "Aisle") and a String representing the desired class type (i.e., "Economy" or
"First"). If it finds an appropriate seat, method reserve updates the database to make the reservation and
returns true; otherwise, no reservation is made, and the method returns false. Note that the statements at
lines 34–39 and lines 44–48 that query and update the database use objects of JDBC types ResultSet and
PreparedStatement.
Our database contains four columns—the seat number (i.e., 1–10), the seat type (i.e., Window, Middle or
Aisle), the class type (i.e., Economy or First) and a column containing either 1 (true) or 0 (false) to
indicate whether the seat is taken. Lines 34–39 retrieve the seat numbers of any available seats matching
the requested seat and class type. This state-ment fills the resultSet with the results of the query

SELECT "NUMBER" FROM "SEATS"


WHERE ("TAKEN" = 0) AND ("TYPE" = type) AND ("CLASS" = class)

The parameters type and class in the query are replaced with values of method reserve‘s seatType and
classType parameters. When you use the Netbeans tools to create a data-base table and its columns, the
Netbeans tools automatically place the table and column names in double quotes. For this reason, you
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

must place the table and column names in double quotes in the SQL statements that interact with the
Reservation database.

If resultSet is not empty (i.e., at least one seat is available that matches the selected criteria), the
condition in line 42 is true and the web service reserves the first matching seat number. Recall that
ResultSet method next returns true if a nonempty row exists, and positions the cursor on that row. We
obtain the seat number (line 44) by accessing resultSet‘s first column (i.e., resultSet.getInt(1)—the first
column in the row).
Then lines 45–48 configure a PreparedStatement and execute the SQL:

UPDATE "SEATS"

SET "TAKEN" = 1
WHERE ("NUMBER" = number)

which marks the seat as taken in the database. The parameter number is replaced with the value of
seat. Method reserve returns true (line 49) to indicate that the reservation was successful. If there are
no matching seats, or if an exception occurred, method reserve re-turns false (lines 52, 57, 62 and 75)
to indicate that no seats matched the user‘s request.

// Fig: Reservation.java
// Airline reservation web service.

package com.deitel.iw3htp4.ch28.reservation;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
@WebService( name = "Reservation", serviceName = "ReservationService" )
public class Reservation
{
private static final String DATABASE_URL = "jdbc:derby://localhost:1527/Reservation";
private static final String USERNAME = "iw3htp4";
private static final String PASSWORD = "iw3htp4";
private Connection connection;
private PreparedStatement lookupSeat;
private PreparedStatement reserveSeat;
// a WebMethod that can reserve a seat
@WebMethod( operationName = "reserve" )
public boolean reserve( @WebParam( name = "seatType" ) String seatType,
@WebParam( name = "classType" ) String classType )
{
try
{
connection = DriverManager.getConnection(
DATABASE_URL, USERNAME, PASSWORD );
lookupSeat = connection.prepareStatement(
"SELECT \"NUMBER\" FROM \"SEATS\" WHERE (\"TAKEN\" = 0) " + "AND (\"LOCATION\" = ?)
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

AND (\"CLASS\" = ?)" );


lookupSeat.setString( 1, seatType );
lookupSeat.setString( 2, classType );
ResultSet resultSet = lookupSeat.executeQuery();
// if requested seat is available, reserve it

if ( resultSet.next() )
{

int seat = resultSet.getInt( 1 );

reserveSeat = connection.prepareStatement(
"UPDATE \"SEATS\" SET \"TAKEN\"=1 WHERE \"NUMBER\"=?" );
reserveSeat.setInt( 1, seat );
reserveSeat.executeUpdate();
return true;

} // end if

return false;
} // end try
catch ( SQLException e ) {
e.printStackTrace();
return false;
} // end catch

catch ( Exception e ) {
e.printStackTrace();

return false;
} // end catch
finally
{
try {

lookupSeat.close();
reserveSeat.close();
connection.close();
} // end try
catch ( Exception e )
{
\e.printStackTrace();
return false;
} // end catch
} // end finally
} // end WebMethod reserve
} // end class Reservation

5.12 SOAP

SOAP (originally Simple Object Access Protocol) is a protocol specification for exchanging structured
information in the implementation of web services in computer networks. Its purpose is to induce
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

extensibility, neutrality and independence. It uses XML Information Set for its message format, and relies
on application layer protocols, most often Hypertext Transfer Protocol (HTTP) or Simple Mail Transfer
Protocol (SMTP), for message negotiation and transmission.
SOAP allows processes running on disparate operating systems (such as Windows and Linux) to
communicate using Extensible Markup Language (XML). Since Web protocols like HTTP are installed
and running on all operating systems, SOAP allows clients to invoke web services and receive responses
independent of language and platforms
Advantages
 SOAP's neutrality characteristic explicitly makes it suitable for use with any transport protocol.
Implementations often use HTTP as a transport protocol, but other popular transport protocols can
be used. For example, SOAP can also be used over SMTP, JMS and message queues.
 SOAP, when combined with HTTP post/response exchanges, tunnels easily through existing
firewalls and proxies, and consequently doesn't require modifying the widespread computing and
communication infrastructures that exist for processing HTTP post/response exchanges.
 SOAP has available to it all the facilities of XML, including easy internationalization and
extensibility with XML Namespaces.
Disadvantages
 When using standard implementations and the default SOAP/HTTP binding, the XML infoset is
serialized as XML. To improve performance for the special case of XML with embedded binary
objects, the Message Transmission Optimization Mechanism was introduced.
 When relying on HTTP as a transport protocol and not using WS-Addressing or an ESB, the roles
of the interacting parties are fixed. Only one party (the client) can use the services of the other.
 The verbosity of the protocol, slow parsing speed of XML, and lack of a standardized interaction
model led to the domination in the field by services using the HTTP protocol more directly. See,
for example, REST.

5.12.1 STRUCTURE OF SOAP

SOAP building blocks


A SOAP message is an ordinary XML document containing the following elements:
Element Description Required
Envelope Identifies the XML document as a SOAP message. Yes
Header Contains header information. No
Body Contains call, and response information. Yes
Fault Provides information about errors that occurred while processing the message. No

5.12.2 SOAP AND HTTP

Example message (encapsulated in HTTP)


M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

POST /InStock HTTP/1.1


Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 299
SOAPAction: "http://www.w3.org/2003/05/soap-envelope"
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:m="http://www.example.org/stock/Manikandan">
<soap:Header>
</soap:Header>
<soap:Body>
<m:GetStockPrice>
<m:StockName>GOOGLE</m:StockName>
</m:GetStockPrice>
</soap:Body>
</soap:Envelope>

5.12.3 SOAP ENCODING

SOAP includes a built-in set of rules for encoding data types. It enables the SOAP message to indicate
specific data types, such as integers, floats, doubles, or arrays.
 SOAP data types are divided into two broad categories − scalar types and compound types.
 Scalar types contain exactly one value such as a last name, price, or product description.
 Compound types contain multiple values such as a purchase order or a list of stock quotes.
 Compound types are further subdivided into arrays and structs.
 The encoding style for a SOAP message is set via the SOAP-ENV:encodingStyle attribute.
 To use SOAP 1.1 encoding, use the value http://schemas.xmlsoap.org/soap/encoding/
 To use SOAP 1.2 encoding, use the value http://www.w3.org/2001/12/soap-encoding
 Latest SOAP specification adopts all the built-in types defined by XML Schema. Still, SOAP
maintains its own convention for defining constructs not standardized by XML Schema, such as
arrays and references.
Scalar Types
For scalar types, SOAP adopts all the built-in simple types specified by the XML Schema specification.
This includes strings, floats, doubles, and integers.
The following table lists the main simple types, excerpted from the XML Schema Part 0 − Primer
http://www.w3.org/TR/2000/WD-xmlschema-0-20000407/
Simple Types Built-In to XML Schema
Simple Type Example(s)
string Confirm this is electric.
boolean true, false, 1, 0.
float -INF, -1E4, -0, 0, 12.78E-2, 12, INF, NaN.
double -INF, -1E4, -0, 0, 12.78E-2, 12, INF, NaN.
decimal -1.23, 0, 123.4, 1000.00.
binary 100010
integer -126789, -1, 0, 1, 126789.
nonPositiveInteger -126789, -1, 0.
negativeInteger -126789, -1.
long -1, 12678967543233
int -1, 126789675
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

short -1, 12678


byte -1, 126
nonNegativeInteger 0, 1, 126789
unsignedLong 0, 12678967543233
unsignedInt 0, 1267896754
unsignedShort 0, 12678
unsignedByte 0, 126
positiveInteger 1, 126789.
date 1999-05-31, ---05.
time 13:20:00.000, 13:20:00.000-05:00
For example, here is a SOAP response with a double data type −
<?xml version='1.0' encoding='UTF-8'?>

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<SOAP-ENV:Body>
<ns1:getPriceResponse xmlns:ns1="urn:examples:priceservice" SOAP-
ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<return xsi:type="xsd:double">54.99</return>

</ns1:getPriceResponse>
</SOAP-ENV:Body>

</SOAP-ENV:Envelope>
Compound Types
SOAP arrays have a very specific set of rules, which require that you specify both the element type and
array size. SOAP also supports multidimensional arrays, but not all SOAP implementations support
multidimensional functionality.
To create an array, you must specify it as an xsi:type of array. The array must also include an arrayType
attribute. This attribute is required to specify the data type for the contained elements and the
dimension(s) of the array.
For example, the following attribute specifies an array of 10 double values −
arrayType = "xsd:double[10]"
In contrast, the following attribute specifies a two-dimensional array of strings −
arrayType = "xsd:string[5,5]"
Here is a sample SOAP response with an array of double values −
<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<SOAP-ENV:Body>
<ns1:getPriceListResponse xmlns:ns1="urn:examples:pricelistservice" SOAP-
ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming

<return xmlns:ns2="http://www.w3.org/2001/09/soap-encoding" xsi:type="ns2:Array"


ns2:arrayType="xsd:double[2]">
<item xsi:type="xsd:double">54.99</item>
<item xsi:type="xsd:double">19.99</item>
</return>

</ns1:getPriceListResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

5.12.4 RPC REPRESENTATION

Remote procedure calls in SOAP


Remote procedure calls in SOAP are essentially client-server interactions over HTTP where the request
and response comply with SOAP encoding rules. The Request-URI (Universal Resource Identifier) in
HTTP is typically used at the server end to map to a class or an object, but this is not mandated by SOAP.
Additionally, the HTTP header SOAPAction specifies the interface name (a URI) and the name of the
method to be called on the server. The SOAP message is an XML document whose root element, the
Envelope, specifies the overall structure of the message, its intended recipient, and other attributes of the
message. SOAP specifies a remote procedure call convention, which includes the representation and
format to be used for calls and responses. A method call is modeled as a compound data element
consisting of a sequence of fields (accessors), one for each parameter. A return structure consists of the
return value as well as the out and in/out parameters. SOAP encoding rules specify the serialization for
primitive and application-defined datatypes.

POST /Temperature HTTP/1.1


Host: www.temperature-service.com
Content-Type: text/xml
Content-Length: 357
SOAPAction: "http://weather.org/query#GetTemperature"

< SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
< SOAP-ENV:Body>
< m:GetTemperature xmlns:m="http://weather.org/query">
< longitude>39W< /longitude>
< latitude>62S< /latitude>
< /m:GetTemperature>
< /SOAP-ENV:Body> < /SOAP-ENV:Envelope>

M.I.E.T./CSE/III/Internet Programming

You might also like