Professional Documents
Culture Documents
ENGINEERING
COURSE MATERIAL
CS6501 - INTERNET PROGRAMMING
M.I.E.T./CSE/III/Internet Programming
CS6501/ CS6501 internet programming
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.
M.I.E.T./CSE/III/Internet Programming
CS6501/ CS6501 internet programming
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
COURSE OBJECTIVE
COURSE OUTCOMES
Prepared by Verified By
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:
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
}
}
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
boolea
n 1 bit True / False False
‗\u0000‘ to
char 16 bits ‗\uffff‘ NA
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.
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.
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
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
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
The following table lists the arithmetic operators −
Show Examples
Show Examples
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
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 = 1100 0011
Show Examples
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
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 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
Assume Boolean variables A holds true and variable B holds false, then −
Show Examples
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
Show Examples
Simple assignment operator. Assigns values from C = A + B will assign value of A + B into
=
right side operands to left side operand. C
Miscellaneous Operators
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 −
Following is an example −
Example
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 −
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
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 {}
Output
true
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.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
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.
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 {
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
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[]) {
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
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(",");
}
}
}
James,Larry,Tom,Lacy,
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
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 {
}
}
}
This would produce the following result:
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
10
20
40
50
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
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.
Syntax
or
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.
Syntax
Other clauses than val and method can be used in a class declaration: we shall introduce them as needed.
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:
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.
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
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{
}
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:
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.
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
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.
import java.io.*;
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
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:
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.
return name;
}
public String getAddress()
{
return address;
}
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 */
}
}
When you would compile above class then you would get the following error:
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 written in a file with a .java extension, with the name of the interface
matching the name of the file.
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:
Example:
{
//Any number of final, static fields
Example:
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
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.
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.
//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.
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
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.
}
System.out.println("Out of the block");
}
}
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;
f.printStackTrace(); return -
1;
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.
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;
}
System.out.println("Thread " + threadName + " exiting.");
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
{
System.out.println("Starting " + threadName ); if (t ==
null)
{
t = new Thread (this, threadName); t.start
();
}
R1.start();
}
}
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
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:
}
} 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
T1.start();
}
}
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
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
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
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).
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
OUTPUT:
java
strings
example
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 {
if (in != null) {
in.close();
}
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
if (out != null) {
out.close();
}
}}
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.*;
try {
int 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();
}
}
}
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.*;
try {
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':
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:
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.
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.
{
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
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.
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
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>
<hr>
</html>
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
UNIT II
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
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.
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
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.
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.
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)
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
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
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
Collaboration tools allow a group of people work together virtually in real-time over the internet.
Features:-
Examples:-
Tool Use
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.
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).
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
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.
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
Applicati
Computer DSL on
software:
email
Browser, ,
etc
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
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
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
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.
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
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.
Internet
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:
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 Intranet
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
For limited external communication between customers, Only for communication within a
suppliers and business partners. company.
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 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.
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.
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
Transmitting the data in duplex mode means flow of data in both the directions at the same time.
Reliable Service
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:
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.
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 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.
2 Authentication Yes No
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.
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
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
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.
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.
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:
Paragraphs:
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.
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
Comments:
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.
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:
Using CSS, the same element can be coded using style properties instead of HTML presentational
attributes:
An "external" CSS file, as described below, can be associated with an HTML document using the
following syntax:
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:
<!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.
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.
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:
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.
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.
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 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?
Why XHTML?
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").
Document Structure
XHTML Elements
XHTML Attributes
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.
Selectors
Box Model
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
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.
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.
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.
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.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
No border.
A hidden border.
A mixed border.
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;
}
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.
UNIT III
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.
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
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.
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.
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 Expressions
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
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:-
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.
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.
<script type="text/javascript">
<!--
try {
// Code to run
[break;]
catch ( e ) {
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
[break;]
[ finally {
// 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
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
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>
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
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:
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:-
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.
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.
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:
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:
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.
Servlet Exceution
This is how a servlet execution takes place when client (browser) makes a request to the webserver.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
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.
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 commonly used methods for a request-response between a client and server are: GET and POST.
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
Note that the query string (name/value pairs) is sent in the HTTP message body of a POST request:
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
HTTP cannot have any data about precious client-server communication (stateless)
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.
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
when user closes the browser. It is removed only if user logout or signout.
Advantage of Cookies
Disadvantage of Cookies
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.
A web server can send a hidden HTML form field along with a unique session ID as follows:
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.
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:
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
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.
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 −
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 −
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.
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)
sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql);
while(rs.next()
{
int id = rs.getInt("id");
}
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
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
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.
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 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:
JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform
JSP-
// 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:
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.
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.
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.
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.
Scripting elements provides the ability to insert java code inside the jsp.
scriptlet tag
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>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%
%>
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>
The code written inside the jsp declaration tag is placed outside the service() method of auto generated
servlet.
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %> </body>
</html>
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.
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" %>
UNIT IV
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
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
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
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
{
echo "Hello Hellow
world!"; orld
}
writeMsg();
?>
function name($fname, $dob)
name("Bala","12-2-91"); name("Gopal","22-12-96");
?> o/p:-
Bala was born on 12-2-91
<?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 −
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;
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;
?>
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
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)
else
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
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
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 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.
<?php
case "red":
case "blue":
case "green":
default:
?>
o/p:-
The for statement is used when you know how many times you want to execute a statement
or a block of statements.
<?php
?>
o/p:
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
01234
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;
?>
o/p:-
0123456789
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
while( $i < 10 );
?>
o/p:-
0123456789
For each pass the value of the current array element is assigned to $value
<?php
$a = range(0,9); foreach( $a as $i )
echo $i,"<br>";
?> o/p:-
0123456789
<?php
?>
o/p
Array ( [a] => Dog [b] => Cat [c] => Horse)
array_chunk()
The last chunk may contain less than size elements. <?php
?>
o/p
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
Array (
[1] => b
)
[1] => d
)
Array
(
[4] => e
)
)
<?php
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
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
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
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.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
?> o/p:-
Array ( [0] => banana [1] => apple [2] => orange ) orange
<?php
O/
$a = array(1,2,3,4); p:-
print_r(array_sum($a)
);
10
echo "<br>";
print_r(array_search(
3, $a)); 2
?>
The calendar extension presents a series of functions to simplify converting between different
calendar formats.
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.
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";
?>
// 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 (PDO)
$conn = null;
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
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>
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
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
No predefined tags in XML, only user defined tags It is stricter than HTML, case sensitive
4.10 BASIC XML
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
Text
XML declaration
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
It is a “name-value” pair
<phone available=”yes”>1234</phone>
References
o Entity reference
o Character Reference
Text
XML elements and attributes are case sensitive Start and end tag needs to be in
same case
Example:-
<?xml version=”1.0”?>
<person>
<name>Bala</name>
<cell>1234</cell>
<company>TCS</company>
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
XML tags
XML attributes
XML HTML
independent dependent
present
It is a Framework It is a mark up
for language
markup language
definition
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
strict
Dynamic static
DTD in XML
Syntax:-
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
sample.xml
company)>
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
<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
<address>
<name>Bala</name>
<phone>1234</phone>
<company>TCS</company>
</address>
address.dtd
>
Advantages of DTD
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
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
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: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>
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:sequence>
</xs:complexType>
</xs:element>
<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
<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>
o/p:-
<contact>
<name>Bala></name>
<company>TCS</company>
<phone>1234</phone>
<contact>
XML Schemas are extensible to additions XML Schemas support data types
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.
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
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
o String
o Numeric
o Date
o Boolean
Document Object
Model Simple API for XML
memory memory
space space
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.*;
{ try
catch(Exception e)
System.exit(1);
else
catch(IOException ioe)
ioe.printStackTrace();
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
User.xml
<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
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
Step-1 simple.xml
<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
<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>
Step-1 simple.xml
<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
<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>
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 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.
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
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
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.
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.
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.
<url>http://www.xul.fr/xul-icon.gif</url> <link>http://www.xul.fr/en/index.php</link>
</image>
<item>
</item>
<item>
</channel>
</rss>
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
Replace the URL by your domain name with the path and filename of your RSS feed.
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.
<?xml version="1.0"?>
<link>...</link> <updated>...</updated>
<author> <name>...</name>
</author>
<id>...</id>
<updated>...</updated> <summary>...</summary>
</entry>
</feed>
Example:-
<title>Example Feed</title>
<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
documents, audio,
escaped sequence as video, etc
payload as payload
or updated
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 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.
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.
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
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
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().
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.
status : Returns the status as a number (e.g., 404 for "Not Found" and 200 for "OK").
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'
},
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.
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
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>
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.
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
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
[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.
4. Click Next.
M.I.E.T./CSE/III/Internet Programming
Subject code/Name: CS6501 internet programming
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 .
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
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).
Binding– a concrete protocol and data format specification for a particular port type.
<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
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.
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.
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.
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.
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
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
if ( resultSet.next() )
{
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.
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
<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
</ns1:getPriceListResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
< 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