0% found this document useful (0 votes)
174 views

Cs6501 Internet Programming

This document discusses object-oriented programming concepts in Java including abstract classes, interfaces, inheritance, and polymorphism. It provides syntax examples and sample code to demonstrate abstract classes with abstract methods that are implemented in derived classes. Interface syntax and a sample program showing a class implementing an interface is also included. Different types of inheritance like single, multilevel and hierarchical are defined along with code examples.

Uploaded by

Sivamani GM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
174 views

Cs6501 Internet Programming

This document discusses object-oriented programming concepts in Java including abstract classes, interfaces, inheritance, and polymorphism. It provides syntax examples and sample code to demonstrate abstract classes with abstract methods that are implemented in derived classes. Interface syntax and a sample program showing a class implementing an interface is also included. Different types of inheritance like single, multilevel and hierarchical are defined along with code examples.

Uploaded by

Sivamani GM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

VELTECH HIGHTECH Dr.RANGARAJAN Dr.

SAKUNTHALA ENGINEERING COLLEGE


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS6501 INTERNET PROGRAMMING


UNIT I JAVA PROGRAMMING
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.

1.1.2 ABSTRACT CLASS EXAMPLE


1.1ABSTRACT CLASSES PROGRAM
➢ abstract class is defined as a super class
in java that does nothing, but lists out the abstract class A
common features of the other class {
➢ “abstract” keyword is used
➢ It may contain abstract methods {
(methods without body) abstract void absmethod();
➢ If a class has at least one abstract
method, then the class must be declared }
as “abstract”
class B extends A
➢ object cannot be created
➢ To use abstract class, we have to inherit it {
from another class, then define the
void absmethod()
abstract methods in it.
{
➢ If abstract class is inherited, all the
System.out.println("One ");
abstract methods in it should be defined
}
in derived class.
}
1.1.1 ABSTRACT CLASS SYNTAX class C extends A
{
abstract class name void absmethod()
{
{
System.out.println("Two ");
abstract void function name(); }
}
} class abs
class class name extends abstract class name {
{ public static void main(String arg[])
void function name() {
{ B b=new B();
} C c=new C();
b.absmethod();
} c.absmethod();
} } O/p: one Two

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 1


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

public static void main(String args[])


{
1.2.INTERFACE
A6 obj = new A6();
➢ An interface is a collection of abstract
methods. obj.print();
➢ A class implements an interface, thereby }
inheriting the abstract methods of the
interface }
➢ An interface is not a class.
O/p: Hello
➢ Writing an interface is similar to writing a
class
➢ A class describes the attributes and 1.3 INHERITANCE
behaviors of an object. ➢ Inheritance in java is defined as the
➢ An interface contains behaviors that a process of deriving a child class from a
class implements. parent class.
➢ Unless the class that implements the ➢ The child class acquires all the properties
interface is abstract, all the methods of the of the parent class.
interface need to be defined in the class ➢ “extends” is the keyword used to inherit
the properties of parent class.
1. 2.1 INTERFACE SYNTAX
INHERITANCE SYNTAX
interface interface name
Class parent name
{
{
}
-------------
Class class name implements interface name
-------------
{
}
}
Class child extends parent name
2.2 INTERFACE SAMPLE PROGRAM
{
interface printable -------
-------
{ }
void print();
} 1.3.1 DIFFERENCES

class A6 implements printable ABSTRACT CLASS INTERFACE


{
public void print() We can inherit only one We can inherit more
{ abstract class than one interfaces
Abstract class Interface Interface members are
System.out.println("Hello");}
abstract class members only public

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 2


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

can be public, private or {


protected int a=10;
Method may or may not No method definition }
have definition (default) Class derived extends base
{ BASE
Efficient Slow int b=20;
void add()
{
System.out.println(a+b);
1.3.2 WHY USE JAVA INTERFACE? } DERIVED
}
There are mainly three reasons to use class single
interface. They are given below. {
public static void main(String bala[])
o It is used to achieve abstraction. {
o By interface, we can support the derived d = new derived();
functionality of multiple inheritance. d.add();
o It can be used to achieve loose }
coupling. O/p : 30
1.3.5 MULTILEVEL INHERITANCE

➢ It is the process of deriving a child


1.3.3 INHERITANCE TYPE
class from another child class.
➢ Single Inheritance MULTI LEVEL INHERITANCE EXAMPLE
➢ Multilevel Inheritance PROGRAM
➢ Hierarchical Inheritance BASE
INHERITANCE ADVANTAGES
➢ Flexibility class base
➢ Reusability {
➢ Extensibility int a=10;
DERIVED 1
➢ Data hiding }
➢ Overriding class derived1 extends base
{
1.3.4 SINGLE INHERITANCE int b=20; DERIVED 2
➢ Single inheritance in java is defined as the }
process of deriving a single derived class class derived2 extends derived1
from a single base class. {
➢ It is the simplest form of inheritance in int c=30;
Java. void add()
SINGLE INHERITANCE EXAMPLE PROGRAM {
class base System.out.println(a+b+c);
}

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 3


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

} derived1 d1 = new derived1();


Class multilevel derived2 d1 = new derived2();
{ d1.add1();
public static void main(String bala[]) d2.add2();
{ }
derived2 d2 = new derived2(); }
d2.add();
}
}

1.3.6 HIERARCHICAL INHERITANCE


1.3.7 HYBRID INHERITANCE
➢ It is the process of deriving more than one
child class from the same parent class. ➢ If more than two types of inheritance
➢ Two or more child classes having the combined together in deriving child
same parent class. classes, it is called hybrid inheritance.
HIERARCHICAL INHERITANCE EXAMPLE ➢ It may be a combination of single-
PROGRAM multilevel, multilevel-hierarchical, etc.
class base HYBRID INHERITANCE EXAMPLE PROGRAM
{ class base
int a=10; {
} int a=10;
class derived1 extends base }
{ class derived1 extends base
int b=20; {
void add1() int b=20;
{ }
System.out.println(a+b); class derived2 extends derived1
} {
} BASE
int c=30;
class derived2 extends base void add1()
{ {
int c=30; DERIVED 1 DERIVED 2 System.out.println(a+b+c);
void add2() }
{ }
System.out.println(a+c); class derived3 extends derived1
} {
} int d=40;
class hierarchical void add2()
{ {
public static void main(String bala[]) System.out.println(a+b+d);
{ }
}

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 4


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

class multilevel ➢ If the string already exists in the pool, a


{ reference to the pooled instance is
public static void main(String bala[]) returned.
{ ➢ If string doesn't exist in the pool, a new
derived2 d2 = new derived2(); string instance is created and placed in
derived3 d3 = new derived3(); the pool.
d2.add1(); BY NEW KEYWORD
d3.add2(); ➢ String s=new String("Welcome");//creates
} two objects and one reference variable
}
JAVA STRING EXAMPLE PROGRAM
DISADVANTAGES OF INHERITANCE public class StringExample
➢ Both classes (super and subclasses) {
are tightly-coupled. public static void main(String args[])
➢ As they are tightly coupled they {
cannot work independently of each String s1="java";
other. char ch[]={'s','t','r','i','n','g','s'};
➢ Changing the code in super class String s2=new String(ch);
method also affects the subclass String s3= System.out.println(s1);
functionality. system.out.println(s1);
➢ If super class method is deleted, the System.out.println(s2);
code may not work System.out.println(s3);
}

1.4 STRING HANDLING }


➢ A string in Java is defined as an object that
String manipulation:-
represents a sequence of characters.
class str
➢ char c [ ] = { ‘B’,’A’,’L’,’A’}; is equal to
{
String s = “BALA”;
public static void main(String bala[ ] )
➢ String class is used to create object for it.
{
String s = “sachin”;
There are two ways to create String object: 1.
System.out.println(“s.concat(“SIR”));
By string literal
System.out.println(s.length());
2. By new keyword
System.out.println(s+”SIR”);
System.out.println(s.charAt(3));
1.4.1 STRING LITERAL
String s2 = “BALA”;
➢ Java String literal is created by using System.out.println(s.equals(s2));
double quotes. For Example: String s3 = “bala”;
String s="welcome"; System.out.println(s2.equalsIgnoreCase(s3));
➢ Each time you create a string literal, the System.out.println(s.substring(1,4));
JVM checks the string constant pool first. System.out.println(s.substring(2));
String s4 = s2.replace(‘L’,’B’);
System.out.println(s4);

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 5


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

System.out.println(s.toUpperCase()); of every source file that contains the classes,


System.out.println(s2.toLowerCase()); interfaces, enumerations, and annotation
System.out.println(s3.lastIndexOf(‘a’)); types that you want to include in the
} package.
} ➢ The package statement should be the
O/P first line in the source file
PACKAGE SYNTAX
SachinSIR
Package name of the package;
6
sachinSIR PACKAGE EXAMPLE PROGRAM
h
false package letmecalculate;
true
ach public class Calculator
chin {
BABA public int add(int a, int b)
SACHIN {
Bala return a+b;
3 }
public static void main(String args[]){
Calculator obj = new Calculator();
1.5 PACKAGES System.out.println(obj.add(10, 20));
➢ A package is a collection of classes and }
interfaces that provides a high-level layer }
of access protection and name space
management.
import letmecalculate.Calculator;
➢ To organize files when a project consists
public class Demo{
of multiple modules.
public static void main(String args[]){
➢ It eliminates naming conflicts when
Calculator obj = new Calculator();
different packages have classes same
System.out.println(obj.add(100,
names.
200));
➢ Packages access level also allows
}
protecting data from non-authorized
}
classes.
➢ Some of the existing packages in Java are::
java.lang - bundles the fundamental
classes java.io - classes for input , output 1.6 EXCEPTION HANDLING
functions are bundled in this package ➢ An exception is a problem that arises
during the execution of a program
1.5.1 CREATING A PACKAGE
➢ Its breaks the normal flow of the
➢ When creating a package, you should execution.
choose a name for the package and put a ➢ So these exceptions have to be handled
package statement with that name at the top efficiently in order to avoid program
getting crashed.

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 6


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

REASONS FOR EXCEPTION not occur.


➢ User entered invalid input. throw To throw the specific
➢ File not found exception from
➢ Network connection lost program code
➢ JVM ran out of memory throws It specifies exceptions
BENEFITS OF EXCEPTION that can be thrown by
➢ Avoid crashing of applications abruptly. particular method
➢ Various types of errors grouped together.
1.6.1 TYPES OF EXCEPTION 1.6.2 EXCEPTION HANDLING EXAMPLE
PROGRAM
i) Checked exception
➢ It occurs during the compile time. Class sample1
➢ It cannot be ignored. {
➢ Programmer should take care/handle public static void main(String bala[])
exceptions. {
➢ Ex: FileNotFoundException int a;
ii) Unchecked exception try
➢ It occurs during runtime {
➢ It includes programming bugs, logical a=10/0;
errors, etc. }
➢ It is ignored at the run time. catch(ArithmeticException e)
➢ int num[] = {1,2,3}; {
➢ System.out.println(num[10]); System.out.println("Div
by zero error");
Error: ArrayIndexOutOfBoundsException }
}
➢ It is not exception, but actually problems. }
➢ They occur beyond the programmers’
control 1.6.3 MULTIPLE CATCH BLOCKS FOR A
➢ It is ignored, because we cannot do SINGLE TRY BLOCK
anything about it.
➢ Ex: StackOverFlowError, JVM out of
memory error. class sample1
{
Keywords used public static void main(String bala[])
try Error prone block of {
code to be monitored int a[] = new int[5];
for exception try
catch Each corresponding {
‘try’ block System.out.println(a[10
finally The code that must be ]);
executed even though System.out.println(10/
exception may/may 0);
}

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 7


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

catch(ArrayIndexOutOfBounds Method that throws exception


Exception e) class sample1
{ {
System.out.println(e); static void xyz(int a[])
} {
catch(ArithmeticException e) try
{ {
System.out.println(e); System.out.println(a[10
} ]);
} }
} catch(ArrayIndexOutOfBounds
Exception e)
O/p:-
{
java.lang.ArrayIndexOutOfBoundsException:
System.out.println(e);
10
}
public static void main(String
bala[])
1.6.4 FINALLY BLOCK
{
class sample1 int a[] = {1,2};
{ xyz(a);
public static void main(String bala[]) }
{ }
try O/p:-
{ java.lang.ArrayIndexOutOfBoundsException:
System.out.println(10/ 10
0);
} 1.7 THREAD
catch(ArithmeticException e)
➢ A thread in java is defined as the
{
smallest unit of a program that runs
System.out.println(e);
continuously, which is a part of a
}
process.
finally
➢ It is a light weight process in Java
{
➢ Each thread performs a certain task.
System.out.println("Thi
THREAD IMPLEMENTATION:-
s is from Finally block");
1. By extending “Thread” class
}
2. By implementing “Runnable” interface
}
}
O/p:-
java.lang.ArithmeticException: / by zero
This is from Finally block 1.7.1 LIFE CYCLE OF THREAD

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 8


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ A thread goes through various stages System.out.println(“Thread is


in its life cycle. running”);
➢ For example, a thread is born, started, }
runs, and then dies. Following diagram public static void main(String bala[ ] )
shows complete life cycle of a thread. {
STATES OF A JAVA THREAD:- ex1 e = new ex1( );
➢ New: A new thread begins its life cycle e.start( );
in the new state. It remains in this }
state until the program starts the }
thread. ➢ run() is the method used to tell a
➢ Runnable: After a newly born thread thread, what task it should perform
is started, the thread becomes while running.
runnable. A thread in this state is ➢ start() is the method used to start
considered to be executing its task. execution of a thread
➢ Waiting: Sometimes, a thread ➢ Thread scheduler handles all the
transitions to the waiting state while thread processes.
the thread waits for another thread to Some popular Thread methods in Java:-
perform a task. A class sleep extends Thread
➢ Timed waiting: A runnable thread can {
enter the timed waiting state for a public void run()
specified interval of time. {
➢ Terminated: A runnable thread enters for(int i = 0; i < 2; i++)
the terminated state when it {
completes its task or otherwise try
terminates. {
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.print("Exception
here");
}
System.out.println(i);
System.out.println(Thread.currentThr
ead)
getName());
}
}
THREAD EXAMPLE PROGRAM public static void main(String bala[ ] )
class ex1 extends Thread {
{ sleep s1 = new sleep();
public void run() System.out.println(s1.getName() );
{ s1.setName("bala");

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 9


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

System.out.println(s1.getName() ); }
s1.start(); }
} class MT
} {
O/p:- public static void main(String
Thread-0 name of thread1 aad[])
Bala Thread name modified {
0 for loop’s i value printed class1 c1=new class1();
Bala current thread name is printed class2 c2=new class2();
1 for loop’s i value printed c1.start();
Bala current thread name is printed c2.start();
}
1.7.2 MULTI THREADING }
➢ We cannot guarantee which thread is
executed first
➢ Multithreading is the process of ➢ Thread scheduler decides it based on
executing more than one thread at a optimality
time. ADVANTAGES OF MULTI-THREADING:-
➢ Each thread performs a specific task ➢ More than one task executed
➢ All the threads run simultaneously simultaneously
➢ OS divides the processing time among ➢ Time saving and efficient
each thread ➢ Quicker execution
➢ Thereby the available CPU resources ➢ Less memory space occupied by each
are optimally used when a computer thread
has multiple CPUs. ➢ It is useful in developing Gaming
➢ Performing multiple activities in a applications, graphics
program concurrently is called
multithreading.
EXAMPLE MULTI THREADING PROGRAM
class class1 extends Thread
{ IO STREAM
public void run()
{ ➢ A stream is defined as a continuous
System.out.print("onet flow of objects sequentially.
ask"); ➢ In Java, A stream is defined as a
} channel on which data flow from
} sender to receiver
class class2 extends Thread ➢ Categories: Input stream and output
{ stream
public void run() ➢ java.io package contains all the classes
{ required for input and output
System.out.print("twot operations.
ask")

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 10


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ Input Stream: Input stream is defined public static void main(String bala[ ] )
as an object that reads a stream of {
data from a file int n;
➢ Output Stream: Output stream is try
defined as an object that writes {
stream of data to a file InputStream is = new
➢ Nature of stream: Byte Stream and FileInputStream("bala.txt");
character stream System.out.println("Total
Byte Stream Bytes = "+(n=is.available()));
➢ To give input and get output in bytes for(int i = 0; i <n; i++)
➢ Super classes available: InputStream, System.out.println((char)is.rea
OutputStream d());
➢ Methods: read(), write() is.close();
InputStream classes OutputStream classes }
FileInputStream FileOuputStream catch(FileNotFoundException
PipedInputStream PipedOuputStream e1)
FilterInputStream FilterOuputStream {
ByteArrayInputStrea ByteArrayOuputStream System.out.print(e1);
m }
catch(IOException e2)
{
System.out.print(e2);
}
}
}
O/p:-
Total bytes = 20
➢ This is the file content from bala.txt
Character Stream BufferedInputStream and
➢ To give input and get output in BufferedOutputStream classes
character ➢ It is preferred over other streams for
➢ Super classes available: Reader, Writer R/W operations
➢ Methods: read(), write() ➢ It is more efficient in handling files
Classes in Reader Classes in Writer ➢ All their methods are extended from
FileReader FileWriter InputStream and OutputStream class
PipeReader PipeWriter which are their parents.
FilterReader FilterWriter ➢ We can specify buffer size (default
ByteArrayreader ByteArrayWriter size = 512 bytes)

Example for FileInputStream and import java.io.*;
FileOutputStream classes class buf
import java.io.*; {
class fis public static void main(String bala[ ] )
{

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 11


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

{
try Uses: To perform arithmetic operations,
{ display graphics, play sounds, display videos,
DataOutputStream dos = new etc
DataOutputStream(new Situations for applet usage:-
BufferedOutputStream(new ➢ To display dynamic web pages
FileOutputStream("bala.txt"))) ➢ To display special effects
; (Audio/Video)
dos.writeUTF("Bala"); ➢ To transfer an application to a user
dos.writeDouble(12345.67); who is located remotely
dos.writeInt(1234); Life Cycle of an Applet:
dos.writeChar('s');
Four methods in the Applet class give you the
dos.close();
framework on which you build any serious
DataInputStream dis = new
applet:
DataInputStream(new
BufferedInputStream(new
FileInputStream("bala.txt"));
System.out.println(dis.readUTF
());
System.out.println(dis.readDo
uble());
System.out.println(dis.readInt(
));
System.out.println(dis.readCha
r()); ➢ init: This method is intended for
} whatever initialization is needed
catch(FileNotFoundException e1) for your applet.
{ ➢
System.out.print(e1); ➢ start: This method is automatically
} called after the browser calls the init
catch(IOException e2) method.
{ ➢
System.out.print(e2); ➢ stop: This method is automatically
} called when the user moves off the
} page on which the applet sits.
} ➢
➢ destroy: This method is only
APPLET called when the browser shuts
➢ Applets are small Java programs that down normally.
can be used in internet
➢ They can be transferred over internet ➢ paint: Invoked immediately after the
from one PC to another, displayed on start() method, and also any time the
Java enabled web browsers applet needs to repaint itself in the

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 12


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

browser. The paint() method is browsers downloading time


actually inherited from the java.awt. Suitable for Real time Slow to execute
apps
Differences between applet and application
Client-server Outdated as of now
➢ Applet does not have main() method
communication is
➢ On loading applets, some methods of
possible
applet are called automatically by JVM
➢ It cannot work independently
APPLET SAMPLE PROGRAM
➢ They cannot read from a file, cannot
import java.awt.*;
write into a file
import java.applet.*;
➢ They cannot execute any program in
public class smiley extends Applet
local PC
{
➢ They cannot communicate with other
public void paint(Graphics g)
server in a network
{
➢ They cannot use library files of other
g.drawOval(60,60,200,200);
languages
g.fillOval(90,120,50,20);
➢ They are more secured
g.fillOval(190,120,50,20);
HIERARCHY OF APPLET
g.drawLine(165,125,165,175);
g.drawArc(110,130,95,95,0,-180);
}
}
O/p:-
D:\>javac smiley.java
D:\>appletviewer smiley.java

BASIC CONCEPTS OF OOPS


Java is an Object-Oriented Language. As
a language that has the Object Oriented
Advantages Disadvantages feature, Java supports the following
Simple, good GUI Java-plugin web fundamental concepts:
browsers needed
Supports many GUI based ➢ Polymorphism
platforms programming is ➢ Inheritance
complex, compared to
latest PHP, HTML&CSS ➢ Encapsulation
Supported by many Takes a lot of
➢ Abstraction

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 13


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ Classes

➢ Objects INNER CLASS

➢ Method
➢ Inner class in java is defined as a
➢ Message Parsing class within another class
➢ They are also called as nested class
Object Any entity that has state and
Behavior is known as an object. For SYNTAX OF INNER CLASS
example: chair, pen, table, keyboard, bike Class one
etc. It can be physical and logical. {
Class Collection of objects is called class. It is Class two
a logical entity. {
-------
Inheritance When one object acquires all -------
the properties and behaviours of parent }
object i.e. known as inheritance. It provides }
code reusability. It is used to achieve
runtime polymorphism.
Polymorphism When one task is performed
by different ways i.e. known as
polymorphism. For example: to convense
the customer differently, to draw something
e.g. shape or rectangle etc. In java, we use
method overloading and method overriding
to achieve polymorphism. Another example
can be to speak something e.g. cat speaks
meaw, dog barks woof etc.
Static inner class
Abstraction Hiding internal details and ➢ They are the static members of
showing functionality is known as another class
abstraction. For example: phone call, we ➢ Static keyword is present before the
don't know the internal processing. In java, inner class
we use abstract class and interface to ➢ Static member of outer class are
achieve abstraction. visible to static inner class
➢ Non static members of outer lass are
Encapsulation Binding (or wrapping) code
invisible to static inner class
and data together into a single unit is known
EXAMPLE PROGRAM FOR STATIC INNER
as encapsulation. For example: capsule, it is
CLASS
wrapped with different medicines. A java
class outer
class is the example of encapsulation. Java
{
bean is the fully encapsulated class because
static class inner
all the data members are private here.
{

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 14


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

public void imethod() }


{ }
System.out.println("Inner class");
O/p:-
}
Inner class
}
public static void main(String[ ] bala) ARRAY
{ ➢ An array in Java is defined as a
outer o = new outer(); collection of elements of similar data
inner i = new inner(); type
i.imethod(); ➢ which are stored in continuous
} memory locations.
} ➢ The elements are accessed by their
O/p:- indexes.
Inner class ➢ Array index always starts from zero
Normal inner class ➢ The size of the array is fixed.
➢ They are non-static member of outer ➢ All the elements are stored under
class the same name.
➢ They can access only non-static
members of outer class ARRAY DECLARATION SYNTAX
✓ int a [ ] = new int [ 5 ] ; //declaration
EXAMPLE PROGRAM FOR NORMAL INNER ✓ int [ ] a = new int [ 5 ]; //another way
CLASS of declaration
class outer ✓ int [ ] a = {1,2,3}; // declared and
{ initialized
class inner
{ Types:-
public void imethod() ➢ Single Dimensional array (1-D array)
{ ➢ Multi-dimensional array (n-D array)
System.out.println("inner class");
} 1-D array example:-
} class array
void omethod() {
{ public static void main(String bala [ ] )
inner i = new inner(); {
i.imethod(); int a [ ] = { 1, 2, 3 };
} for(int i = 0; i < 3 ; i++)
} System.out.println(a[i]);
public class innernormal }
{ }
public static void main(String bala[ ]) O/p:-
{ 3
outer o = new outer(); 6
o.omethod(); 9

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 15


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

public static void main(String args[])


2-D array example:- {
class array Bike1 b=new Bike1();
{ }
public static void main(String bala [ ] ) }
{ Output: Bike is created
int a [ ] [ ] = { { 1, 1, 1 }, {1,1,1}, Java parameterized constructor
{1,1,1} } ; A constructor that have parameters is
for(int i = 0; i < 3 ; i++) known as parameterized constructor.
for(int j = 0; j<3; j++) Parameterized constructor is used to provide
System.out.println(a[ i ] [ j ] ); different values to the distinct objects. In this
} example, we have created the constructor of
} Student class that have two parameters. We
can have any number of parameters in the
O/p:- constructor. class Student4
333
{
CONSTRUCTORS
int id;
➢ Constructor in java is a special type of
String name;
method that is used to initialize the
object. Student4(int i, String n)
➢ constructor is invoked at the time of
object creation. { id = i;
Rules for creating java constructor name = n; }
There are basically two rules defined for the
constructor. void display()
1.Constructor name must be same as its class {
name 2. Constructor must have no explicit
return type Types of java constructors System.out.println(id+" "+name);
There are two types of constructors: }
1. Default constructor (no-arg constructor)
2. Parameterized constructor public static void main(String args[])
Example of default constructor
{Student4 s1 = new
In this example, we are creating the no-arg
Student4(111,"Karan");
constructor in the Bike class. It will be invoked
at the time of object creation. Student4 s2 = new
class Bike1 Student4(222,"Aryan");
{ s1.display(); s2.display();
Bike1()
}}
{
System.out.println("Bike is Output: 111 Karan
created");
}

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 16


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

LIST THE ACCESS SPECIFIER USED IN JAVA? 3. Explain exception handling(NOV/DEC


Java provides a number of access modifiers to set 2016 & 2015)
access levels for classes, variables, methods and 4. Explain Buffer reader (NOV/DEC 2016)
constructors. The four access levels are: 5. Explain thread(APR/MAY 2017 &
• Visible to the package. the default. No modifiers (NOV/DEC 2017))
are needed. 6. Explain APPLET(APR/MAY 2017)
• Visible to the class only (private). 7. Explain Multi threading(NOV/DEC
• Visible to the world (public). 2015)
• Visible to the package and all subclasses 8. Explain interface(NOV/DEC 2017)
(protected).
IMPORTANT 2 MARKS QUESTION:
PREVIOUS YEAR UNIVERSITY 2 MARKS 1. How java is platform independent?
QUESTION
2. Differentiate a vector and an array in Java.
1. Give the different types of type casting in
java with example program.(NOV/DEC 3. How to create two-dimensional array in
2016) Java
2. Mention the way in which the current 4. Is there any error in the given Java
state of a thread can be obtain. (NOV/DEC Statement? Analyze:
2016) char [] string = “abcdef”;
3. Difference between overriding and
5. Write down the fundamentals of Exception
overloading(MAY/JUNE 2016)
handling.
4. Example of chained exception(MAY/JUNE
2016) 6. Define Multithreaded Programming.
5. JAVA program for floating point 7. What are the two ways for creating a
division(APR/MAY 2017) Thread?
6. Difference between package and
8. What is static in Java? Give its uses.
interface(APR/MAY 2017)
7. Define Abstract class(NOV/DEC 2015) 9. Mention the purpose of the keyword
“final”.
8. Features of JAVA(NOV/DEC 2015)
9. Difference between abstract class and 10.Can an abstract class in Java be
interface(NOV/DEC 2017) instantiated? Give the reason.
10. Define APPLET(NOV/DEC 2017) 11.What is the difference between
constructor and a method?
PREVIOUS YEAR UNIVERSITY 16 MARKS
QUESTIONS 12. What is the difference between method
overloading and overriding?
1. Explain the types of constructor
(NOV/DEC 2016) 13.How do you define an interface?
2. Explain multi level 14. What is finalize() and Garbage Collection?
inheritance(NOV/DEC 2016)

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 17


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

15.How does a radio button in java differ 9 Discuss the different models of Threads and
from a check box? their states.
16.Why do you need run () and start () 10 Design and Write a Java Program using
method both. Applets
17.What is a Stream? Which class allows you
to read objects directly from a stream?
18.What is Polymorphism in Java? Explain
how Polymorphism is supported in Java?
19.Mention the subclasses of the AWT Event
class.
20.Code a Graphics method in Java to draw
the String “Hello World” from the
coordinates (100,200).
IMPORTANT 16 MARKS QUESTION:
1 Explain the features and structure of Java
Program.
2 Explain about Inheritance and Interfaces in
Java.
3 Show how compile- time and run- time
polymorphism are achieved in Java? Explain
with examples.
4 Explain about Packages and Abstract classes
in Java.
5 Explain about Applet Lifecycle? How Applets
are prepared and executed?
6 List and discuss the role of String and String
Buffer classes used in Java.
7 What are the different input and output
streams and their classes? Explain with
Examples?
8 Discuss about Exception handling in Java
with suitable examples.

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 18


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

CS6501 INTERNET PROGRAMMING


UNIT II WEBSITES BASICS, HTML 5, CSS
3, WEB 2.0 8 Web 2.0
Basics-2.1 RIA Rich Internet
Applications – 2.2 Collaborations tools
– 2.3 Understanding websites and web
servers: 2.4 Understanding Internet –
2.5 Difference between websites and
web server- 2.6 Internet technologies
Overview –2.7 Understanding the
difference between internet and
intranet; HTML and CSS: 2.8 HTML 5.0 ,
2.9 XHTML, 2.10 CSS 3

➢ Rich set of visual elements like image,


2.1 RICH INTERNET video, graphics, etc
➢ It works in real-time, helps business
APPLICATIONS services
➢ Users can know how to use complex
➢ RIA (Rich Internet Application) is apps
defined as a web application that is ➢ Reduce unnecessary page navigations
designed to give the same features and ➢ Responsiveness, interactivity
functions associated with desktop ➢ Ex: Apache Flex, Quick PHP, .NET
applications. framework, JavaFX
➢ HTML is not having much capability
and performance in web apps
➢ Users need desktop type of
interaction from web apps
➢ RIA fulfils this need, user interactivity
➢ It is the 3rd generation of web apps
➢ It runs inside a web browser and does
not need any special software installation
(plug&play)

2.1.1 FEATURES OF RIA

➢ Ability to work on web


➢ GUI logic moved from server to client

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 19


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ Because GUI is executed in browser


➢ GUI state is kept in browser
➢ Because GUI is separated from app logic, it is 2.2 COLLABORATION TOOLS
easy to implement
➢ RIA communicate with servers by exchanging
data, not the GUI code (HTML, CSS, JS) ➢ Collaboration is a process defined by the
➢ Data exchange: XML via HTTP (or) JSON via recursive interaction of knowledge and
HTTP mutual learning between two or more
➢ If server side becomes completely free, then people who are working together
the app logic will become very clear to
understand ➢ Collaboration tools allow a group of
people work together virtually in real-
time over the internet.
2.1.2 BENEFITS OF RIA

➢ Increased productivity, new customers 2.2.1 COLLABORATION TOOLS


➢ Reduced operational costs FEATURE
➢ No installation required
➢ Easy upgrade Easy to use and Clean interface
➢ Available through internet set up.
➢ Client/server balance Secure Permissions control
➢ Asynchronous communication Ability to File storage
➢ Efficiency in network upload
documents
Scalable Document locking
2.1.3 LIMITATIONS OF RIA

➢ Too fast in displaying contents


➢ Maintain balance between HTML and RIA 2.2.2 EXAMPLE TOOLS
➢ GUI logic and app logic might be in
different languages Examples:- Use
➢ Search engines are declining Tool
➢ Complicated to develop apps, what to
Google Docs Upload/modify/retrieve files
cache, what not to.
anytime
➢ Breaks web page paradigm
Dropbox Store/share/sync files online
Blogger Blogging site of google
POSSIBLE QUESTIONS FROM RIA Wordpress Flexible, FOSS, easy blogging
2 marks tool
1. Define RIA[APRIL/MAY 2017] PDFcatch e-books, PDF search engine
2. Features of RIA SlideShare PPT, PDF
share/upload/download
16 marks Youtube Upload/download/view
1. Explain rich internet application videos

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 20


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

Facebook Upload/download/view
micro contents WEBSITE
Twitter Upload/doenload/view
thoughts A collection of web pages which are
grouped together and usually connected
2.2.3 ADVANTAGES OF together in various ways. Often called a
COLLABORATION TOOLS "web site" or simply a "site."

➢ Reduces distance between employees WEB SERVER


➢ Work in same room, together in same
documents A computer that hosts a website on the
➢ No need to send documents back and Internet.
forth between offices
➢ Communication between employees is 2.4 INTERNET
improved
➢ Increases team work and transparency ➢ Internet is a world-wide / global system of
➢ Easy to keep track of projects interconnected computer networks
➢ Easy to generate reports ➢ Internet uses the standard Internet
➢ Team members can be present anywhere Protocol (TCP/IP)
➢ Online chatting ➢ Every computer in internet is identified by
➢ IRC (Internet relay Chat) a unique IP address.
➢ Video conferencing ➢ IP Address is a unique set of numbers
(such as 110.22.33.114) which identifies a
computer‘s location.
➢ A special computer DNS (Domain Name
POSSIBLE QUESTIONS FROM Server) is used to give name to the IP
COLLABORATION TOOLS Address so that user can locate a
2 marks computer by a name.
➢ For example, a DNS server will resolve
1. Define collaboration
a name http://www.tutorialspoint.com to a
2. List some of the collaboration tools
particular IP address to uniquely identify the
computer on which this website is hosted.
2.3 UNDERSTANDING WEBSITES ➢ Internet is accessible to every user all
AND WEB SERVERS over the world.
➢ Internet = Network of networks
WEB PAGE
2.4.1 ESSENTIALS FOR INTERNET
A document which can be displayed in a CONNECTION
web browser such as Firefox, Google
Chrome, Microsoft Internet Explorer or ➢ Computer – DSL, Application software
Edge, or Apple's Safari. These are also often ➢ Connection – Modem, ISP
called "web pages" or just "pages." ➢ Cable – TCP/IP protocol, wireless

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 21


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ Protocols: Set of rules for


2.4.2 WORKING OF INTERNET communication
➢ TCP/IP: to establish a virtual
connection between source and
destination.
➢ 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
2.4.3 EVOLUTION OF INTERNET assigned to a computing device that
➢ It was introduced in 1969 at gets connected to the internet.
ARPANET (Advanced research project ➢ DNS: Domain Name Servers are used
Agency),USA to translate the website names given
➢ It’s prime purpose was to connect by the users into machine
among various bodies of US government understandable IP addresses from a
➢ Initially there were only four nodes database.
(Hosts) ➢ URL: Uniform Resource Locator (URL)
➢ In 1972, ARPANET was spread across is defined as an unique address for the
the globe with 23 nodes file that has to be accessed over the
➢ All the other organizations in internet.
respective countries joined to this ➢ WWW: It is a standard in which all the
network websites are server on the internet via
➢ Around 1990s, Tim Berners Lee and HTTP
O-Reilly had developed WWW and other
internet communication protocols
2.4.5 INTERNET WORKING STYLE
2.4.4 TERMINOLOGIES USED IN ➢ From a web browser, user sends HTTP
INTERNET request to a server
➢ ISP finds the corresponding site from DNS and
➢ Host: A computer that is connected forwards it.
to internet ➢ The request reaches the server after a long
➢ Communication service: Protocols to travel
send and receive data over the internet ➢ Server responds to that request and the reply
such as FTP, HTTP, WWW, VoIP, etc. goes back
➢ ISP: provide internet connectivity to ➢ Any file transmitted in internet will not be
its subscribers. Ex: BSNL send as a whole
➢ Online: When a computer is ➢ All the information will be chopped into
connected to internet chunks (data packets)
➢ Hyperlink: Allows an user to move ➢ Packets have header and footer info,
from one page to another useful for ordering

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 22


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ Reliable
2.4.6 PROTOCOLS USED IN ➢ Heavy weight protocol
INTERNET ➢ Handshaking mechanism available
➢ Error control, flow control, congestion
FTP (File transfer Protocol) control mechanisms
➢ FTP is used to share files among the ➢ Complex, tough to implement
computers in the LAN ➢ Ex: Telnet, SMTP, FTP, e-mail, SSH, HTTP,
➢ It uses two connections (data HTTPS
transfer and control)
➢ FTP data transfer connection uses POP3 (Post Office Protocol Version 3)
port 20 ➢ It is used by local email client
➢ FTP control connection uses port 21 ➢ It uses port no 110
➢ Some familiar commands in FTP are: ➢ Popo3 protocol works only at the
USER, PASS, QUIT, CWD, DELE, LIST, receivers end
RETR, STOR, HELP ➢ The client can receive the emails from the
mailbox
HTTP (Hyper Text Transfer protocol)
➢ Hyper Text Transfer protocol (HTTP) is a UDP(User Datagram Protocol)
stateless protocol for communication, to ➢ Connectionless protocol
transfer information on LAN and WWW ➢ Used for simply transmission of data
➢ It is used to deliver files virtually and ➢ It is an unreliable protocol
other data on WWW
➢ It takes place through TCP/IP sockets DIFFERENCE BETWEEN TCP AND UDP
➢ A browser is a HTTP client – sends HTTP TCP UDP
request Connection oriented Connection less
➢ A web server is a HTTP server – sends (link between the
HTTP reply packets)
➢ It uses port no: 80 (HTTP servers listen to ACK is available No ACK
this port) Reliable Unreliable
Heavy weight protocol Light weight protocol
SNMP (Simple Network Management Handshaking mechanism No handshaking concept
protocol) Error control, flow No control mechanism
➢ It is used to manage a network such as its control, congestion
participants, etc control, etc
➢ Types of participants: Supervisors, Agents Complex, tough to Simple, easy to
➢ SNMP make use of UDP connection for implement implement
transferring the SNMP message Ex: Telnet, SMTP, FTP, e- Ex: VoIP, DHCP, DNS, RIP,
mail, SSH, HTTP, HTTP, SNMP
HTTPS
TCP (Transmission Control Protocol ) POSSIBLE QUESTIONS FROM
➢ Connection oriented (link between the INTERNET
packets)
2 marks
➢ ACK is available

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 23


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

1. Define internet share information or computing services


2. Difference between TCP and UDP within an organization.
16 marks ➢ intranets are restricted to a particular
1. Explain internet technologies [NOV/DEC set of users and are not accessible by the
2016] outside world.
2. Explain internet protocols ➢ For example, many corporations use a
corporate intranet to provide information to
2.5 DIFFERENCE BETWEEN their employees, and run another Internet
site for external users.
WEBSITE AND WEB SERVER ➢ Users within the company can access
both the intranet sites and the Internet, but
Website Web server users outside the company can access only
It is a collection of It is a server on which the company's Internet sites.
web pages web application is
executed 2.7.1 DIFFERENCES BETWEEN
It is a software It is a physical entity
application that has that has unique IP
INTERNET AND INTRANET
unique domain name address
It can host many web It can host many INTERNET INTRANET
pages websites Network of Network of
They communicate They communicate networks, open for computers, open for
with web server with other servers all group of people
such as DB server, File Different sources Limited sources of
server, etc of info info
Web server = It receives request Large no. of Less number of
HTML&CSS + JS+ and gives intranets systems
DHTML corresponding Internet =LAN + Intranet = LAN |
response WAN + MAN WAN | MAN
Ex: Ex: IIS, Apache
https://www.google.c POSSIBLE QUESTIONS FROM
o.in INTERNET AND INTRANET
2 marks
1. Difference between internet and
POSSIBLE QUESTIONS FROM WEBSITE intranet[NOV/DEC 2015]
AND WEBSERVER
2 marks 2.8 BASIC HTML TAGS
1. Difference between website and
webserver[APR/MAY 2017] Tag Description
<!DOCTYPE> Defines the document
2.7 INTRANET type
➢ An intranet is a computer network <html> Defines an HTML
that uses Internet Protocol technology to document

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 24


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

<head> Defines information ➢ It is a formatting language used to


about the document design the contents of a web page
<title> Defines a title for the ➢ Hypertext means, the text which acts
document as a link
➢ Mark up means symbols that are
<body> Defines the document's
used to define structure of the text. It tells
body
browser how to display the text (tags)
<h1> to <h6> Defines HTML headings ➢ Language refers to the syntax
<p> Defines a paragraph ➢ It was invented by Tim-Berners Lee at
<br> Inserts a single line break CERN
<hr> Defines a thematic change in ➢ HTML 1.0 (1991), HTML 2.0 (1995),
the content HTML 3.2 (1997), HTML 4.0 (1999), XHTML
<!--...--> Defines a comment (2000), HTML5 (2014)
<form> Defines an HTML form
for user input 2.8.2 FEATURES OF HTML5
➢ HTML 5.0 is the 5th version of HTML
<input> Defines an input
by W3C (Oct 2014)
control
➢ To support latest multimedia, more
<textarea> Defines a multiline readable
input control (text area) ➢ <audio>, <video>, <canvas>, <svg>
<button> Defines a clickable tags are supported
button ➢ <header>, <footer>, <article>,
<select> Defines a drop-down <section> are supported
list ➢ Number, date, time, calendar, range
<optgroup> Defines a group of are suooprted
related options in a drop-down list ➢ API available for geolocation,
<option> Defines an option in a drag&drop, local storage, etc.
drop-down list ➢ Allows Javascript to run in back side
➢ 2D and 3D drawings supported
<label> Defines a label for an
➢ Need for flash plugin is reduced
<input> element
<fieldset> Groups related
POSSIBLE QUESTIONS FROM RIA
elements in a form
2 marks
<img> Defines an image
1. Define HTML 5
<map> Defines a client-side
image-map
2. Write a HTML code for draw a table

16 marks
2.8.1 HTML 5 1. Explain basic HTML tags[NOV/DEC
2017]
➢ HTML stands for Hyper Text Mark-up 2. Explain Box model
Language 3. Explain about two types of list and
➢ It is used to organize text, graphics, frame set[NOV/ DEC 2017]
audio, video on a web page

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 25


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

4. How to create form in HTML <tr>


[MAY/JUNE 2016] <td>…..</td>
5. Draw a time table with using HTML and </tr>
CSS technique [NOV/DEC 2016] </table>
EXAMPLE HTML TABLE PROGRAM
POSSIBLE QUESTIONS FROM HTML 5 <!DOCTYPE html>
<html>
2 marks
<head>
1. Define HTML 5
<style>
table, th, td
16 marks {
1 Explain basic HTML tags[NOV/DEC border: 1px solid black;
2017] }
</style>
2.9 XHTML </head>
<body>
➢ XHTML stands for EXtensible HyperText
<table style="width:100%">
Markup Language
<tr>
➢ XHTML is almost identical to HTML <th>First Name</th>
➢ XHTML is stricter than HTML <th>Last Name</th>
➢ XHTML is HTML defined as an XML </tr>
application <tr>
➢ XHTML is supported by all major browsers <td>Jill</td>
<td>Smith</td>
</tr>
2.9.1 HTML TABLE
<tr>
➢ An HTML table is defined with the
<td>Eve</td>
<table> tag.
<td>Jackson</td>
➢ Each table row is defined with the
</tr>
<tr> tag.
</table>
➢ A table header is defined with the
</body>
<th> tag.
</html>
➢ By default, table headings are bold
and centered.
O/P
➢ A table data/cell is defined with the
First Name Last Name
<td> tag.
Jill Smith
HTML TABLE SYNTAX Eve Jackson

<table>
<tr> 2.9.2 HTML FRAMES
<th>……</th>
</tr>

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 26


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ HTML frames are used to divide your • Margin


browser window into multiple sections • Border
where each section can load a separate • Padding
HTML document. • Content
➢ A collection of frames in the browser
window is known as a frameset.
➢ The window is divided into frames in a
similar way the tables are organized: into
rows and columns.

SYNTAX OF FRAME
<frameset >
<frame src="top.htm" name="top"/>
</frameset>

EXAMPLE PROGRAM
<!DOCTYPE html>
<html> <!DOCTYPE >
<head> <html lang="en">
<title>HTML Frames</title> <head>
</head> <title>CSS Box Model Example</title>
<frameset rows="16%,84%"/> <style type="text/css">
<frame src="top.htm" name="top"/> .example1 {
<frameset cols="50%,50%"/> width:220px;
<frame src="left.htm" name="left"/> background-color: yellow;
<frame src="right.htm" name="right"/> }
</frameset> .example2 {
</frameset> width:220px;
</html> background-color: yellow;
O/P: margin:40px;
}
top </style>
</head>
left right <body>
<h1>Box Model Example</h1>
<hr style="width: 100%; height: 1px;">
<p class="example1">My Content
2.9.3 BOX MODEL Example 1</p>
➢ The CSS box model is essentially a box that <hr style="width: 100%; height: 1px;
wraps around HTML elements, and it color: blue;">
consists of: margins, borders, padding, and <p class="example2">My Content
the actual content. Example 2</p>
➢ The different parts are: </body>

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 27


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

</html>
✓ File Select boxes
O/P:
✓ Hidden Controls
Box Model Example
✓ Clickable Buttons
✓ Submit and Reset Button
My Content Example 1
The HTML <form> tag is used to create
an HTML form and it has following syntax –

<form action = "Script URL" method =


My Content Example 2 "GET|POST">
form elements like input, textarea etc.
</form>

2.9.4 HTML FORMS 2.9.4.1 TEXT INPUT CONTROL


➢ This control is used for items that require
➢ HTML Forms are required, when you
only one line of user input, such as search
want to collect some data from
boxes or names.
the site visitor.
➢ They are created using HTML <input> tag.
➢ For example, during user registration
yoU would like to collect
PROGRAM
information such as name, email
<!DOCTYPE html>
address, credit card, etc.
<html>
➢ A form will take input from the site
<head>
visitor and then will post it to a
<title>Text Input Control</title>
back-end application
</head>
➢ The back-end application will
<body>
perform
<form >
Required processing on the passed data
First name: <input type = "text" name =
based on defined business logic inside the
"first_name" />
application.
</form>
There are different types of form controls </body>
</html>
that you can use to collect data using HTML
O/P :
form – First name:

✓ Text Input Controls


✓ Checkboxes Controls
✓ Radio Box Controls 2.9.4.2 MULTI LINE TEXT BOX CONTROL
✓ Select Box Controls

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 28


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ This is used when the user is PROGRAM


required to give details that may be longer
than a single sentence. <!DOCTYPE html>
➢ Multi-line input controls are <html>
created using HTML <textarea> tag.
<head>
PROGRAM <title>Checkbox Control</title>
</head>
<!DOCTYPE html>
<html> <body>
<form>
<head> <input type = "checkbox" name =
<title>Multiple-Line Input Control</title> "maths" value = "on"> Maths
</head> <input type = "checkbox" name =
"physics" value = "on"> Physics
<body> </form>
<form> </body>
Description : <br /> </html>
<textarea rows = "5" cols = "50" name = O/P:
"description">
Maths Physics
Enter description here...
</textarea>
2.9.4.4 RADIO BOX CONTROL
</form>
➢ Radio buttons are used when out of
</body>
</html> many options, just one option is required to
be selected.
O/P: ➢ They are also created using HTML
Description: <input> tag but type attribute is set to radio.

PROGRAM
<!DOCTYPE html>
<html>
<head>
<title>Radio Box Control</title>
</head>
2.9.4.3 CHECK BOXCONTROL <body>
➢ Checkboxes are used when more than <form>
one option is required to be selected. <input type = "radio" name = "subject"
➢ They are also created using HTML <input> value = "maths"> Maths
tag but type attribute is set to checkbox.. <input type = "radio" name = "subject"
value = "physics"> Physics
</form>
</body>

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 29


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

</html> ➢ This is also created using the <input>


O/P: element but type attribute is set to file.

Maths Physics
PROGRAM
<!DOCTYPE html>
2.9.4.5 SELECT BOX CONTROL
<html>
<head>
➢ A select box, also called drop down box
<title>File Upload Box</title>
➢ which provides option to list down various
</head>
options in the form of drop down list,
from where a user can select one or more
<body>
options.
<form>
<input type = "file" name =
PROGRAM
<!DOCTYPE html> "fileupload" accept = "image/*" />
<html>
</form>
</body>
<head>
</htm>
<title>Select Box Control</title>
</head>
2.9.5 HTML LISTS
<body>
<form> HTML offers web authors three ways for
<select name = "dropdown"> specifying lists of information. All lists must
<option value = "Maths" contain one or more list elements. Lists may
selected>Maths</option> contain −
<option value =
"Physics">Physics</option> ➢ <ul> − An unordered list. This will list
</select> items using plain bullets.
</form> ➢ <ol> − An ordered list. This will use
</body> different schemes of numbers to list
your items.
</html> ➢ <dl> − A definition list. This arranges
O/P: your items in the same way as they
Maths
are arranged in a dictionary.

2.9.4.6 FILE BOX CONTROL


➢ If you want to allow a user to upload a file
to your web site, you will need to use a
file upload box, also known as a file select 2.9.5.1HTML UNORDERED LISTS
box.

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 30


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

<html>
➢ An unordered list is a collection of related
items that have no special order or <head>
<title>HTML Ordered List</title>
sequence.
</head>
➢ This list is created by using
<body>
HTML <ul> tag. Each item in the list is
<ol>
marked with a bullet. <li>Beetroot</li>
<li>Ginger</li>
PROGRAM
<li>Potato</li>
<!DOCTYPE html>
<li>Radish</li>
<html>
</ol>
</body>
<head>
</html>
<title>HTML Unordered List</title>
</head>
O/P:
<body>
<ul>
2. Beetroot
<li>Beetroot</li>
3. Ginger
<li>Ginger</li>
4. Potato
<li>Potato</li>
5. Radish
<li>Radish</li>
</ul>
2.9.5.3 HTML DEFINITION LISTS
</body>
</html> ➢ HTML and XHTML supports a list style
O/P:
which is called definition lists where
• Beetroot entries are listed like in a dictionary
• Ginger
or encyclopedia.
• Potato
• Radish ➢ The definition list is the ideal way to
present a glossary, list of terms, or
2.9.5.2 HTML ORDERED LISTS
➢ If you are required to put your items in a other name/value list.
numbered list instead of bulleted, then
HTML ordered list will be used. Definition List makes use of following three
➢ This list is created by using <ol> tag.
tags.
➢ The numbering starts at one and is
incremented by one for each successive
ordered list element tagged with <li>. • <dl> − Defines the start of the list

PROGRAM • <dt> − A term


<!DOCTYPE html>

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 31


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

4. Draw a time table with using HTML and


• <dd> − Term definition
CSS technique [NOV/DEC 2016]
• </dl> − Defines the end of the list
2.10 CASCADING STYLE
PROGRAM SHEET(CSS)
<!DOCTYPE html>
<html> ➢ Cascading style sheet is defined as a
<head> style sheet in which, all the style
<title>HTML Definition List</title> information of a web page can be defined.
</head> ➢ CSS handles the look and feel part of a
web page.
<body> ➢ Using CSS, you can control the color of
<dl> the text, the style of fonts, the spacing
<dt><b>HTML</b></dt> between paragraphs, how columns are
<dd>This stands for Hyper Text Markup sized and laid out, what background images
Language</dd> or colors are used, as well as a variety of
<dt><b>HTTP</b></dt> other effects.
<dd>This stands for Hyper Text Transfer ➢ CSS is easy to learn and understand but
Protocol</dd> it provides powerful control over the
</dl> presentation of an HTML document.
</body> ➢ Most commonly, CSS is combined with
</html> the markup languages HTML or XHTML.

O/P: 2.10.1 TYPES


HTML ➢ Inline style sheets
This stands for Hyper Text Markup ➢ Embedded style sheets
Language ➢ External style sheet
HTTP ➢ Imported style sheets
This stands for Hyper Text Transfer
Protocol 2.10.2 EXAMPLE FOR EMBEDDED CSS
<HTML>
POSSIBLE QUESTIONS FROM RIA <HEAD>
2 marks <STYLE TYPE="TEXT/CSS">
1. Write a HTML code for draw a table P{FONT-FAMILY:CALIBRI; }
H3.A{COLOR:BLUE; }
16 marks H3.B{FONT-SIZE:40PX}
</STYLE>
1. Explain Box model </HEAD>
2. Explain about two types of list and frame <BODY>
set[NOV/ DEC 2017] <P>SELECTOR</P>
3. How to create form in HTML [MAY/JUNE <H3 CLASS="A">CLASS SELECTOR 1</H3>
2016] <H3 CLASS="B">CLASS SELECTOR 2</H3>

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 32


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

</BODY> </body>
</HTML> </html>
O/P
O/P : INLINE CSS
POSSIBLE QUESTIONS FROM CSS
CLASS SELECTOR 1 2 marks
CLASS SELECTOR 2 1.Define CSS
16 marks
2.10.4 EXAMPLE FOR EXTERNAL STYLE 1. Explain CSS [NOV/DEC 2017 &
SHEET APRIL/MAY 2015 & NOV/DEC 2016]

EXTERNALCSS.HTML
<HTML>
<HEAD>
<LINK REL="STYLESHEET
TYPE="TEXT/CSS" HREF="EX.CSS">
</HEAD>
2.11 WEB 2.0
<BODY>
➢ Internet has revolutionized the computer
<P CLASS="FORMAT">FORMATTING</P>
and communications, undergoing extreme
<P CLASS="WEIGHT">WEIGHT</P>
make-over
</BODY>
➢ In 1990s, it was used to retrieve
</HTML>
information (Read-Only)
EX.CSS
➢ Around 2004, new web tools came up, to
P.FORMAT
add contents to web
{
➢ People with no programming knowledge
FONT-FAMILY:ARIAL;
can publish an article, photo, video, ppt,
FONT-SIZE:25PX;
pdf, etc.
}
➢ Web has become 2-way communication
P.WEIGHT
medium (R/W)
{
➢ This is called Web 2.0 (bidirectional data
FONT-WEIGHT:BOLD;
traffic)
FONT-STYLE:ITALIC;
➢ It is not the second version of Web
}
➢ It is also called Participatory web (or)
O/P :
Read/Write Web
FORMATTING
➢ Web 2.0 refers to the transition of static
WEIGHT
HTML pages to dynamic web
2.10.5 EXAMPLE FOR INLINE STYLE ➢ XML is used
SHEET ➢ It offers freedom for everybody to
<html> contribute to the web
<head> ➢ Ex: Wikipedia, FB, YouTube, Twitter, etc.
</head>
<body> 2.10.1COMPONENTS OF WEB 2.0
<h2>INLINE CSS</h2>

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 33


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ Blogs
➢ Wikis
➢ Web services

2.10.2 FEATURES OF WEB 2.0


➢ Classify and find required info
➢ Get dynamic contents from the web
➢ Information is shared among all users on
the web
➢ Information is used and reused
➢ Mass participation in discussion forum

2.10.3 TECHNOLOGIES USED IN WEB


2.0
➢ At client side: client side scripting
languages (AJAX, java script)
➢ At server side: server side scripting languages
(PHP, PYTHON, RUBY, etc)

2.10.4 ADVANTAGES OF WEB 2.0


➢ Equal chance to all to
post/view/comment/share
➢ Latest/updated contents
➢ Social networking sites are useful to be in
contact
➢ Write reviews about a product
➢ Digital advertisement

2.10.5 DISADVANTAGES OF WEB 2.0


➢ Increased spam
➢ Information overloaded (everybody posts)
➢ Negative feedback may cause bad
effect on business

POSSIBLE QUESTIONS FROM web 2.0


2 marks
1.Define web 2.0
16 marks
1. Explain web 2.0 [NOV/DEC 2017 ]

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 34


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

CS6501 INTERNET PROGRAMMING


UNIT III CLIENT SIDE AND SERVER
Java Script: 3.1 An introduction to JavaScript–
3.2JavaScript DOM Model-3.3 Date and
Objects,-3.4 Regular Expressions- 3.5
Exception Handling-3.6 Validation-3.7 Built-in
objects-3.8 Event Handling- 3.9 DHTML with
JavaScript. 3.10 Servlets: Java Servlet
Architecture- Servlet Life Cycle- 3.11 Form
GET and POST actions- 3.12 Session Handling-
3.13 Understanding Cookies- 3.14 Installing
and Configuring Apache Tomcat Web Server,
3.15 DATABASE CONNECTIVITY: JDBC
perspectives, JDBC program example – 3.16
JSP: Understanding Java Server Pages- 3.17
JSP Standard Tag Library(JSTL)- 3.18 Creating
HTML forms by embedding JSP code.

oriented an object based


3.1 JAVA SCRIPT programming programming
➢ JavaScript is a programming language language. language.
Java creates JavaScript code run
that can be included on web pages to
application that can on browser only.
make them more interactive. run in a virtual
➢ It is a client-side scripting language machine or browser.
developed by Netscape Objects of Java Objects of JavaScript
Communications Corp. and Sun are class based. are prototype based.
Microsystems. Java program has file JavaScript file has file
extension “.Java” extension “.js”.
Java program uses This requires less
3.1.1 DIFFERENCE BETWEEN JAVA AND
more memory memory
JAVA SCRIPT

JAVA JAVA SCRIPT


Java is an object JavaScript is not

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 35


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

3.1.2 FEATURES OF JAVASCRIPT ➢ Level 2:Platform independent, language


independent
➢ It is useful for page designers ➢ Level 3: Platform independent, language
➢ Light weight, interpreted, embedded in independent .To access dynamically,
HTML update contents, structure, style
➢ Network centric apps
➢ JS = JAVA + HTML 3.2.3 DOM TREE
➢ To develop dynamic and interactive
pages ➢ Documents in DOM are represented using
➢ To validate data, create cookies a tree like structure

POSSIBLE QUESTIONS FROM JAVA ➢ Every element is represented as a node


SCRIPT
2 MARKS ➢ This tree structure is called as DOM tree
1. Define java script
2. Difference between java and java
script
3. Uses or features of java script

1.2DOM MODEL
➢ Document Object Model (DOM) is a
set of platform independent and language
neutral application interface (API)
➢ Its describes how to access and
manipulate the information stored in XML,
XHTML and javascript documents.

3.2.1 DOM USES


3.2.4 METHODS OF DOCUMENT OBJECT
➢ To identify interface and object for
representing and manipulating a document ➢ We can access and change the
contents of document by its methods.
➢ To find behaviour and attributes of
interface & object ➢ The important methods of document
➢ To find relation between interface and object are as follows:
object

3.2.2 LEVELS OF DOM

➢ Level 0 : To access few html elements (by


Netscape in 1990s)
➢ Level 1: To change entire web page
(1998)

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 36


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

3.2.5 EXAMPLE OF DOCUMENT OBJECT


THAT PRINTS NAME WITH WELCOME
MESSAGE.

<script type="text/javascript">
Method Description function printvalue()
{
write("string") writes the given string on the var name=document.form1.name.value;
doucment.
alert("Welcome: "+name);
writeln("string writes the given string on the
}
") doucment with newline
character at the end. </script>

getElementBy returns the element having the <form name="form1">


Id() given id value. Enter Name:<input type="text"
name="name"/>
getElementsB returns all the elements having
yName() the given name value. <input type="button"
onclick="printvalue()" value="print name"/>
</form>
getElementsB returns all the elements having
yTagName() the given tag name. O/P:

getElementsB returns all the elements having


yClassName() the given class name.
POSSIBLE QUESTIONS FROM DOM
2 MARKS
Accessing field value by document object 1. Define DOM
2. Draw the structure of DOM tree
➢ In this example, we are going to get 3. Levels of DOM
the value of input text by user. Here, we are
using document.form1.name.value to get the 16 MARKS
value of name field. 1. Explain DOM and levels DOM with
example program
Here, document →The root element that
represents the html document.
name →The attribute name of the input text.
value →The property, that returns the value
of the input text.
VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 37
VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

3.4 REGULAR EXPRESSION ➢ Javascript allows to search the desired


➢ Regular expressions are patterns used to pattern from the given text using object
match character combinations in strings. RegExp
➢ In JavaScript, regular expressions are also EXAMPLE PROGRAM
objects.
➢ These patterns are used with the exec and <!DOCTYPE html PUBLIC “-//W3C//DTD
test methods of RegExp, and with the XHTML 1.0 Transitional//EN”
match, replace, search, and split methods http://www.w3.org/1999/xhtml11.dtd>
of String. <html xmlns =
http://www.w3.org/1999/xhtml>
3.4.1 METHODS OF REGULAR <head>
EXPRESSION
<script type=”text/javascript”>
Methods that use regular expressions Function test(str)
Method Description
exec A RegExp method that executes {
a search for a match in a string.
Document.write(str);
It returns an array of
information. Var i= new RegExp(“like”);
test A RegExp method that tests for
a match in a string. It returns If(i.test(str))
true or false. alert(“word is found”);
match A String method that executes a
search for a match in a string. It else
returns an array of information or
null on a mismatch. alert(“sorry”);
search A String method that tests for a }
match in a string. It returns the
index of the match, or -1 if the </script>
search fails.
</head>
replace A String method that executes a <body>
search for a match in a string,
and replaces the matched <script type=”text/javascript”>
substring with a replacement Test(“I like programming”);
substring.
split A String method that uses a </script>
regular expression or a fixed
string to break a string into an </body>
array of substrings. </html>
O/P:

3.4.2 USE OF OBJECT RegExp I like programming

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 38


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

Word is found </script>


3.4.3 USE OF SEARCH METHOD </body>

➢ The search method is used to search </html>


for the desired pattern in the given O/P:
input text
the word is found at 2

POSSIBLE QUESTIONS FROM JAVA


EXAMPLE PROGRAM SCRIPT
<!DOCTYPE html PUBLIC “-//W3C//DTD 2 MA
XHTML 1.0 Transitional//EN” RKS
http://www.w3.org/1999/xhtml11.dtd> 1. Def
ine Regular Expression
<html xmlns = 16 marks
http://www.w3.org/1999/xhtml>
1. Exp
<head>
lain Regular Expression with example
<script type=”text/javascript”> program

Function test(str) 3.5EXCEPTION HANDLING


{ ➢ An exception is a problem that arises
during the execution of a program
Document.write(str); ➢ Its breaks the normal flow of the
execution.
Var i= new RegExp(“/like/”);
➢ So these exceptions have to be handled
return i; efficiently in order to avoid program
getting crashed.
}
REASONS FOR EXCEPTION
</script> ➢ User entered invalid input.
➢ File not found
</head> ➢ Network connection lost
<body> ➢ JVM ran out of memory
BENEFITS OF EXCEPTION
<script type=”text/javascript”> ➢ Avoid crashing of applications abruptly.
Var x=Test(“I like programming”); ➢ Various types of errors grouped together.

If(x>0)
3.5.1 THE TRY...CATCH...FINALLY
Document.write(“the word is
found at”+x); STATEMENT
➢ The latest versions of JavaScript added
else
exception handling capabilities.
document.write(“not found”);

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 39


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ JavaScript implements the }


try...catch...finally construct as well as </script>
the throw operator to handle </body>
exceptions. </html>
O/P: Welcome guest!

3.6 VALIDATION
SYNTAX
➢ JavaScript, provides a way to validate
<script type="text/javascript"> form's data on the client's computer
<!-- before sending it to the web server.
➢ Form validation generally performs two
try
functions.
{ ✓ Basic Validation − First of all, the
} form must be checked to make
sure all the mandatory fields are
catch ( e )
filled in.
{
✓ Data Format Validation −
} Secondly, the data that is entered
finally must be checked for correct form
and value.
{
} VALIDATION EXAMPLE PROGRAM

//--> <html>
</script> <body>
EXAMPLE PROGRAM <script>
<!DOCTYPE html>
function validateform(){
<html>
<body> var name=document.myform.name.value;
<p id="demo"></p>
<script> var
try password=document.myform.password.value
{ ;
adddlert("Welcome guest!");
if (name==null || name==""){
}
catch(err) alert("Name can't be blank");
{
document.getElementById("demo"); return false;
innerHTML = err.message;

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 40


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

} ➢ In javascript object is a collection of


properties.
else if(password.length<6){
➢ built-in objects that create the essential
alert("Password must be at least 6 functionality of the language.
characters long."); ➢ JavaScript has many intrinsic objects that
return false; define it as a language.
✓ Math object
}
✓ Number object
} ✓ Date object
✓ Boolean object
</script>
<body> 3.7.1 NUMBER OBJECT

<form name="myform" method="post" ➢ The JavaScript Number object is a


action="http://www.javatpoint.com/javascrip wrapper for numeric values.
tpages/valid.jsp" onsubmit="return SYNTAX
validateform()" > var myNumber = new Number(numeric
Name: <input type="text" value);
name="name"><br/>
Four properties are included in
Password: <input type="password" the Number object:
name="password"><br/> • MAX_VALUE
• MIN_VALUE
<input type="submit" value="register"> • NEGATIVE_INFINITY
• POSITIVE_INFINITY
</form>
</body> EXAMPLE PROGRAM
</html> <!DOCTYPE html PUBLIC “-//W3C//DTD
XHTML 1.0 Transitional//EN”
O/P
http://www.w3.org/1999/xhtml11.dtd>
Name: <html xmlns =
http://www.w3.org/1999/xhtml>
Password:
register <head>
</head>
<body>
3.7 BUILT IN OBJECTS <script type=”text/javascript”>
Document.write(Number.NEGATIVE_INFI
NITY);

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 41


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

</script> </script>
</body>
</body>
</html> </html>
O/P O/P
Infinity 10
3.7.2 MATH OBJECT 3.7.3 DATE OBJECTS
➢ The JavaScript Math object is ➢ The JavaScript Date object provides a
used to perform mathematical functions. way to work with dates and times.
SYNTAX
SYNTAX

var pi = Math.PI; var myDate = new Date();

➢ commonly used methods from math ➢ commonly used methods from date
object object
✓ sqrt(num) ➢ getDate
✓ abs(num) ➢ getDay
✓ ceil(num) ➢ getFullYear
✓ floor(num) ➢ getHours
✓ log(num) ➢ getMilliseconds
✓ pow(a,b) ➢ getMinutes
➢ getMonth
EXAMPLE PROGRAM ➢ getSeconds
➢ getTime
<!DOCTYPE html PUBLIC “-//W3C//DTD ➢ getTimezoneOffset
XHTML 1.0 Transitional//EN”
http://www.w3.org/1999/xhtml11.dtd>
EXAMPLE PROGRAM
<html xmlns =
http://www.w3.org/1999/xhtml> <!DOCTYPE html PUBLIC “-
//W3C//DTD XHTML 1.0
<head> Transitional//EN”
</head> http://www.w3.org/1999/xhtml11.dt
d>
<body>
<html xmlns =
<script type=”text/javascript”> http://www.w3.org/1999/xhtml>
Var num=100; <head>

Document.write(Math.surt(num)); </head>

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 42


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

<body> <body>
<script type=”text/javascript”>
<script type=”text/javascript”>
Var temp = new Boolean(false);
Var my_date = new Date(); Document.write(false);
Document.write(my_date.getDate()); </script>
</body>
Document.write(my_date.getHours());
</html>
Document.write(my_date.getSeconds(
)); O/P
</script> false
</body>
</html> 3.8 EVENT HANDLING
➢ An event handler executes a segment of a
O/P code based on certain events occurring
18 within the application
5 ➢ JavaScript event handers can be divided
32 into two parts:
✓ interactive event handlers
3.7.4 BOOLEAN OBJECT ✓ non-interactive event handlers.
➢ The Boolean object is necessary when ➢ An interactive event handler is the one
attempting to create any sort of logic in that depends on the user interactivity
JavaScript. with the form or the document. For
➢ A Boolean is an object that represents a true example, onMouseOver
or a false value. ➢ non-interactive event handler would be
onLoad, because this event handler would
SYNTAX
automatically execute JavaScript code
var myBoolean = true; ➢ following event handlers available in
EXAMPLE PROGRAM JavaScript

<!DOCTYPE html PUBLIC “-//W3C//DTD on Abort image


XHTML 1.0 Transitional//EN” on Blur select, text, text area
http://www.w3.org/1999/xhtml11.dtd> on Change select, text, textarea
unclick button, checkbox, radio,
<html xmlns = link, reset, submit, area
http://www.w3.org/1999/xhtml> on Error image
on Focus select, text, testarea
<head>
onLoad windows, image
</head> onMouseOver link, area
onMouseOut link, area

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 43


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

onSelect text, textarea <script language="javascript">


onSubmit form
onUnload window function valid(form){ var input=0;
input=document.myform.data.value;
3.8.1 on Abort EVENT if (input<0){
➢ An on Abort event handler executes alert("please input a value that is less than
JavaScript code when the user aborts 0");
loading an image.
}
EXAMPLE PROGRAM
<html> }

< <head> </script>

</head> </head>

<body> <body>

<IMG SRC="reaz.gif" on Abort="alert('You <form name="myform">


stopped the loading the image!')"> <input type="text" name="data" value=""
</body> size=10 onblur="valid(this.form)">

</html> </form>

O/P </body>

You stopped the loading the image </html>


O/P
3.8.2 onBlur EVENT Please input a value that is less than 0
➢ An onBlur event handler executes
3.8.3 on Change EVENT
JavaScript code when input focus leaves
the field of a text, textarea, or a select ➢ The on Change event handler executes
option. JavaScript code when input focus exits the
➢ For windows, frames and framesets field after the user modifies its text.
the event handler executes JavaScript
EXAMPLE PROGRAM
code when the window loses focus.
<html>
EXAMPLE PROGRAM
<head>
<html>
<script language="javascript">
<head>
function valid(form)

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 44


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

{ HTML DHTML
Hypertext Markup Dynamic HTML
var input=0;
Language
input=document.myform.data.value; Static web pages Dynamic web pages
It works slowly upon It works faster on
alert("you have changed the value from 10 to client-server client-server
" + input ); technology technology
No CSS, and no Use CSS, events,
}
dynamic contents methods to create
</script> dynamic pages
No processing at Script is processed at
</head> browser browser
<body> Contents will not be Contents can be
changed changed
<input type="text" name="data" value="10" Simple, less Complex, more
size=10 on change="valid(this.form)"> interactive interactive
</form> Only HTML contents DHTML =
HTML+CSS+JS
</body>
</html>
3.10 SERVLET
O/P
➢ Servlets are defined as simple java programs
You have changed the value from 10 to 0
that are dynamically loaded and run on JVM
of web servers, to respond to the requests
3.9 DHTML WITH JAVASCRIPT from the clients
➢ It acts as middle layer between browser and
server
➢ DHTML stands for Dynamic HTML
➢ To develop sites with secure access, interact
➢ DHTML is NOT a language or a web
with DB, maintain unique session info of each
standard.
client
➢ DHTML is a TERM used to describe the
➢ Used with HTTP, hence called HttpServlet
technologies used to make web pages
➢ It makes use of two packages:
dynamic and interactive.
✓ Javax.servlet
➢ To most people DHTML means the
combination of HTML, JavaScript, DOM,
and CSS.
SERVLET CONTAINER
➢ The server that executes a servlet is called as
servlet container or servlet engine
3.9.1 DIFFERENCE BETWEEN HTML AND ➢ Browsers send an HTTP request to server,
DHTML which in turn sends to servlet container
➢ Servlet container receives the request from
the server, processes appropriate servlet,

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 45


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

sends back request instance of the servlet.

✓ javax.servlet.http

3.10.1 SERVLET API LIFE CYCLE METHODS


Servlet API life cycle methods –
➢ init()
The web container calls the init method only once
after creating the servlet instance. The init method is
used to initialize the servlet
➢ service(): method called directly by Fig servlet architecture
server when an HTTP request is received;
➢ destroy(): called when server shuts ADVANTAGES
down 1. better performance: because it creates
a thread for each request not process.
2. Portability: because it uses java
language.
3. Robust: Servlets are managed by JVM
so we don't need to worry about memory
leak, garbage collection etc.
4. Secure: because it uses java language.

EXAMPLE PROGRAM

Fig: servlet life cycle import java.io.*;


import javax.servlet.*;
import javax.servlet.http.*;
3.10.2 ARCHITECTURE DIGRAM public class HelloWorld extends
HttpServlet
➢ First the HTTP requests coming to the server {
are delegated to the servlet container. public void init()
➢ The servlet container loads the servlet before {
invoking the service() method. }
➢ Then the servlet container handles multiple public void doGet(HttpServletRequest
requests by spawning multiple threads, each request, HttpServletResponse response)
thread executing the service() method of a single throws ServletException, IOException

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 46


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

{ HelloWorld.class file in the same


response.setContentType("text/html"); directory.
PrintWriter out = response.getWriter();
out.println("<html><body>helloworld</b
ody></html>"); 3.11 GET AND POST METHOD
} ➢ HTTP request makes use of two
public void destroy() commonly used methods such as GET and
{ POST
}
3.11.1 DIFFERENCE BETWEEN DO GET
}
AND DO POST METHODS
O/P
helloworld HTTP GET request HTTP POST request
doGet() method is doPost() method is
3.10.3 COMPILING SERVLET used used
URL string displays URL string does not
➢ Let us put above code if request submitted by display request
HelloWorld.java file and put this file in the user submitted by user
C:\ServletDeveloper To download info To upload info from
➢ add these directories as well in from server server
CLASSPATH. No effect on data Has effect on data
➢ Assuming your environment is setup Page can be Page cannot be
properly, go in ServletDeveloper directory bookmarked bookmarked
and compile HelloWorld.java as follows: $ page can be cached, Page cannot be
javac HelloWorld.java saved in history cached, cannot be
➢ If the servlet depends on any other saved in history
libraries, you have to include those JAR Only ASCII characters Any character is
files on your CLASSPATH as well. allowed allowed
➢ I have included only servlet-api.jar Unsafe More secure
JAR file because I'm not using any other
library in Hello World program.
➢ This command line uses the built-in 3.11.2 HTTP GET
javac compiler that comes with the Sun
➢ Query string is part of URL
Microsystems Java Software Development
Kit (JDK). ➢ Length of query string may be limited
➢ For this command to work properly,
you have to include the location of the
Java SDK that you are using in the PATH
environment variable.
➢ If everything goes fine, above
compilation would produce

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 47


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

HTML PROGRAM {
Login.html PrintWriter out = resp.getWriter();
<html> out.println("<html><body>");
<body> out.println(msg);
<form action="login" method="get"> out.println("</body></html>");
<table> }
<tr> <td>User</td> <td><input }
name="user" /></td> </tr> <tr> ➢ We compilate this Servlet and we include
<td>password</td> <td><input name="password" LoginServlet.class in the folder /WEB-
/></td> </tr> INF/classes. We modify web.xml to link
</table> /login with this Servlet.
<input type="submit" />
</form>
</body> WEB.XML
</html>
➢ create a Servlet which receives the request <web-app>
in /login , which is the indicated direction in <servlet>
the action attribute of the tag <form> of <servlet-name>hello</servlet-name>
login.html <servlet-class> hello </servlet-class>
SERVLET PROGRAM </servlet>
import java.io.*; <servlet-mapping> <servlet-name>login-
import javax.servlet.*; servlet</servlet-name> <url-pattern>/login</url-
import javax.servlet.http.*; pattern>
public class LoginServlet extends HttpServlet </servlet-mapping>
{ </web-app>
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws O/P
ServletException, IOException
{
String user = req.getParameter("user");
String pass = req.getParameter("password");
if ("balamurugan".equals(user) &&
"bala1234".equals(pass))
{
response(resp, "login ok");
}
else
{
response(resp, "invalid login");
}
}
private void response(HttpServletResponse resp,
String msg) throws IOException 3.11.3 HTTP POST

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 48


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ Query string is sent as body of HTTP if ("balamurugan".equals(user) &&


request "bala1234".equals(pass))
➢ Length of query string is unlimited {
➢ Most browsers will warn you if they are response(resp, "login ok");
about to resubmit POST data to avoid }
duplicate updates else
{
HTML PROGRAM response(resp, "invalid login");
<html> }
<body> }
<form action="login" method="post"> private void
<table> response(HttpServletResponse resp,
<tr><td>User</td> <td><input String msg) throws IOException
name="user" /></td></tr> {
<tr><td>password</td> <td> PrintWriter out = resp.getWriter();
<input name="password" /></td></tr> out.println("<html><body>");
</table> out.println(msg);
<input type="submit" /> out.println("</body></html>");
</form>
</body> }
</html> O/P

SERVLET PROGRAM
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends
HttpServlet
3.12 SESSION HANDLING
{
protected void
➢ Session simply means a particular interval
doPost(HttpServletRequest req, of time.
HttpServletResponse resp) throws ➢ Session Tracking is a way to maintain
ServletException, IOException state (data) of an user. It is also known
{ as session management in servlet.
String user = req.getParameter("user"); ➢ Http protocol is a stateless so we need to
String pass = maintain state using session tracking
techniques.
req.getParameter("password");

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 49


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ Each time user requests to the server, request.


server treats the request as the new ➢ In cookies technique, we add cookie with
request. response from the servlet.
➢ So we need to maintain the state of an ➢ So cookie is stored in the cache of the browser.
user to recognize to particular user. ➢ After that if request is sent by the user, cookie is
added with request by default. Thus, we
HTTP is stateless that means each request is recognize the user as the old user.
considered as the new request. It is shown in
the figure given below: Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the
browser.
2. Only textual information can be set in Cookie
object.
3.12.1 Session Tracking Techniques
Gmail uses cookie technique for login. If you disable
There are four techniques used in
Session tracking:
the cookie, gmail won't work.
Hidden Form Fields

1. Cookies

2. Hidden Form Field

3. URL Rewriting

4. HttpSession

3.12.2 Cookies in Servlet


3.12.3 URL Rewriting
➢ A cookie is a small piece of information that is
persisted between the multiple client requests.
➢ A cookie has a name, a single value, and optional
attributes such as a comment, path and domain
qualifiers, a maximum age, and a version
number.
How Cookie works
➢ By default, each request is considered as a new

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 50


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

or visit to a Web site and to store


information about that user.
➢ The servlet container uses this interface
to create a session between an HTTP
client and an HTTP server.
➢ You would get HttpSession object by
calling the public method getSession() of
HttpServletRequest, as below:
➢ You can append some extra data on the
end of each URL that identifies the SYNTAX
session, and the server can associate that
HttpSession session =
session identifier with data it has stored
request.getSession();
about that session.
➢ URL rewriting is a better way to maintain EXAMPLE PROGRAM
sessions and works for the browsers when
they don't support cookies import java.io.*;
➢ but here drawback is that you would have
import javax.servlet.*;
generate every URL dynamically to assign
a session ID though page is simple static
import javax.servlet.http.*;
HTML page.
import java.util.*;
THE HTTP SESSION OBJECT
public class SessionTracker extends
HttpServlet

public void doGet(HttpServletRequest


request, HttpServletResponse response)
➢ Apart from the above mentioned three throws ServletException, IOException
ways, servlet provides HttpSession
Interface which provides a way to identify {
a user across more than one page request

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 51


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

HttpSession session = visitCount =


request.getSession(true); (Integer)session.getAttribute(visitCountKe
y);
Date createTime = new
Date(session.getCreationTime()); visitCount = visitCount + 1;

Date lastAccessTime=new userID =


Date(session.getLastAccessedTime()); (String)session.getAttribute(userIDKey);

String title = "Welcome Back to my }


website";
session.setAttribute(visitCountKey,
Integer visitCount = new Integer(0); visitCount);

String visitCountKey = new response.setContentType("text/html");


String("visitCount");
PrintWriter out = response.getWriter();
String userIDKey = new String("userID");
out.println("<html><body><center>");
String userID = new String("ABCD");
out.println("Session Information");
if (session.isNew())
out.println("<table border=\"1\"><tr>");
{
out.println("<th>Session
title = "Welcome to my website"; info</th><th>value</th></tr>");

session.setAttribute(userIDKey, userID); out.println("<tr><td>Session ID</td><td>


+ session.getId() + </td></tr>");
}
out.println("<tr><td>Creation
else Time</td><td> + createTime +
</td></tr>");
{

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 52


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

out.println("<tr><td>Time of Last
Types of Cookie
Access</td><td> + lastAccessTime+ There are 2 types of cookies in servlets.
</td></tr>"); 1. Non-persistent cookie
2. Persistent cookie
out.println("<tr><td>User ID</td><td> +
Advantage of Cookies
userID+ </td></tr>"); 1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
out.println("<tr><td>Number of
visits</td><td> + visitCount+ </td></tr>"); Disadvantage of Cookies
1. It will not work if cookie is disabled from the
browser.
out.println("</table></body></html>"); 2. Only textual information can be set in Cookie
object.
}
Gmail uses cookie technique for login. If you disable
} the cookie, gmail won't work.
Hidden Form Fields
O/P

3.13.1 HTML PROGRAM

<html>

3.13 COOKIES
➢ By default, each request is considered as a <head>
new request.
➢ In cookies technique, we add cookie with <title>Cookies Example in Servlets</title>
response from the servlet.
</head>
➢ So cookie is stored in the cache of the
browser.
➢ After that if request is sent by the user,
cookie is added with request by default. <body bgcolor=wheat>
Thus, we recognize the user as the old
user.

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 53


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

<center> {
<h1>Cookies Example in Java</h1> String fname=req.getParameter("fname");
String lname=req.getParameter("lname");
<form
action="http://localhost:8080/cookies/co"
Cookie f=new Cookie("first_name",fname);
method="Post">
Cookie l=new Cookie("last_name",lname);
First name: <input type="text"
name="fname">
Last name: <input type="text" res.addCookie(f);
name="lname">
res.addCookie(l);
<input type="submit"value="SUBMIT">
</form>

res.sendRedirect("http://localhost:8080/cook
ies/st");
</center>
}
}
</body>
GETCOOKIE.JAVA
import javax.servlet.*;
</html>
import javax.servlet.http.*;
3.13.2 SERVLET PROGRAMS
import java.io.*;
COOKIEEXAMPLE.JAVA
public class GetCookie extends HttpServlet
import javax.servlet.*;
{
import javax.servlet.http.*;
public void doGet(HttpServletRequest
import java.io.*; req,HttpServletResponse res) throws
public class CookieExample extends ServletException,IOException
HttpServlet {
{ PrintWriter pw=res.getWriter();
public void doPost(HttpServletRequest
req,HttpServletResponse res) throws
ServletException,IOException pw.println("<h1>");

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 54


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

Cookie[] c=req.getCookies(); 3.14 APACHE TOMCAT


for(Cookie k:c) ➢ It is an application server or web server
or servlet container developed by the
{ Apache Software Foundation (ASF) and
pw.println(k.getValue()); released under the Apache License
version 2.
}
➢ HTTP web servers provide an
pw.println("</h1>"); environment for Java code to run in.
} ➢ It includes tools for configuration and
management, but can also be configured
} by editing XML configuration files.
O/P ➢ Most of the modern Java web
frameworks are based on servlets and
JavaServer Pages and can run on Apache
Tomcat, for example Struts, JavaServer
Faces, Spring, etcetera.
How to Install Tomcat 7

There are certain steps we must follow for


configuring Apache Tomcat 7.

Click on the SUBMIT then,


Step 1

Download and Install Tomcat

Go to
http://tomcat.apache.org/download-
70.cgi then go to the Binary
Distribution/Core/ and download the
"zip" package
Step 2

Check the installed directory to ensure it


contains the following sub-directories:

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 55


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

bin folder "Start" buttonthen select "Control Panel"


logs folder / "System" / "Advanced system settings".
webapps folder Then switch to the "Advanced" tab and
work folder select "Environment Variables" / "System
temp folder Variables" then select "New" (or "Edit" for
conf folder modification). In "Variable Name", enter
lib folder "JRE_HOME". In "Variable Value", enter
Step 3 your JRE installed directory (e.g.,
"C:\Program Files\Java\jre7\").
Now, we need to create an Environment Step 4
Variable JAVA_HOME.
Configure Tomcat Server
We need to create an environment
variable called "JAVA_HOME" and set it to The configuration files of the Apache
our JDK installed directory. Tomcat Server are located in the "conf"
sub-directory of our Tomcat installed
To create the JAVA_HOME environment directory, for example
variable in Windows XP/Vista/7 we need "E:\myserver\tomcat7.0.40\conf". There
to push the "Start" button then select are 4 configuration XML files:
"Control Panel" / "System" / "Advanced
system settings". Then switch to the context.xml file
"Advanced" tab and select "Environment tomcat-users.xml file
Variables" / "System Variables" then server.xml file
select "New" (or "Edit" for modification). web.xml file
In "Variable Name", enter "JAVA_HOME". Before proceeding, make a BACKUP of the
In "Variable Value", enter your JDK configuration files.
installed directory (e.g., "c:\Program
Files\Java\jdk1.7.0_{xx}"). Step 4(a) "conf\web.xml"; Enabling a
For ensuring that it is set correctly, we Directory Listing
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
Sometimes we need to set JRE_HOME
also. So for creating JRE_HOME we need
to use the same procedure. Push the

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 56


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

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:
In that we set reloadable="true" to the
<Context> element to enable automatic
Step 4(b) "conf\server.xml file"; set the
reload after code changes.
TCP Port Number
Add reloadable="true" as in the following:

<Context reloadable="true">
......
</Context> Like

Step 4(d) (Optional) "conf\tomcat-


users.xml"

Open the file "server.xml" in a text editor.


It is used to manage Tomcat by adding the
highlighted lines, inside the <tomcat-
The default port number of Tomcat is
users> elements.
8080. Now we need to change the TCP
port number for Tomcat, since the same
In that we can add a password and
port number can be used by other servers
username as an optional step.
like SQL Server. We may choose any
number between 1024 and 65535. We
shall choose 9999 in this article.

Step 5
Locate the following lines, and change
port="8080" to port="9999". Like:
Now, start the tomcat server

<Connector port="9999"
Executable programs and scripts are kept
protocol="HTTP/1.1" Like
in the "bin" sub-directory of the Tomcat
Step 4(c) "conf\context.xml"; Enabling
installed directory, e.g.,
Automatic Reload
"E:\myserver\tomcat7.0.40\bin".

Step 5(a)

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 57


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

Start Server Open a browser then enter the URL


"http://localhost:9999" to access the
Tomcat server's welcome page.

Launch a command shell. Set the current


directory to "<TOMCAT_HOME>\bin" like
E:\myserver\tomcat7.0.40\bin, and run
"startup.bat" as follows:
After that a new Tomcat console window If we get this type of page then it means
appears. Read the messages on the we are done.
console. Look out for the Tomcat's port
number (double check that Tomcat is Fig-7.jpg
running on port 9999).......
Now try the URL
We saw a figure like: http://localhost:9999/examples to view
JSP and servlet examples.

Step 5(c) How to Shutdown Server

We can stop the server using one of the


following:

Press ctrl-c on the Tomcat console; or


Run
"<TOMCAT_HOME>\bin\shutdown.bat"
script:
// Change the current directory to
Tomcat's "bin"
> e: // Change the current drive
e:\> cd E:\myserver\tomcat7.0.40\bin //
Change Directory to YOUR Tomcat's "bin"
Step 5(b) Access the Server directory
// Shutdown the server
E:\myserver\tomcat7.0.40\bin> shutdown

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 58


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

3.15 JDBC
➢ JDBC is defined as an API that provides
industry standard and database
connectivity between java apps and
database servers
➢ It is a framework that contains many
classes, interfaces, exceptions, using
which java apps can send SQL statement
to database to store and retrieve data
Uses
➢ It helps client to store and retrieve data
to databases
3.15.2 COMMON JDBC COMPONENTS
➢ It helps client to update databases
Types The JDBC API provides the following
➢ JDBC-ODBC bridge driver interfaces and classes −
➢ Partial java driver ➢ DriverManager: This class manages a list of
➢ Pure java driver for accessing database drivers. establish a database
Connection.
middleware ➢ Driver: This interface handles the
➢ Pure java driver for direct DB access communications with the database server.
You will interact directly with Driver objects
3.15.1 JDBC ARCHITECTURE very rarely.
➢ Connection: This interface with all methods
The JDBC API supports both two-tier and
for contacting a database. The connection
three-tier processing models for database
object represents communication context, i.e.,
access but in general, JDBC Architecture
all communication with database is through
consists of two layers −
connection object only.
➢ JDBC API: This provides the application-
➢ Statement: You use objects created from this
to-JDBC Manager connection.
interface to submit the SQL statements to
➢ JDBC Driver API: This supports the JDBC
the database.
Manager-to-Driver Connection. ➢ ResultSet: These objects hold data retrieved
from a database after you execute an SQL
➢ The JDBC API uses a driver manager and query using Statement objects.
database-specific drivers to provide ➢ SQLException: This class handles any errors
transparent connectivity to heterogeneous that occur in a database application.
databases. ➢ Structured Query Language (SQL) is a
Following is the architectural diagram, standardized language that allows you to
which shows the location of the driver perform operations on a database, such as
creating entries, reading content, updating
manager with respect to the JDBC drivers
content, and deleting entries.
and the Java application ➢ SQL is supported by almost any database you

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 59


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

will likely use, and it allows you to write SQL> SELECT column_name, column_name, ...
database code independently of the FROM table_name
underlying database. Example
➢ Create Database The following SQL statement selects the age,
The CREATE DATABASE statement is used for first and last columns from the Employees
creating a new database. The syntax is − table, where id column is 100 −
CREATE DATABASE DATABASE_NAME; SQL> SELECT first, last, age
Example FROM Employees
The following SQL statement creates a WHERE id = 100;
Database named EMP − ➢ UPDATE Data
CREATE DATABASE EMP; The UPDATE statement is used to update data.
➢ Drop Database The syntax for UPDATE is −
The DROP DATABASE statement is used for SQL> UPDATE table_name
deleting an existing database. The syntax is − SET column_name = value, column_name =
SQL> DROP DATABASE DATABASE_NAME; value, ...
Note: To create or drop a database you should Example
have administrator privilege on your database The following SQL UPDATE statement changes
server. Be careful, deleting a database would the age column of the employee whose id is
loss all the data stored in the database. 100 −
The DROP TABLE statement is used for SQL> UPDATE Employees SET age=20 WHERE
deleting an existing table. The syntax is − id=100;
DROP TABLE table_name; DELETE Data
Example The DELETE statement is used to delete data
The following SQL statement deletes a table from tables. The syntax for DELETE is −
named Employees − SQL> DELETE FROM table_name WHERE
DROP TABLE Employees; conditions;
➢ INSERT Data SQL> DELETE FROM Employees WHERE
id=100;
The syntax for INSERT, looks similar to the 3.15.3 BUILDING A JDBC
following, where column1, column2, and so on
represents the new data to appear in the ➢ Import the packages: Requires that you
respective columns − include the packages containing the JDBC
SQL> INSERT INTO table_name VALUES classes needed for database programming.
(column1, column2, ...); Most often, using import java.sql.* will suffice.
Example ➢ Register the JDBC driver: Requires that you
The following SQL INSERT statement inserts a initialize a driver so you can open a
new row in the Employees database created communication channel with the database.
earlier − ➢ Open a connection: Requires using the
SQL> INSERT INTO Employees VALUES (100, DriverManager.getConnection() method to
18, 'Zara', 'Ali'); create a Connection object, which represents
➢ SELECT Data a physical connection with the database.
The SELECT statement is used to retrieve data ➢ Execute a query: Requires using an object of
from a database. The syntax for SELECT is − type Statement for building and submitting an

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 60


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

SQL statement to the database. System.out.print("ID: " + id);


➢ Extract data from result set: Requires that you System.out.print(", Age: " + age);
use the appropriate ResultSet.getXXX() System.out.print(", First: " + first);
method to retrieve the data from the result System.out.println(", Last: " + last);
set. }
➢ Clean up the environment: Requires explicitly rs.close();
closing all database resources versus relying stmt.close();
on the JVM's garbage collection. conn.close();
}
➢ EXAMPLE PROGRAM catch(SQLException se)
import java.sql.*; {
public class FirstExample se.printStackTrace();
{ }
static final String JDBC_DRIVER = catch(Exception e)
"com.mysql.jdbc.Driver"; {
static final String DB_URL = e.printStackTrace();
"jdbc:mysql://localhost/EMP"; }
static final String USER = "username"; finally
static final String PASS = "password"; {
public static void main(String[] args) try
{ {
Connection conn = null; if(stmt!=null) stmt.close();
Statement stmt = null; }
try catch(SQLException se2)
{ {
Class.forName("com.mysql.jdbc.Driver"); }
System.out.println("Connecting to try
database..."); {
conn = if(conn!=null) conn.close();
DriverManager.getConnection(DB_URL,USER,PAS }
S); catch(SQLException se)
System.out.println("Creating statement..."); {
stmt = conn.createStatement(); se.printStackTrace();
String sql; }
sql = "SELECT id, first, last, age FROM }
Employees"; System.out.println("Goodbye!");
ResultSet rs = stmt.executeQuery(sql); }
while(rs.next() }
{ O/P
int id = rs.getInt("id"); C:\>javac FirstExample.java
int age = rs.getInt("age"); Connecting to database...
String first = rs.getString("first"); Creating statement...
String last = rs.getString("last"); ID: 100, Age: 18, First: Zara, Last: Ali

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 61


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

ID: 101, Age: 25, First: Mahnaz, Last: Fatma JSP makes use of No custom tags
ID: 102, Age: 30, First: Zaid, Last: Khan custom tags
ID: 103, Age: 28, First: Sumit, Last: Mittal
3.16.1 ARCHITECTURE

➢ The web server needs a JSP engine ie.


container to process JSP pages.
➢ The JSP container is responsible for
3.16 JSP intercepting requests for JSP pages
➢ Java Server Pages is a kind of server side ➢ A JSP container works with the Web
scripting language that enables user to server to provide the runtime
embed java code with HTML elements for environment and other services a JSP
the creation of dynamic, platform-
needs.
independent method for building web
➢ It knows how to understand the special
apps
➢ JSP = Java + HTML + servlet elements that are part of JSPs.
➢ 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 3.16.2 JSP PROCESSING
JSP tags, most of which start with <% and end
with %>. The following steps explain how the web
➢ JSP, you can collect input from users through server creates the web page using JSP:
web page forms, present records from a
➢ As with a normal page, your browser
database or another source, and create web
sends an HTTP request to the web server.
pages dynamically.
➢ The web server recognizes that the HTTP
request is for a JSP page and forwards it
DIFFERENCE BETWEEN JSP AND SERVLET to a JSP engine. This is done by using the
URL or JSP page which ends with .jsp
JSP Servlet
instead of .html.
JSP = Java inside Servlet = HTML inside
HTML Java ➢ The JSP engine loads the JSP page from
It generates dynamic It generates dynamic disk and converts it into a servlet content.
web contents web pages
In MVC, JSP acts as a In MVC, servlet acts as ➢ This conversion is very simple in which all
view controller template text is converted to println( )

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 62


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

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 3.16.3 LIFE CYCLE OF A JSP PAGE
response to your browser in terms of static
HTML content. The JSP pages follows these phases:
➢ Finally web browser handles the
dynamically generated HTML page inside ➢ Translation of JSP Page
the HTTP response exactly as if it were a ➢ Compilation of JSP Page
static page. ➢ Classloading (class file is loaded by the
classloader)
The following are the paths followed by a JSP ➢ Instantiation (Object of the Generated
✓ Compilation Servlet is created).
✓ Initialization ➢ Initialization ( jspInit() method is invoked
✓ Execution by the container).
✓ Cleanup ➢ Reqeust processing ( _jspService() method
is invoked by the container).
The four major phases of JSP life cycle are ➢ Destroy ( jspDestroy() method is invoked
very similar to Servlet Life Cycle and they are
by the container).
as follows:
3.16.4 RUNNING JSP PAGE

Follow the following steps to execute this JSP


page:
➢ Start the server
➢ put the jsp file in a folder and deploy on the
server
➢ visit the browser by the url
http://localhost:portno/contextRoot/jspfile
e.g.
http://localhost:8888/myapplication/index.jsp

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 63


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ MVC stands for Model View and Controller. It


is a design pattern that separates the business
logic, presentation logic and data.
➢ Controller acts as an interface between View
and Model. Controller intercepts all the
incoming requests.
➢ Model represents the state of the application
i.e. data. It can also have business logic.
➢ View represents the presentaion i.e. UI(User
Interface).

3.17 JSTL
➢ Java Standard Tags Library represents set of
tags to simplify JSP development

➢ J2EE is used for server side programming using


JAVA and JSTL (a compoment of J2EE web app
development

➢ It is useful in performing condition execution,


loop execution, data procession, etc
<%@ taglib
➢ Embed logic in JSP page without java code uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %>
Advantage of JSTL <html>
<head>
➢ Fast Developement JSTL provides many tags
<title>Tag Example</title>
that simplifies the JSP.
</head>
➢ Code Reusability We can use the JSTL tags in <body>
various pages. <c:out value="${'Welcome to
javaTpoint'}"/>
➢ No need to use scriptlet tag It avoids the use
</body>
of scriptlet tag.
</html>
3.17.1 JSTL TAGS O/P

➢ The syntax used for including JSTL core library


in your JSP is:

<%@ taglib
uri="http://java.sun.com/jsp/jstl/core" prefix="c"
%>

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 64


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

It returns the subset of string after a


specific substring.
fn:substringBefore()
It returns the subset of string before a
specific substring.
fn:length()
JSTL Function Tags It returns the number of characters inside
➢ The JSTL function provides a number of a string, or the number of items in a
standard functions, most of these collection.
functions are common string fn:replace()
manipulation functions. It replaces all the occurrence of a string
<%@ taglib with another string sequence.
uri="http://java.sun.com/jsp/jstl/function PROGRAM
s" prefix="fn" %> <%@ taglib
fn:contains() uri="http://java.sun.com/jsp/jstl/core"
It is used to test if an input string prefix="c" %>
containing the specified substring in a <%@ taglib
program. uri="http://java.sun.com/jsp/jstl/function
fn:indexOf() s" prefix="fn" %>
It returns an index within a string of first <html>
occurrence of a specified substring. <head>
fn:trim() <title>JSTL fn:length()
It removes the blank spaces from both the example</title>
ends of a string. </head>
fn:split() <body>
It splits the string into an array of <c:set var="str1" value="This is first
substrings. string"/>
fn:toLowerCase() <c:set var="str2" value="Hello"/>
It converts all the characters of a string to Length of the String-1 is:
lower case. ${fn:length(str1)}<br>
fn:toUpperCase() Length of the String-2 is: ${fn:length(str2)}
It converts all the characters of a string to </body>
upper case. </html>
fn:substring()
It returns the subset of a string according
to the given start and end position.
fn:substringAfter()

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 65


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

<head> <title>fmt:formatDate</title>
</head>
<body>
<h2>Different Formats of the
Date</h2>
<c:set var="Date" value="<%=new
java.util.Date()%>" />
JSTL Formatting tags <p> Formatted Time :
➢ The formatting tags provide support for <fmt:formatDate type="time"
message formatting, number and date value="${Date}" />
formatting etc. </p>
➢ The url for the formatting tags is <p> Formatted Date :
http://java.sun.com/jsp/jstl/fmt and <fmt:formatDate type="date"
prefix is fmt. value="${Date}" />
➢ The JSTL formatting tags are used for </p>
internationalized web sites to display and <p> Formatted Date and Time :
format text, the time, the date and <fmt:formatDate type="both"
numbers. value="${Date}" />
<%@ taglib </p>
uri="http://java.sun.com/jsp/jstl/fmt" </body></html>
prefix="fmt" %> Formatting Tags
Descriptions fmt:timeZone
It specifies a parsing action nested in its
body or the time zone for any time
formatting. fmt:formatNumber
It is used to format the numerical value
JSTL XML tags
with specific format or precision.
➢ The JSTL XML tags are used for providing a
fmt:parseDate
JSP-centric way of manipulating and
It parses the string representation of a
creating XML documents.
time and date. fmt:formatDate
➢ XML Tags Descriptions x:out
It formats the time and/or date using the
Similar to <%= ... > tag, but for XPath
supplied pattern and styles.
expressions.
<%@ taglib prefix="c"
➢ x:parser It is used for parse the XML data
uri="http://java.sun.com/jsp/jstl/core"%>
specified either in the tag body or an
<%@ taglib prefix="fmt"
attribute.
uri="http://java.sun.com/jsp/jstl/fmt"%>
➢ x:set
<html>

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 66


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

It is used to sets a variable to the value of <x:out


an XPath expression. select="$output/vegetables/vegetable[1]/
➢ x:if It is used for evaluating the test XPath name" /><br>
expression and if it is true, it will <b>Price of the Potato is</b>:
processes its body content. <x:out
➢ x:transform select="$output/vegetables/vegetable[2]/
It is used in a XML document for providing price" />
the XSL(Extensible Stylesheet Language) </body> </html>
transformation.
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"
%>
<%@ taglib prefix="x"
uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<body> JSTL SQL TAG
<h2>Vegetable Information:</h2> ➢ The JSTL sql tags provide SQL support.
<c:set var="vegetable"> ➢ The url for the sql tags is
<vegetables> http://java.sun.com/jsp/jstl/sql and prefix
<vegetable> is sql. SQL Tags Descriptions
<name>onion</name> sql:setDataSource
<price>40/kg</price> It is used for creating a simple data source
</vegetable> suitable only for prototyping. sql:query
<vegetable> It is used for executing the SQL query
<name>Potato</name> defined in its sql attribute or the body.
<price>30/kg</price> sql:update
</vegetable> It is used for executing the SQL update
<vegetable> defined in its sql attribute or in the tag
<name>Tomato</name> body. sql:transaction
<price>90/kg</price> It is used to provide the nested database
</vegetable> action with a common connection.
</vegetables> <%@ page
</c:set> import="java.io.*,java.util.*,java.sql.*"%>
<x:parse xml="${vegetable}" <%@ page
var="output"/> import="javax.servlet.http.*,javax.servlet.
<b>Name of the vegetable is</b>: *" %>

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 67


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

<%@ taglib
uri="http://java.sun.com/jsp/jstl/core"
prefix="c"%>
<%@ taglib
uri="http://java.sun.com/jsp/jstl/sql"
prefix="sql"%>
<html>
<body>
<sql:setDataSource var="db"
driver="com.mysql.jdbc.Driver" 3.18 CREATING HTML FORMS BY
url="jdbc:mysql://localhost/test" EMBEDDING JSP CODE
user="root" password="1234"/>
<sql:query dataSource="${db}" var="rs">
SELECT * from Students; JSP Scripting elements
</sql:query> ➢ Scripting elements provides the ability to
<table border="2" width="100%"> insert java code inside the jsp.
<tr> ✓ scriptlet tag
<th>Student ID</th> ✓ expression tag
<th>First Name</th> ✓ declaration tag
<th>Last Name</th>
<th>Age</th> 3.18.1 JSP SCRIPTLET TAG
</tr> A scriptlet tag is used to execute java source
<c:forEach var="table" code in JSP
items="${rs.rows}">
<tr> Example
<td><c:out value="${table.id}"/></td> In this example, we have created two files
<td><c:out index.html and welcome.jsp. The index.html
value="${table.First_Name}"/></td> file gets the username from the user and the
<td><c:out welcome.jsp file prints the username with the
value="${table.Last_Name}"/></td> welcome message.
<td><c:out value="${table.Age}"/></td> File: index.html
</tr>
</c:forEach> <html>
</table> <body>
</body></html>
<form action="welcome.jsp">
O/P
<input type="text" name="uname">

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 68


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

<input type="submit" value="go"><br/> <body>


</form> <form action="welcome.jsp">
</body> <input type="text"
name="uname"><br/>
</html>
<input type="submit" value="go">
File: welcome.jsp
</form>
<html>
</body>
<body>
</html>
<%
File: welcome.jsp
String
name=request.getParameter("uname"); <html>
out.print("welcome "+name); <body>
%> <%= "Welcome
"+request.getParameter("uname") %>
</form>
</body>
</body>
</html>
</html>
3.18.3 JSP DECLARATION TAG
3.18.2 JSP EXPRESSION TAG
➢ The JSP declaration tag is used to declare
The code placed within JSP expression tag is
fields and methods.
written to the output stream of the response.
➢ The code written inside the jsp
So you need not write out.print() to write
data. It is mainly used to print the values of declaration tag is placed outside the
variable or method. service() method of auto generated
servlet.
Example of JSP expression tag that prints the ➢ So it doesn't get memory at each request.
user name
<html>
In this example, we are printing the username
using the expression tag. The index.html file <body>
gets the username and sends the request to
<%! int data=50; %>
the welcome.jsp file, which displays the
username. <%= "Value of the variable is:"+data %>
File: index.jsp </body>
<html>

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 69


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

CS6501 INTERNET PROGRAMMING XML:4.9 Basic XML- 4.10 Document Type


Definition- 4.11 XML Schema 4.12 DOM and
UNIT IV PHP and XML
Presenting XML,4.13 XML Parsers and
An introduction to PHP: 4.1 PHP- 4.2 Using Validation, 4.14 XSL and XSLT Transformation,
PHP-4.3 Variables-4.4 Program control- 4.5 4.15 News Feed (RSS and ATOM).
Built-in functions-4.6 Connecting to Database
– 4.7 Using Cookies-4.8 Regular Expressions;
➢ To encrypt data
4.1 PHP
➢ PHP is defined as a server side scripting
language that is mainly used for form 4.2.1 RULES IN PHP
handling and database access.
➢ White space insensitive
➢ PHP stands for Hypertext Pre Processor
➢ Case sensitive
➢ It was invented in 1994 by Rasmus
➢ Each statement ends with semi colon
Lerdorf
➢ Expressions are combination of tokens
➢ It is the most popular scripting language
➢ $ is used before variables
in web
➢ Save file as .php and access it from
➢ It is free to download and use
localhost server

4.1.1 FEATURES OF PHP


4.3 VARIABLES
➢ Embedded inside HTML, easy to develop ➢ Variables ate entities that are used for
➢ Easy to manage dynamic content, storing the values
database, session tracking ➢ All PHP variable names must be pre-fixed
➢ Supports many protocols such as IMAP, with a $.
POP3 ➢ It is this prefix which informs the PHP
➢ Supports many databases such as MS SQL pre-processor that it is dealing with a
server, Oracle, SyBase etc variable.
➢ Simple like C and HTML ➢ The first character of the name must be
either a letter or an underscore (_).
➢ The remaining characters must comprise
4.2 USING PHP
only of letters, numbers or underscores.
➢ To perform system functions such as file
➢ Values are assigned to variables using the
create, open, close, read, write, etc
PHP assignment operator.
➢ To handle forms, gather data from files,
➢ Finally the line, as with all PHP code
save data to a file, send email, etc
statements, is terminated with a semi-
➢ To add, delete, modify database contents
colon (;)
➢ To access and set cookies and variables
SYNTAX
➢ To restrict users from page access

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 70


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

$variable name = value; { }


EXAMPLE
EXAMPLE PROGRAM
$A = 10;
<htmal>

4.4 PROGRAM CONTROL <head>


➢ PHP supports following three decision </head>
making statements.
<body>
➢ The if, elseif ...else and switch statements
are used to take decision based on the <?php
different condition. $a=10;
➢ You can use conditional statements in
your code to make your decisions. if ($a == 10)
echo "a value is 10";
4.4.1 IF…ELSE STATEMENT
else
➢ If you want to execute some code if a
condition is true and another code if a echo "a value is not 10";
condition is false, use the if....else ?>
statement.
</body>
</html>
O/P
a value is 10
4.4.2 IF…ELSEIF…ELSE STATEMENT

➢ If one of the several conditions are true,


then use elseif

SYNTAX
If(condition)
{ }
else
VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 71
VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

statement echo "a is zero";


?>
</body>
</html>
O/P
a is positive
4.4.3 SWITCH STATEMENT

➢ If you want to select one of many


blocks of code to be executed, use the
SYNTAX Switch statement.
➢ The value of the expression is then
If (condition)
compared with the values for each case in
{ } the structure.
➢ If there is a match, the block of code
elseif( condition )
associated with that case is executed.
{ } ➢ Use break to prevent the code from
else running into the next case automatically.
➢ The default statement is used if no
{ } match is found.
EXAMPLE PROGRAM
<head>
</head>
<body>
<?php
$a=10;
if ($a > 0)
echo "a is positive";
elseif ($a< 0)
echo "a is negative";
else

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 72


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

case "red":
echo "Your favorite color is red!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is
neither red, blue, nor green!";
?>
</body>
</html>
SYNTAX
O/P
Switch(condition)
Your favorite color is green!
{
Case : 4.5 BUILT IN FUNCTIONS
…………. ➢ PHP functions are similar to other
programming languages.
……… ➢ A function is a piece of code which takes
default : one more input in the form of parameter
and does some processing and returns a
}
value.
EXAMPLE PROGRAM ➢ PHP has more than 1000 built-in
<head> functions.
➢ Two types of function
</head> ✓ User define function
<body> ✓ Built in function
SYNTAX
<?php
function name_of_function(parameter)
$fav = "green"; {
………………
switch ($fav)
}
{
VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 73
VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

4.5.1 USER DEFINE FUNCTION $a = array("a"=>"Dog", "b"=>"Cat",


"c"=>"Horse");
➢ User define function in PHP , we can
create our own functions. print_r($a);
➢ A function will not execute immediately ?>
when a page loads.
o/p
➢ A function will be executed by a call to
the function. Array ( [a] => Dog [b] => Cat [c] => Horse )
EXAMPLE PROGRAM
array_fill()
<?php
function writeMsg() ➢ Fills an array with num entries of the
{ value of the valueparameter, keys
starting at the start_index parameter.
echo "Hello world!";
} <?php
writeMsg();
$a = array_fill(5, 6, 'apple');
?>
O/P print_r($a);
HelloWorld ?>
4.5.2 BUILT IN FUNCTION o/p
➢ PHP Array Functions Array ( [5] => apple [6] => apple [7] => apple
➢ PHP Calender Functions [8] => apple [9] => apple [10] => apple )
➢ PHP Class/Object Functions array_keys() and array_values()<?php
➢ PHP Character Functions
➢ PHP Date & Time Functions <?php
➢ PHP Directory Functions $array = array("a"=>"green", "b"=>"brown",
➢ PHP Error Handling Functions "c"=>"blue", "red");
➢ PHP File System Functions
print_r(array_values($array));
➢ PHP MySQL Functions
➢ PHP Network Functions echo "<br>";
➢ PHP ODBC Functions print_r(array_keys($array));
➢ PHP String Functions
➢ PHP SimpleXML Functions ?>
➢ PHP XML Parsing Functions O/P
ARRAY FUNCTIONS Array ( [0] => green [1] => brown [2] => blue
[3] => red ) Array ( [0] => a [1] => b [2] => c [3]
<?php
=> 0 )

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 74


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

CALENDER FUNCTION ➢ This function checks if all of the characters


in the provided string, text, are lowercase
➢ The calendar extension presents a series
letters.
of functions to simplify converting
➢ This function checks if all of the
between different calendar formats.
characters in the provided string, text, are
➢ The intermediary or standard it is based
uppercase characters.
on is the Julian Day Count.
EXAMPLE PROGRAM
➢ To convert between calendar systems,
<?php
you must first convert to Julian Day
$strings = array('AB','cd','123','#');
Count, then to the calendar system of
foreach ($strings as $check)
your choice.
{
if (ctype_alnum($check)) echo "$check
cal_days_in_month() consists of letters or digits"; echo "<br>";
➢ This function will return the number of days in
the month of year for the specified calendar
?>
➢ This function returns the day of the week. It can
return a string or an integer depending on the O/p:-
mode. AB consists of letters or digits

<?php
$num = 4.6 CONNECTING TO DATABASE
cal_days_in_month(CAL_GREGORIAN,10, ➢ Before you can get content out of your
2016); MySQL database, you must know how to
echo "There are $num days in October 2016"; establish a connection to MySQL from
?> inside a PHP script.
O/p:- ➢ To perform basic queries from within
There are 31 days in October 2016 MySQL is very easy.
➢ The first thing to do is connect to the
CHARACTER FUNCTIONS database. The function to connect to
➢ The functions provided by this extension MySQL is called mysql_connect.
check whether a character or string falls ➢ This function returns a resource which is
a pointer to the database connection.
into a certain character class according to
the current locale. <?php
➢ Checks if all of the characters in the $username = "your_name";
provided string, text, are alphabetical. $password = "your_password";
Checks if all of the characters in the $hostname = "localhost"; //connection to the
provided string, text, are numerical. It database $dbhandle =
mysql_connect($hostname, $username,
checks only 1...9
$password) or die("Unable to connect to
MySQL");
echo "Connected to MySQL<br>";

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 75


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

?> MySQL"); echo "Connected to MySQL<br>";


➢ All going well, you should see "Connected //select a database to work with $selected =
to MySQL" when you run this script. mysql_select_db("examples",$dbhandle) or
➢ Once you've connected, you're going to die("Could not select examples"); //execute
want to select a database to work with. the SQL query and return records $result =
➢ Let's assume the database is ca mysql_query("SELECT id, model,year FROM
'examples'. To start working in this cars"); //fetch the data from the database
database, you'll need the while ($row = mysql_fetch_array($result)) {
mysql_select_db() function: echo "ID:".$row{'id'}."
Name:".$row{'model'}."Year: ". //display the
<?php //select a database to work with results $row{'year'}."<br>"; } //close the
$selected = connection mysql_close($dbhandle); ?> To
mysql_select_db("examples",$dbhandle) create 'examples' database on your MySQL
or die("Could not select examples"); server you should run the following script:
?> CREATE DATABASE `examples`; USE
➢ Now that you're connected, let's try and `examples`; CREATE TABLE `cars` ( `id` int
run some queries. The function used to UNIQUE NOT NULL, `name` varchar(40),
perform queries is named - my The `year` varchar(50), PRIMARY KEY(id) ); INSERT
function returns a resource that contains INTO cars VALUES(1,'Mercedes','2000');
the results of the query, called the result INSERT INTO cars VALUES(2,'BMW','2004');
set.
➢ A convenient way to access all the rows is
with a while loop. Let's add the code to 4.7 COOKIES
our script: ➢ A cookie is a name-value pair that is
➢ <?php //execute the SQL query and stored on client computer for tracking
return records $result = purpose
mysql_query("SELECT id, model, year
➢ It is created by some software on the
FROM cars"); //fetch the data from the
server
database while ($row =
mysql_fetch_array($result)) { echo ➢ In every HTTP communication
"ID:".$row{'id'}." Name:".$row{'model'}." between client and server, there is a
".$row{'year'}."<br>"; } header, within that, cookies are
?> present
EXAMPLE PROGRAM ➢ PHP supports cookies
<?php //close the connection
➢ Server puts cookie into client machine
mysql_close($dbhandle); ?> Here is a
code in full: <?php $username = on first visit.
"your_name"; ➢ When that client machine sends request
$password = "your_password"; to that server next time, server identifies
$hostname = "localhost"; //connection to the which user it is, from where the request
database $dbhandle = arrives, from what device the request
mysql_connect($hostname, $username, comes
$password) or die("Unable to connect to

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 76


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

4.7.1 CREATE COOKIES WITH PHP ➢ For example, it can be used to verify
whether the format of data i.e. name,
➢ A cookie is created with the
email, phone number, etc.
setcookie() function.
➢ PHP (version 5.3 and above) supports
Syntax Perl style regular expressions via its preg_
setcookie(name, value, expire, path, family of functions.
domain, secure, httponly);
4.8.1 REGULAR EXPRESSION FUNCTION
➢ Only the name parameter is required.
All other parameters are optional. Function What it Does
preg_match() Perform a regular expression
match.
EXAMPLE PROGRAM preg_match_all Perform a global regular
<html> expression match.
<body> preg_replace() Perform a regular expression
<?php search and replace.
if(!isset(“Myname”])) preg_grep() Returns the elements of the
echo "welcome input array that matched the
“.$+COOKIE[“Myname”]”; . $else pattern.
“welcome guest”; preg_split() Splits up a string into
?> substrings using a regular
expression.
</body> preg_quote() Quote regular expression
characters found within a
</html> string.
O/P
4.8.2 Regular Expression Syntax
Welcome cse
Regular expression syntax includes the use of
special characters (do not confuse with
4.8 REGULAR EXPRESSION
the HTML special characters). The characters
➢ Regular Expressions, commonly known as that are given special meaning within a
"regex" or "RegExp", are a specially regular expression, are: . * ? + [ ] ( ) { } ^ $ | \.
formatted text strings used to find
patterns in text. EXAMPLE PROGRAM
➢ Regular expressions are one of the most
powerful tools available today for <?php
effective and efficient text processing and $pattern = "/ca[kf]e/";
manipulations.
$text = "He was eating cake in the cafe.";
if(preg_match($pattern, $text)){

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 77


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

echo "Match found!"; ➢ Any data can be expressed in XML


} else{ 4.9.2 RULES IN XML DECLARATION
echo "Match not found.";
➢ If XML declaration is present, it should be
} placed 1st
➢ If XML declaration is present, it must
?>
contain version no
O/P ➢ Parameter name and parameter value is
Match found! case sensitive
➢ Correct order is: version, encoding,
standalone
➢ Either ‘ or “ can be used
➢ XML declaration has no close tag </?xml>
is wrong
4.9 XML
➢ Xtensible Markup language 4.9.3 DIFFERENCE BETWEEN XML AND
➢ XML is defined as a text based mark up HTML
language derived from Standard
Generalised Markup Language
XML HTML
➢ Developed by W3C in Feb 1998 to To transport and To display data
overcome HTML store data
➢ A web script that contains XML tags is Focus on what data it Focus on how the
called XML document is data looks
➢ It is a mark up language that defines set of Provides framework It is mark up language
rules for encoding documents in a format for defining mark up itself
languages
that is both human readable and machine
It is neither a It is a presentation
readable programming language
➢ It is not a programming language language, nor a
presentation language
4.9.1MENTION THE FEATURES OF XML
Case sensitive Case insensitive
➢ Extensible: user defined tags User defined tags No user defined tags
Closing of each tag is Not necessary of
➢ Secure: Carries data, but does not shows
mandatory closing all the opened
it tags
➢ Public standard: developed by W3C Preserve white space Does not.
➢ Simplifies HTML for large websites
➢ To offload and reload databases
4.9.4 ADVANTAGES OF XML
➢ To store and arrange data
➢ Can be merged with CSS ➢ Human readable, easy to understand

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 78


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ Language neutral <name>Bala</name>


➢ Tree structured, understood in simpler <phone>1234</phone>
manner </person>
Attributes
➢ Independent of hardware, software and
o To specify a property of an element
OS o It is a “name-value” pair
➢ User defined tags o An element can have more than 1
attributes
4.9.5 MENTION THE USES OF XML
o <phone available=”yes”>1234</phone>
➢ To display meta contents
References
➢ To exchange data between applications
o To add additional information
and databases o Begin with &
➢ To store any kind of complex data in o Entity reference
simpler way o Character Reference
➢ A java program can generate XML and can
be parsed by Perl Text
XML elements and attributes are case
4.9.6 BUILDING BLOCKS OF XML sensitive
Start and end tag needs to be in same
➢ Elements (start and end tags) case
➢ Attributes (flag type=”true”) To avoid encoding problems, use UTF-8
➢ CDATA (Character DATA, parsed by XML or UTF-16
parser) It is whitespace insensitive
➢ PCDATA ( Parsed Character DATA, i.e.,
Example:-
text)
<?xml version=”1.0”?>
➢ <person>
XML declaration <name>Bala</name>
< ? xml version = “1.0” ?> <cell>1234</cell>
“xml” should be in lower case <company>TCS</company>
Every XML document should begin with </person>
<?xml…> Rules for XM
It must be the root element in all XML
files
4.10 DOCUMENT TYPE DECLARATION
Tags and elements ➢ Document Type Definition
Tags are the building blocks of XML ➢ To define the type of the document
document ➢ A DTD is attached to a document
It is also called XML nodes ➢ To describe the XML
<name>Bala</name>
Syntax:-
<person>

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 79


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

< ! ELEMENT name(#PCDATA)>


< ! ELEMENT phone(#PCDATA)>
< ! ELEMENT company(#PCDATA)>
]
>
<address>
<name>Bala</name>

➢ The DTD starts with <!DOCTYPE delimiter. <phone>1234</phone>


➢ An element tells the parser to parse the <company>TCS</company>
document from the specified root
element </address>
➢ DTD identifier is an identifier for the Note:-
document type definition, which may be
CDATA -Character Data, this data is parsed by
the path to a file on the system or URL to
the XML parser
a file on the internet. If the DTD is
pointing to external path, it is called PCDATA -Parsed Character Data, plain text
External Subset. # -Delimiter
➢ The square brackets [ ] enclose an
optional list of entity declarations called 4.10.2 EXTERNAL DTD
Internal Subset. ➢ DTD is stored in a separate file called
4.10.1 INTERNAL DTD “sample.dtd”
➢ Set stand alone attribute = “no”
➢ Elements are declared within XML
➢ DTD is stored within the XML file itself. sample.xml
➢ Set stand alone attribute = “yes” <? xml version = “1.0” encoding = “utf-8”
standalone=”yes”?>
sample.xml
< ! DOCTYPE address SYSTEM “address.dtd”>
<? xml version = “1.0” encoding = “utf-8”
standalone=”yes”?> <address>

< ! DOCTYPE address <name>Bala</name>

[ <phone>1234</phone>

< ! ELEMENT address(name, phone, <company>TCS</company>


company)>
</address>

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 80


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

address.dtd ➢ The schemas are more specific and


provide the support for data types.
< ! DOCTYPE address ➢ The schema is aware of namespace
[ ➢ The XML Schema is written in XML
itself and has a large number of
< ! ELEMENT address(name, phone, built-in and derived types.
company)> ➢ The xml schema is the W3C
< ! ELEMENT name(#PCDATA)>
< ! ELEMENT phone(#PCDATA)>
➢ recommendation. Hence it is
< ! ELEMENT company(#PCDATA)> supported by various XML validator
and XML Processors.
]
>
What a
Advantages of DTD
schema
➢ XML processor enforces structure, as XML d
file is a
defined in DTD comple
➢ Application is accessed easily in document process
structure
➢ DTD gives hint to XML processor
4.11.2 DISADVANTAGES OF SCHEMA
➢ Reduces size of document
➢ The XML schema is complex to design
and hard to learn
➢ The XML document cannot be if the
4.11 XML SCHEMA
corresponding schema file is absent.
➢ Maintaining the schema for large and
➢ It is also known as XML schema Definition complex operations sometimes slows
(XSD) down the processing of XML
➢ To represent structure of XML document document
➢ To describe and validate structure and Simple Type - Simple type element is used
content of XML only in the context of the text. Some of
➢ Defines elements, attributes and data predefined simple types are: xs:integer,
types xs:boolean, xs:string, xs:date. For example:
➢ To define building blocks of XML
<xs:element name="phone_number"
Ex: <xs:schema type="xs:int" />
xmlns:xs=http://www.w3.org/2001/XMLSche ii) Complex Type - A complex type is a
ma> container for other element definitions. This
allows you to specify which child elements an
4.11.1 PURPOSE OF XML SCHEMA element can contain and to provide some

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 81


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

structure within your XML documents. For <xs:element name="Address2">


example: <xs:complexType>
<xs:sequence>
<xs:element name="Address"> <xs:element name="address"
<xs:complexType> type="AddressType" />
<xs:sequence> <xs:element name="phone2" type="xs:int" />
<xs:element name="name" type="xs:string" </xs:sequence>
/> </xs:complexType>
<xs:element name="company" </xs:element>
type="xs:string" /> 1. Instead of having to define the name
<xs:element name="phone" type="xs:int" /> and the company twice (once for
</xs:sequence> Address1 and once for Address2), we
</xs:complexType> now have a single definition.
</xs:element> 2. This makes maintenance simpler, i.e., if you
iii) Global Types - With global type, you can decide to add "Postcode" elements to the
define a single type in your document, which address, you need to add them at just one
can be used by all other references. For place.
example, suppose you want to generalize the
person and company for different addresses Step 2: student.xml
of the company. In such case, you can define <?xml version="1.0" encoding="UTF-8"?>
a general type as below: <contact
xmlns:xs="http://www.w3.org/2001/XMLSche
<xs:element name="AddressType"> ma-instance” SchemaLocation=”student.xsd”>
<xs:complexType> <name>Bala></name>
<xs:sequence> <company>TCS</company>
<xs:element name="name" type="xs:string" <phone>1234</phone>
/> <contact>
<xs:element name="company" Step 3: Open the Xml file in browser
type="xs:string" /> o/p:-
</xs:sequence> <contact>
</xs:complexType> <name>Bala></name>
</xs:element> <company>TCS</company>
Now let us use this type in our example as <phone>1234</phone>
below: <contact>
<xs:element name="Address1">
<xs:complexType> 4.11.3 XML SCHEMA DATA TYPES
<xs:sequence>
<xs:element name="address" ➢ String
type="AddressType" /> ➢ Numeric
<xs:element name="phone1" type="xs:int" /> ➢ Date
</xs:sequence> ➢ Boolean
</xs:complexType> ➢
</xs:element>

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 82


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

Step 2: string.xml
<xs:string> data type <?xml version="1.0" encoding="UTF-8"?>
➢ The <xs:string> data type can take <contact
characters, line feeds, carriage returns, xmlns:xs="http://www.w3.org/2001/XMLSchema-
and tab characters. instance” SchemaLocation=”string.xsd”>
➢ The XML processor does not replace Balamurugan
line feeds, carriage returns, and tab </contact>
characters in the content with space Step 3: Validate in Xml validator
and keep them intact. o/p:-
➢ For example, multiple spaces or tabs This XML document is valid
are preserved during display. ii) <xs:date> data type
The <xs:date> data type is used to represent date in
Example:- YYYY-MM-DD format.
Step 1: string.xsd * YYYY − represents year
<?xml version="1.0" encoding="UTF-8"?> * MM − represents month
<xs:schema * DD − represents day
xmlns:xs="http://www.w3.org/2001/XMLS Step 1: date.xsd
chema"> <?xml version="1.0" encoding="UTF-8"?>
<xs:element name=”contact” <xs:schema
type=”xs:string”/> xmlns:xs="http://www.w3.org/2001/XMLSchema">
</xs:schema> <xs:element name=”contact” type=”xs:date”/>
</xs:schema>
Step 2: date.xml
<?xml version="1.0" encoding="UTF-8"?>
<contact
xmlns:xs="http://www.w3.org/2001/XMLSchema-
instance” SchemaLocation=”date.xsd”>
2016-10-17
</contact>
Step 3: Validate in Xml validator
o/p:-
This XML document is valid
iii) <xs:numeric> data type
The <xs:decimal> data type is used to represent
numeric values.
It supports decimal numbers up to 18 digits.
The <xs:integer> data type is used to represent
integer values.
Step 1: numeric.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name=”contact” type=”xs:decimal”/>

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 83


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

</xs:schema> memory memory


Step 2: numeric.xml Requires less Requires more
<?xml version="1.0" encoding="UTF-8"?> memory space memory space
<contact Useful for small Uesful for large
xmlns:xs="http://www.w3.org/2001/XMLSchema- apps apps
instance” SchemaLocation=”numeric.xsd”> Traverse in any Top-down
93.5 direction traversing
</contact>
Step 3: Validate in Xml validator
o/p:-
This XML document is valid 4.13.1 DOM BASED PARSING:-
dom.java
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class dom
{
public static void main(String bala[])
{
try
{
System.out.println(“Enter XML document
name”);
BufferedReader input = new BufferedReader(
new InuptStreamReader(System.in));
String filename = input.readLine();
4.13 XML Parsers and Validation File fp = new File(filename);
➢ XML parser is a software library or a if(fp.exists())
package that gives interface for client {
apps to work with XML try
{
➢ It checks for proper format of XML
DocumentBuilderFactory dbf = new
document and validate XML documents DocumentBuilderFactory.newInstance();
➢ To parse the given XML document DocumentBuilder db = dbf.new
DocumentBuilder();
InputSource ips = new InputSource(filename);
DOM API SAX API Document doc = db.parse(ips);
Document Simple API for System.out.println(filename + “is well formed”);
Object Model XML }
Tree based Event based catch(Exception e)
parsing parsing {
Entire XML is Part of Xml is System.out.println(“Not well formed”);
stored in stored in

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 84


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

System.exit(1); 4.13.2 SAX BASED PARSING


}
} import java.io.*;
import org.xml.sax.*;
else import org.xml.sax.helpers.*;
{ public class dom
System.out.println(“File not Found”); {
} public static void main(String bala[])
} {
catch(IOException ioe) try
{ {
ioe.printStackTrace(); System.out.println(“Enter XML document
} name”);
} BufferedReader input = new BufferedReader(
} new InuptStreamReader(System.in));
User.xml String filename = input.readLine();
<?xml version="1.0"?> File fp = new File(filename);
<userdata> if(fp.exists())
<user1> {
<userno>001</userno> try
<username>Bala</username> {
<phonenumner>123456789</phonenumber> XMLReader reader =
<address>Chennai</Chennai> XMLReaderFactory.CreateXMLReader();
</user1> reader.parse(filename);
<user2> System.out.println(“filename + “is well formed”);
<userno>002</userno> }
<username>Suresh</username> catch(Exception e)
<phonenumner>987654321</phonenumber> {
<address>madurai</Chennai> System.out.println(“filename + “is not well
</user2> formed”);
<user3> System.exit(1);
<userno>003</userno> }
<username>arul</username> else
<phonenumner>1122334455</phonenumber> {
<address>Vellore</Chennai> System.out.println(“file not found”);
</user3> }
</userdata>
catch(IOException ioe)
o/p:-
{
C:> javac dom.java
C:> java dom ioe.printStackTrace();
Enter file name }
dom.xml }
dom.xml is well formed }

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 85


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

o/p:- ➢ It is XML related technology to


C:> javac sax.java manipulate and transform XML
C:> java sax documents
Enter file name
➢ To define XML transformations and
data.xml
presentations
data.xml is well formed
➢ The Extensible Stylesheet Language
(XSL) is an XML vocabulary typically
4.14 XSL and XSLT Transformation
used to transform XML documents
➢ XML concentrates on structure of from one form to another for
information

➢ W3C has published 2 recommendations for


style sheets

a) CSS

b) XSL

➢ XSL = XML Style sheet Language 4.15 NEWS FEED


➢ On the World Wide Web, a web feed (or
➢ To transform a document before display news feed) is a data format used for
providing users with frequently updated
➢ For advanced style information
content.
PARTS OF XSL
➢ Content distributors syndicate a web feed,
➢ XSLT: XSL Transformation, to thereby allowing users to subscribe to it.
transform XML
➢ Making a collection of web feeds accessible
➢ XPath: a language for navigating XML in one spot is known as aggregation, which
is performed by a news aggregator.
➢ XSL-FO: XSL-Formatting Objects, for
formatting XML ➢ A web feed is also sometimes referred to as
a syndicated feed.
XSLT

➢ XSLT is a language to specify


transformation of XML documents 4.15.1 ADVANTAGES OF WEB FEEDS

➢ It takes XML document, transforms it ➢ Users do not disclose their email address
into another XML document when subscribing to a feed and so are not
increasing their exposure to threats
VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 86
VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

associated with email: spam, viruses, updates to web-based content.


phishing, and identity theft.
➢ RSS is an XML application, which conforms
➢ Users do not have to send an unsubscribe to the W3C's RDF specification and is
request to stop receiving news. They simply extensible via XML.
remove the feed from their aggregator.
WORKING OF RSS
➢ The feed items are automatically sorted in
➢ A website willing to publish its content using
that each feed URL has its own sets of
RSS creates one RSS Feed and keeps it on a
entries
web server.
➢ News websites and blogs are common
➢ RSS Feeds can be created manually or with
sources for web feeds, but feeds are also
software.
used to deliver structured information
ranging from weather data to top-ten lists ➢ A website visitor will subscribe to read your
of hit tunes to search results. RSS Feed.
➢ The two main web feed formats are ➢ An RSS Feed will be read by an RSS Feed
reader.
1) RSS
➢ The RSS Feed Reader reads the RSS Feed
2) Atom.
file and displays it.
➢ Web feeds are designed to be machine-
➢ The RSS Reader displays only new items
readable rather than human-readable
from the RSS Feed.
4.15.2 RSS
<?xml version="1.0" ?>
➢ RSS stand for: It depends on what version of
<rss version="2.0">
RSS you are using.
<channel>
o RSS Version 0.9 - Rich Site Summary
<title>Ajax and XUL</title>
o RSS Version 1.0 - RDF Site Summary
<link>http://www.xul.fr/en/</link>
o RSS Versions 2.0, 2.0.1, and 0.9x -
Really Simple Syndication <description>XML graphical interface
etc...</description>
➢ RSS is a protocol that provides an open
method of syndicating and aggregating web <image>
content.
<url>http://www.xul.fr/xul-icon.gif</url>
➢ RSS is a standard for publishing regular
<link>http://www.xul.fr/en/index.php</link

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 87


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

>

</image> STRUCTURE OF AN ATOM 1.0 FEED

<item> <?xml version="1.0"?>

<title>News of today</title> <feed


xmlns="http://www.w3.org/2005/Atom">
<link>http://www.xul.fr/en-xml-
rss.html</link> <title>...</title>

<description>All you need to know about <link>...</link>


RSS</description>
<updated>...</updated>
</item>
<author>
<item>
<name>...</name>
<title>News of tomorrows</title>
</author>
<link>http://www.xul.fr/en-xml-
<id>...</id>
rdf.html</link>
<entry>
<description>And now, all about
RDF</description> <title>...</title>
</item> <link>...</link>
</channel> <id>...</id>
4.15.3 ATOM FEED <updated>...</updated>
➢ Atom is the name of an XML-based Web <summary>...</summary>
content and metadata syndication format,
and an application-level protocol for </entry>
publishing and editing Web resources
</feed>
belonging to periodically updated websites.
EXAMPLE:-
➢ Atom is a relatively recent spec and is much
more robust and feature-rich than RSS. <?xml version="1.0" encoding="utf-8"?>

➢ All Atom Feeds must be well-formed XML <feed


documents, and are identified with the xmlns="http://www.w3.org/2005/Atom">
application/atom+xml media type.
<title>Example Feed</title>

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 88


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

<subtitle>Insert witty or insightful remark Loose approach on Strict approach on


here</subtitle> data data
More complicated Easier process
<link href="http://example.org/"/> process
Not a standard Standard feature
<updated>2003-12- feature
13T18:30:02Z</updated> Less robust, More robust,
scalable, efficient scalable, efficient
<author>
<name>Mohtashim</name>
<email>mohtashim@example.com</em
ail>
</author>
<id>urn:uuid:60a76c80-d399-11d9-
b93C-0003939e0af6</id>
<entry>
<title>Tutorial on Atom</title>
<link
href="http://example.org/2003/12/13/
atom03"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-
80da344efa6a</id>
<updated>2003-12-
13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>

</feed>

RSS ATOM
Contains either Contains html, xml,
plain text or dhtml, documents,
escaped sequence audio, video, etc as
as payload payload
Shows timestamp Shows timestamp
of data when feed of data when it was
was last created or last updated
updated
Uses blogger and It has only one
meta weblog standard protocols
protocols

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 89


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

CS6501 INTERNET PROGRAMMING


UNIT V INTRODUCTION TO AJAX and WEB
SERVICES
AJAX: 5.1 Ajax Client Server Architecture- 5.2
XML Http Request Object-5.3 Call Back
Methods; Web Services: 5.4 Introduction- 5.5
Java web services Basics – 5.6 Creating,
Publishing ,Testing and Describing a Web
services (WSDL)- 5.8 Consuming a web
service, 5.9 Database Driven web service from
an application – 5.10 SOAP.
TECHNOLOGIES ARE BEING USED IN AJAX
5.1 AJAX ✓ JavaScript
✓ XMLHttpRequest
➢ AJAX is an acronym for asynchronous
✓ Document Object Model (DOM
JavaScript and XML
✓ Extensible HTML (XHTML)
➢ It is a set of web development techniques ✓ Cascading Style Sheets (CSS)
using many web technologies on the
client-side to create asynchronous Web 5.1.1 AJAX CLIENT SEVER ARCHITECTURE
applications.
RIA TECHNOLOGY
➢ HTML and CSS can be used in
combination to mark up and style ➢ AJAX is the most viable Rich Internet
information. Application (RIA) technology
➢ The DOM is accessed with JavaScript to
dynamically display and allow the user to ➢ It is getting tremendous industry
interact with the information presented. momentum and several tool kit and
➢ JavaScript and the XMLHttpRequest frameworks are emerging.
object provide a method for exchanging
data asynchronously between browser ➢ But at the same time, AJAX has browser
and server to avoid full page reloads. incompatibility and it is supported by
JavaScript, which is hard to maintain and
ADVANTAGES OF AJAX debug.
➢ Using Ajax are asynchronous
communication, minimal data transfer
and server is not overloaded with
unnecessary load.

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 90


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

EXAMPLE FOR AJAX: Google maps, Gmail, cricket


update websites, stock markets websites, etc

EXAMPLE PROGRAM
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button"
onclick="loadDoc()">
Change Content
</button>
</div>
<script>
function loadDoc()
5.1.2 STEPS OF PROCESSING IN AJAX {
var xhttp = new XMLHttpRequest();
➢ An event occurs in a web page (the page xhttp.onreadystatechange = function()
is loaded, a button is clicked) {
➢ An XMLHttpRequest object is created by if (this.readyState == 4 && this.status ==
200)
JavaScript
{
➢ The XMLHttpRequest object sends a
request to a web server document.getElementById("demo").innerHTML =
➢ The server processes the request this.responseText;
➢ The server sends a response back to the }
web page };
xhttp.open("GET", "ajax_info.txt", true);
➢ The response is read by JavaScript
xhttp.send();
➢ Proper action (like page update) is
}
performed by JavaScript </script>
</body>

</html>
O/P

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 91


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

SERVER SIDE

5.2 XML HTTP REQUEST OBJECT


➢ The XMLHttpRequest object can be used
to request data from a web server
➢ 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
➢ 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
CLIENT SIDE
5.2.1 XMLHTTPREQUEST METHODS

➢ abort() : Cancels the current request.


➢ getAllResponseHeaders() : Returns the
complete set of HTTP headers as a string.

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 92


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ getResponseHeader( headerName ) : Returns ➢ responseText :Returns the response as a


the value of the specified HTTP header. string.
➢ open(): method, URL ➢ responseXML :Returns the response as
XML.
5.2.2 XMLHTTPREQUEST PROPERTIES ➢ status : Returns the status as a number
(e.g., 404 for "Not Found" and 200 for
➢ onreadystatechange : An event handler "OK").
for an event that fires at every state ➢ statusText :Returns the status as a string
change. (e.g., "Not Found" or "OK")
➢ readyState : The readyState property
defines the current state of the
XMLHttpRequest object.

State Description
0 The request is not
initialized.
1 The request has
been set up.
2 The request has
been sent.
3 The request is in EXAMPLE PROGRAM
process. <!DOCTYPE html>
4 The request is
completed <html>
<body>
➢ readyState = 0 After you have created the <h2>Using the XMLHttpRequest
XMLHttpRequest object, but before you Object</h2>
have called the open() method <div id="demo">
➢ readyState = 1 After you have called the <button type="button"
open() method, but before you have onclick="loadXMLDoc()">Change Content
called send(). </button>
➢ readyState = 2 After you have called </div>
send(). <script>
➢ readyState = 3 After the browser has function loadXMLDoc()
established a communication with the {
server, but before the server has var xhttp = new XMLHttpRequest();
completed the response. xhttp.onreadystatechange =
➢ readyState = 4 After the request has been function()
completed, and the response data has {
been completely received from the if (this.readyState == 4 &&
server. this.status == 200)

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 93


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

{ 5.3.1 JQUERY CALLBACK FUNCTIONS

➢ JavaScript statements are executed line


document.getElementById("demo").inner
by line. However, with effects, the next
HTML = this.responseText;
line of code can be run even though the
}
effect is not finished. This can create
};
errors.
xhttp.open("GET", "xmlhttp_info.txt",
➢ To prevent this, you can create a callback
true);
function.
xhttp.send();
➢ A callback function is executed after the
}
current effect is finished.
</script>
SYNTAX
</body>
$(selector).hide(speed,callback);
</html>
O/P
EXAMPLE PROGRAM
<html>
<head>
<script src=”jquery.min.js”>
</script>
<script>
➢ The onreadystatechange property $(document).ready(function()
specifies a function to be executed every {
time the status of the XMLHttpRequest $(“button”).click(
object changes. function()
➢ When readyState property is 4 and the {
status property is 200, the response is $(“p”.hide();
ready. }
➢ responseText property returns the server );
response as a text string. });
➢ The text string can be used to update a </script>
web page
</head>
<body>
5.3 CALL BACK METHODS
➢ The ajaxSuccess( callback ) method <h3>call back</h3>
attaches a function to be executed <button>CLICK ME</button>
whenever an AJAX request completes </body>
successfully. </html>
➢ This is an Ajax Event.
VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 94
VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

O/P the network


CALL BACK ➢ Interoperability
➢ Standardized protocol
CLICK ME ➢ Low Cost of Communication

5.5 JAVA WEB SERVICES BASICS


➢ Two main java web services api:
5.4 WEB SERVICES
JAX-WS and JAX-RS.
➢ Web services are open standard (XML,
SOAP, HTTP etc.) based Web applications ➢ The java web service application
that interact with other web applications can be accessed by other
for the purpose of exchanging data. programming languages such as
➢ It is OS and language independent .Net and PHP.
➢ Web Services can convert your existing
applications into Web-applications. ➢ Java web service application
➢ A web service is a collection of open perform communication through
protocols and standards used for WSDL (Web Services Description
exchanging data between applications or Language).
systems. ➢ There are two ways to write java
➢ web service application code: SOAP
➢ and RESTful.
CHARACTERISTICS OF WEB SERVICE
➢ Machine-to-machine interactions 5.5.1 CONCEPT OF RPC
➢ Loose coupling
➢ Remote Procedure Call (RPC) is a
➢ Interoperability
➢ Platform-independence powerful technique for
➢ Operating system-independence constructing distributed, client-
➢ Language-independence server based applications.

COMPONENTS OF WEB SERVICES ➢ It is based on extending the


➢ The basic web services platform is conventional local procedure
XML + HTTP. calling, so that the called procedure
➢ SOAP (Simple Object Access need not exist in the same address
Protocol)
space as the calling procedure.
➢ UDDI (Universal Description,
Discovery and Integration) ➢ The two processes may be on the
➢ WSDL (Web Services Description
same system
Language)
ADVANTAGES OF WEB SERVICE
➢ Exposing the Existing Function on

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 95


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

an action supported by the service.


➢ Port Type–an abstract set of
operations supported by one or more
endpoints.
➢ Binding– a concrete protocol and
data format specification for a
particular port type.
➢ Port– a single endpoint defined as a
combination of a binding and a
network address.
➢ Service– a collection of related
endpoints.

4.7.2FEATURES OF WSDL
Fig. Principle of RPC between a client and
server program ➢ WSDL is an XML-based protocol for
information exchange in decentralized
and distributed environments.
5.6 DESCRIBING A WEB SERVICES ➢ WSDL definitions describe how to
access a web service and what
(WSDL)
operations it will perform.
➢ WSDL is a language for describing
➢ WSDL stands for Web Services how to interface with XML-based
Description Language. services.
➢ It is the standard format for describing ➢ WSDL is an integral part of Universal
a web service. Description, Discovery, and
➢ WSDL was developed jointly by Integration (UDDI), an XML-based
Microsoft and IBM. worldwide business registry.
➢ To exchange information in a ➢ WSDL is the language that UDDI uses.
distributed environment. WSDL is pronounced as 'wiz-dull' and
➢ WSDL is used to describe web spelled out as 'W-S-D-L'.
services
➢ WSDL is written in XML
➢ WSDL is a W3C recommendation
from 26. June 2007
5.7.1 ELEMENTS of WSDL?

➢ Types– a container for data type


definitions using some type system
(such as XSD).
➢ Message– an abstract, typed
definition of the data being
communicated.
➢ Operation– an abstract description of

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 96


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

<part name="value" type="xs:string"/>


</message>
<portType name="glossaryTerms">
<operation name="getTerm">
<input message="getTermRequest"/>
<output message="getTermResponse"/>
</operation>
</portType> In this example the

➢ <portType> element defines


"glossaryTerms" as the name of a
port, and "getTerm" as the name of
an operation.
➢ The "getTerm" operation has an input
message called "getTermRequest"
and an output message called
"getTermResponse".
4.7.3 THE WSDL DOCUMENT ➢ The <message> elements define the
STRUCTURE parts of each message and the
associated data types.
<definitions>
<types>
definition of types........ 5.8 DATABASE DRIVEN WEB SERVICE
</types> FROM AN APPLICATION
<message>
➢ In this tutorial we will develop a
definition of a message....
simple user registration Webservices.
</message>
The user registration/account
<portType>
registration form will be presented to
<operation>
the user.
definition of a operation.......
➢ Once user fills in the form and clicks
</operation>
on the "OK" button, the serverside
</portType>
JSP will call the webservice to register
<binding>
the user.
definition of a binding……
➢ The MySQL database is used to save
</binding>
the user registration data.
<service>
Software required to develop and run
definition of a service....
this example:
</service>
</definitions>
• JDK 1.6
EXAMPLE PROGRAM
• NetBeans 6.1
<message name="getTermRequest">
• MySQL Database 5 or above
<part name="term" type="xs:string"/>
Let's get started with the development
</message>
of the applicaton
<message name="getTermResponse">
VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 97
VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

MySql Database Configuration In Step 3:


NetBeans
Let's configure MySQL database in the • It opens a dialog box for the mysql
NetBeans IDE and then create the configuration.
required table into database. • Type the driver name, url , user
name and password as shown
Step 1: below in Fig. 3.
• Click on the service tab in
NetBeans as shown below in Fig
1

Fig. 1
Fig. 3
Step 2: Step 4:
• Right Click on the Databases
• Click on the Ok button .
• Select New Connection as shown
• Now expand the Newly created
below in Fig 2.
database connection.
• It shows the all the tables of the
database test as shown below in
Fig 4.

Fig. 2.

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 98


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

fields name of the table


• Now give the field name and data
type as shown below in Fig 6.

Fig. 4

Step 5:
Fig. 6
• Create a table named login.
• Right Click on the Tables and Step 7:
select Create table
as shown below in Fig 5 • Click on the Ok
• It creates the table login in the
test database.

Creating the WebService program


for Account creation

Step 8:

• Open the netbeans 6.1


• Creat a new web project as shown
below in Fig 7.

Fig. 5
Step 6:

• It opens a dialog box for giving the

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 99


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

Fig. 7
Step 9:
Fig. 9
• Type the project Name as Step 11:
MyAccount
• Click on the next button as shown • It creates a Web Project named
below in Fig 8. MyAccount.

Creating the WebService

Step 12:

• Right Click on the project


MyAccount
• Select New-->WebService as
shown below in Fig 10.

Fig. 8

Step 10:

• Select the server as Glassfish


• Click on the Next and then finish
button as shown below in Fig 9.

Fig. 10

Step 13:

• Type the name of the WebService


as myaccount with the package as
mypack.
• Click on the Finish button as
shown below in Fig 11.

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 100


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

• In the dialog box type all


parameter names.
• Also select the appropriate data
type.
• Click on Ok as shown below in Fig
13.

Fig. 11

Step 14:

• It creates a WebService
application in design view
• Click on the Add operation as
shown below in Fig 12.

Fig. 13
Step 16:

• It creates a WebService
application
• Click on the source tab as shown
below in the Fig 14.

Fig. 12
Step 15:

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 101


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

Add button as shown below in Fig

Fig. 14
Step 17:

• Now create the database source Fig. 16


• Right Click in the source code of Step 19:
• It opens a Add Data Source
myaccount.java
• Select the Enterprise Resources-- Reference.
• Type the Reference Name as
>Use Database as shown below in
Fig 15. data1
• For Project Data Sources Click on
the Add button as shown below in
Fig 17.

Fig. 15
Step 18:

• In the choose database select the


Fig. 17
VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 102
VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

Step 20:

• In the Crea Data Source type thye


jndi name as jndi1
• In the database connection select
the newly created database
connction for the mysql.
as shown below in Fig 18.

Fig. 19

Step 22:

• It creates the datasource data1


with the resource name as data1
Fig. 18 in the code
• Edit the code and give the
Step 21: database connection, statement
for the mysql connectivity
• Click on the Ok button as shown below.
• It creates the database connection
gives the dialog box as shown package mypack;
below.
• Click on the Ok button as shown import java.sql.Connection;
below in Fig 19. import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.sql.DataSource;

@WebService()
public class myaccount {

@Resource(name = "data1")

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 103


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

private DataSource data1; }


}
@WebMethod(operationName = "inser
t") Step 23:
public String insert(@WebParam(name
= "uname") String uname, • Now deploy the project
@WebParam(name = "fname") String fn • Right click on the project
ame, • Select Undeploy and Deploy as
@WebParam(name = "lname") String lna shown below in Fig 20.
me, • It builds and deploys the
@WebParam(name = "location") String l MyAccount Web project on the
ocation, glassfish server.

@WebParam(name = "phone") String ph


one,
@WebParam(name = "credit") String cre
dit,
@WebParam(name = "dl") String dl) {
try {
Class.forName("com.mysql.jdbc.Driver"
);
Connection con =
DriverManager.getConnection("jdbc:mys
ql://localhost:3306/test",
"root", "");
PreparedStatement st =
con.prepareStatement("insert into login Fig. 20
values(?,?,?,?,?,?,?)"); Step 24:
st.setString(1, uname); • After deploying now we can test
st.setString(2, fname); the Web Service created
st.setString(3, lname); • Right click on the myaccount
st.setString(4, location); webservice
int ph = Integer.parseInt(phone); • Select Test Web Service as shown
st.setInt(5, ph); below in Fig 21.
int cr = Integer.parseInt(credit);
st.setInt(6, cr);
int d1 = Integer.parseInt(dl);
st.setInt(7, d1);
st.executeUpdate();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return "record inserted";

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 104


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

• After clicking on the insert button


it insert the values into the login
table
• It open new window and displays
the Method parameters, SOAP
request and response
as shown below in Fig 23.

Step 27:

Fig. 21 Check the data in the database table
Step 25: • In the service tab select the mysql
connection
• It runs the deployed webservice in • In its table node right click on the
the firefox browser. table login
• Type the value and click on the • Select the view data as shown
insert button as shown below in below in Fig 24.
Fig 22.

Fig. 24
Fig. 22
Step 27:
Step 26:

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 105


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

• It opens a new window Step 29:


• Then display the data as shown • Click on the next button
below in Fig. 25. • Select the server as glassfish as
shown below in Fig. 27.

Fig. 25

Making the client of the WebService Fig. 27


Step 30:
Step 28:
• Click on the finish button
• Create a new Web Project • It creates a web project with a
• Type the name as index.jsp file
MyAccountClient as shown below • In the index.jsp design it with
in Fig.26. form and all its fields
• Give the form action as Client.jsp
as shown below in Fig 28.

Create WebService Client

Step 1:

• Right Click on the


MyAccountClient
• Select WebService Client as
shown below in Fig.28.

Fig. 26

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 106


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

• Select the myaccount webservice.


• Click on the OK button as shown
below in Fig 30.

Fig. 28
Step 2:
Fig. 30
• In the dialog box click on the Step 4:
browse button
as shown below in Fig 29. • Now project is containing the
WSDL file url.
• Click on the Ok button as shown
below in Fig 31.

Fig. 31
Step 5:
Fig. 29
Step 3: • Right Click in the Client.jsp

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 107


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

• Select Web Service Client Fig. 33


Resources-->Call WebService Step 6:
Operation
as shown below in Fig 32. • After insert operation the code
becomes like as shown below in
Fig 34.

Fig. 32
Step 5:
Fig. 34
• Select the insert operation as
Step 7:
shown below in Fig .33.
• Deploy the MyAccountClient
• Right Click and select Undeplo and
Deploy as shown below in Fig.35.

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 108


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

Fig. 35 Fig. 37
Step 8: Step 10:

• After deployment run the project. • After this click values get inserted
• Right Click and select the run as in the database table
shown below in Fig 36. • The message comes as record
inserted as shown below in Fig.38

Fig. 38
Step 11:

Fig. 36 • See the data inserted in the table.


Step 9: • In the service tab select the
connection created for mysql.
• It runs the index.jsp in the browser • In the table node select the login
as shown below in Fig 37. • Right Click and select the view
• Put the data and click on the ok data as shown below in Fig. 39.
button

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 109


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

➢ SOAP is an application communication


protocol
➢ SOAP is a format for sending and
receiving messages
➢ SOAP is platform independent
➢ SOAP is based on XML
➢ SOAP is a W3C recommendation

5.10.1 FEATURES OF SOAP.


Fig. 39
Step 12: ➢ SOAP is a communication protocol
designed to communicate via Internet.
• It displays the record inserted as ➢ SOAP can extend HTTP for XML
shown below in Fig 40. messaging.
➢ SOAP provides data transport for Web
services.
➢ SOAP can exchange complete documents
or call a remote procedure.
➢ SOAP can be used for broadcasting a
message.
➢ SOAP is platform- and language-
independent.
➢ SOAP is the XML way of defining what
information is sent and how.
➢ SOAP enables client applications to easily
5.10 SOAP connect to remote services and invoke
➢ SOAP is an acronym for Simple Object remote methods.
Access Protocol.
➢ It is an XML-based messaging protocol for 5.10.2 ELEMENTS OF SOAP
exchanging information among ➢ An Envelope element that identifies the
computers. XML document as a SOAP message
➢ SOAP is an application of the XML
specification. ➢ A Header element that contains header

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 110


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

information soap:encodingStyle="http://www.w3.org/2
003/05/soap-encoding">
➢ A Body element that contains call and
response information <soap:Header> ... </soap:Header>
<soap:Body> ...
➢ A Fault element containing errors and status
information <soap:Fault> ... </soap:Fault>
</soap:Body>
5.10.4 ADVANTAGES OF SOAP
</soap:Envelope>
➢ Simplicity

➢ Portability
SOAP REQUEST
➢ Firewall
POST /Quotation HTTP/1.0
➢ Scalable
Host: www.xyz.org
➢ Flexible
Content-Type: text/xml; charset=utf-8
➢ Interoperability
Content-Length: nnn
5.10.5 RULES
<?xml version="1.0"?>
➢ A SOAP message MUST be encoded using
XML <SOAP-ENV:Envelope xmlns:SOAP-
ENV="http://www.w3.org/2001/12/soap-
➢ A SOAP message MUST use the SOAP
envelope" SOAP-
Envelope namespace
ENV:encodingStyle="http://www.w3.org/20
➢ A SOAP message MUST use the SOAP 01/12/soap-encoding" >
Encoding namespace
<SOAP-ENV:Body
➢ A SOAP message must NOT contain a DTD xmlns:m="http://www.xyz.org/quotations"
reference >

➢ A SOAP message must NOT contain XML <m:GetQuotation>


Processing Instructions
<m:QuotationsName>MiscroSoft</m:Quota
<?xml version="1.0"?> tionsName>

<soap:Envelope </m:GetQuotation>
xmlns:soap="http://www.w3.org/2003/05/s
</SOAP-ENV:Body>
oap-envelope/"

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 111


VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT
OF COMPUTER SCIENCE AND ENGINEERING

</SOAP-ENV:Envelope>

SOAP RESPONSE

HTTP/1.0 200 OK

Content-Type: text/xml; charset=utf-8

Content-Length: nnn

<?xml version="1.0"?>

<SOAP-ENV:Envelope xmlns:SOAP-
ENV="http://www.w3.org/2001/12/soap-
envelope" SOAP-
ENV:encodingStyle="http://www.w3.org/20
01/12/soap-encoding" >

<SOAP-ENV:Body
xmlns:m="http://www.xyz.org/quotation" >

<m:GetQuotationResponse>

<m:Quotation>Here is the
quotation</m:Quotation>

</m:GetQuotationResponse>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 112

You might also like