Web Technology Complete Notes Computer Science 3rd Year
Web Technology Complete Notes Computer Science 3rd Year
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Course Outcomes of Web Technology
CO 1 Apply the knowledge of the internet and
related internet concepts that are vital in
understanding web application development and
analyze the insights of internet programming to
implement complete application over the web.
K3, K6
CO 2 Understand, analyze and apply the role of
mark up languages like HTML, DHTML, and XML in
the workings of the web and web applications.
K2, K3
CO 3 Use web application development software
tools i.e. XML, Apache Tomcat etc. and identifies
the environments currently available on the
market to design web sites. K3, K6
CO 4 Understand, analyze and build dynamic
web pages using client side programming
JavaScript and also develop the web application
using servlet and JSP. K2, K4, K6
CO 5 Understand the impact of web designing
by database connectivity with JDBC in the
current market place where everyone use to
prefer electronic medium for shopping,
commerce, fund transfer and even social life
also. K2, K3, K4
Unit -1
Lecture 1
• Introduction and Web Development
Strategies
• History of Web and Internet
Introduction and Web Development Strategies
6. Launch:
a. HTTP
b. TCP/IP
c. FTP
d. SMTP
e. TELNET
• HTTP: HTTP is the primary protocol used to
distribute information on the web.
• TCP/IP: It is a set of rules that an application
can use to package its information for sending
across the networks of networks.
• FTP: It is used to transfer the files over
networks.
• Simple Mail Transfer Protocol (SMTP) is
an Internet standard for electronic mail (e-
mail) transmission across Internet
Protocol (IP) networks.
• Telnet: Telnet lets you remotely log into
another system and browse files and
directories on that remote system.
Connecting to Internet
• All modern computers and laptops are
capable of connecting to the internet, as are
many other devices, including mobiles,
tablets, e-readers, televisions, video games
consoles.
• There are two ways of getting the internet at
home. The most popular way is to have your
telephone line (also known as a ‘landline’)
converted to broadband so that it can carry
normal phone calls and internet data at the
same time.
• if you don’t have a landline or if you want to
be able to use the internet when you’re out
and about, you might prefer mobile internet
from one of the mobile network providers.
This can be used anywhere there’s a mobile
signal but does tend to be slower and more
expensive than broadband through a landline.
Step-by-Step instructions to connect
to the internet
}}
Java Shift Operator Example: Right
Shift
class OperatorExample{
public static void main(String args[]){
[Link](10>>2);//10/2^2=10/4=2
[Link](20>>2);//20/2^2=20/4=5
[Link](20>>3);//20/2^3=20/8=2
}}
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Lecture 5
• Variable
• Arrays
Java Variable Types
Variable is name of reserved area allocated in
memory.
There are three kinds of variables in Java:
• Local variables
• Instance variables
• Class/static variables
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Local variables :
• Local variables are declared in methods, constructors,
or blocks.
• Local variables are created when the method,
constructor or block is entered and the variable will be
destroyed once it exits the method, constructor or
block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared
method, constructor or block.
• Local variables are implemented at stack level
internally.
• There is no default value for local variables so local
variables should be declared and an initial value should
be assigned before the first use.
Instance variables :
• Instance variables are declared in a class, but
outside a method, constructor or any block.
• When a space is allocated for an object in the
heap a slot for each instance variable value is
created.
• Instance variables are created when an object is
created with the use of the key word 'new' and
destroyed when the object is destroyed.
• Instance variables hold values that must be
referenced by more than one method,
constructor or block, or essential parts of an
object’s state that must be present through out
the class.
Class/static variables :
• Class variables also known as static variables
are declared with the static keyword in a class,
but outside a method, constructor or a block.
• There would only be one copy of each class
variable per class, regardless of how many
objects are created from it.
• Static variables are stored in static memory. It
is rare to use static variables other than
declared final and used as either public or
private constants.
Java Modifier Types
• Modifiers are keywords that you add to those
definitions to change their meanings. The Java
language has a wide variety of modifiers,
including the following:
• Java Access Modifiers
• Non Access Modifiers
Access Control Modifiers:
• Java provides a number of access modifiers to
set access levels for classes, variables,
methods and constructors. The four access
levels are:
• Visible to the package. the default. No
modifiers are needed.
• Visible to the class only (private).
• Visible to the world (public).
• Visible to the package and all subclasses
(protected).
Private access modifier
• The private access modifier is accessible only within
class.
class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
} Output:Hello
public access modifier
• The public access modifier is accessible
everywhere. It has the widest scope among all
other modifiers.
Non Access Modifiers:
Java provides a number of non-access modifiers
to achieve many other functionality.
• The static modifier for creating class methods
and variables
• The final modifier for finalizing the
implementations of classes, methods, and
variables.
• The abstract modifier for creating abstract
classes and methods.
Interview Questions Asked in different
Companies
1. Is Empty .java file name a valid source file
name? [Infosys Interview]
2. What if I write static public void instead of
public static void? [TCS Interview]
3. What are the various access specifiers in
Java? (wipro)
4. What is the default value of the local
variables? (wipro)
Java Array
• Array is a collection of similar type of
elements that have contiguous memory
location.
• Java array is an object that contains elements
of similar data type.
• It is a data structure where we store similar
elements.
• We can store only fixed set of elements in a
java array.
• Array in java is index based, first element of
the array is stored at 0 index.
Advantage of Java Array
• Code Optimization: It makes the code
optimized, we can retrieve or sort the data
easily.
• Random access: We can get any data located
at any index position.
Disadvantage of Java Array
• Size Limit: We can store only fixed size of
elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection
framework is used in java.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array
[Link]
Single Dimensional Array in java
Syntax to Declare an Array in java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in java
Array RefVar=new datatype[size];
Example
int a[]=new int[5];
[Link]
Example of single dimensional java array
class Testarray{
public static void main(String args[]){
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<[Link];i++)
[Link](a[i]);
}}
[Link]
Declaration, Instantiation and Initialization
of Java Array
We can declare, instantiate and initialize the java array
together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initializ
ation
//printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}
[Link]
Passing Array to method in java
class Testarray2{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<[Link];i++)
if(min>arr[i])
min=arr[i];
[Link](min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array to method
}} [Link]
Multidimensional array in java
In such case, data is stored in row and column
based index (also known as matrix form).
Syntax to Declare Multidimensional Array in java.
• dataType[][] arrayRefVar; (or)
• dataType [][]arrayRefVar; (or)
• dataType arrayRefVar[][]; (or)
• dataType []arrayRefVar[];
[Link]
Example to instantiate Multidimensional Array in
java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
[Link]
Example of Multidimensional java array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}
}}
[Link]
class Testarray5{
public static void main(String args[]){
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
int c[][]=new int[2][3];
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
[Link](c[i][j]+" ");
}
[Link]();//new line
}
}}
[Link]
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Index
• Methods & Classes
Object in Java
• Object is an instance of a class. Class is a
template or blueprint from which objects are
created. So object is the instance(result) of a
class.
An object has three characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality)
of an object such as deposit, withdraw etc.
• identity: Object identity is typically implemented
via a unique ID. The value of the ID is not visible
to the external user. But,it is used internally by
the JVM to identify each object uniquely.
Class in Java
• Class is a template or blueprint from which
objects are created.
A class in java can contain:
• data member
• method
• constructor
• block
• class and interface
Syntax to declare a class:
class <class_name>
{
data member;
method;
}
Constructor in Java
• Constructor in java is a special type of
method that is used to initialize the object.
• Java constructor is invoked at the time of
object creation.
• It constructs the values i.e. provides data for
the object that is why it is known as
constructor.
Rules for creating java constructor
There are basically two rules defined for the
constructor.
• Constructor name must be same as its class
name
• Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
• Default constructor (no-arg constructor)
• Parameterized constructor
Example of default constructor
• In this example, we are creating the no-arg
constructor in the Bike class. It will be invoked
at the time of object creation.
class Bike1{
Bike1(){[Link]("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}}
Rule: If there is no constructor in a class,
compiler automatically creates a default
constructor.
Example of parameterized constructor
class Student4{
int id;
String name;
Student6(Student6 s){
id = [Link];
name =[Link];
}
void display(){[Link](id+" "+name);}
Bike10(){
speedlimit=70;
[Link](speedlimit);
}
class OverloadingExample
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
Method Overriding in Java
• If subclass (child class) has the same method
as declared in the parent class, it is known
as method overriding in java.
• Method overriding is used to provide specific
implementation of a method that is already
provided by its super class.
• Method overriding is used for runtime
polymorphism.
Rules for Java Method Overriding
• method must have same name as in the
parent class
• method must have same parameter as in the
parent class.
• must be IS-A relationship (inheritance).
class Vehicle{
void run(){[Link]("Vehicle is runnin
g");}
}
class Bike extends Vehicle{ void run(){System.o
[Link](“Bike is running");}
[Link]
Advantage of Java Package
1) Java package is used to categorize the classes
and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
[Link]
[Link]
There are three ways to access the package from
outside the package.
• import package.*;
• import [Link];
• fully qualified name.
[Link]
1) Using packagename.*
If you use package.* then all the classes and interfaces of this
package will be accessible but not subpackages.
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
} }
[Link]
2) Using [Link]
If you import [Link] then only declared class of
this package will be accessible.
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
[Link]
3) Using fully qualified name
• If you use fully qualified name then only
declared class of this package will be
accessible.
• Now there is no need to import.
• But you need to use fully qualified name every
time when you are accessing the class or
interface.
[Link]
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
[Link]
Abstract class in Java
• A class that is declared with abstract keyword, is
known as abstract class in java. It can have
abstract and non-abstract methods (method with
body).
Abstraction in Java
• Abstraction is a process of hiding the
implementation details and showing only
functionality to the user.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
• Abstract class (0 to 100%)
• Interface (100%)
Abstract class in Java
• A class that is declared as abstract is known
as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Example
abstract class A{}
Abstract method
• A method that is declared as abstract and does
not have implementation is known as abstract
method.
Example
abstract void printStatus();//no body and abstract
Example of abstract class that has abstract method
In this example, Bike the abstract class that contains only
one abstract method run. It implementation is
provided by the Honda class.
abstract class Bike{
abstract void run();
}
class TestBank{
public static void main(String args[]){
SBI b=new SBI();//if object is PNB, method of PNB will be invoked
int interest=[Link]();
[Link]("Rate of Interest is: "+interest+" %");
}}
class Test5{
public static void main(String args[]){
M a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Interface in Java
• An interface in java is a blueprint of a class. It has
static constants and abstract methods only.
• The interface in java is a mechanism to achieve
fully abstraction. There can be only abstract
methods in the java interface not method body. It
is used to achieve fully abstraction and multiple
inheritance in Java.
• Java Interface also represents IS-A relationship.
• It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface.
They are given below.
• It is used to achieve fully abstraction.
• By interface, we can support the functionality of
multiple inheritance.
• It can be used to achieve loose coupling.
The java compiler adds public and abstract
keywords before the interface method and
public, static and final keywords before data
members.
In other words, Interface fields are public, static and
final by default, and methods are public and
abstract.
interface printable{
void print();
}
interface Showable{
void show();
}
[Link]
Types of Exception
There are mainly two types of exceptions: checked and
unchecked where error is considered as unchecked
exception.
• Checked Exception
• Unchecked Exception
• Error
[Link]
[Link]
Difference between checked and unchecked exceptions
1) Checked Exception
The classes that extend Throwable class except
RuntimeException and Error are known as checked
exceptions [Link], SQLException etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known
as unchecked exceptions e.g. ArithmeticException,
NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather
they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.
[Link]
Java Exception Handling Keywords
There are 5 keywords used in java exception
handling.
• try
• catch
• finally
• throw
• throws
[Link]
Java try block
• Java try block is used to enclose the code that
might throw an exception. It must be used
within the method.
• Java try block must be followed by either
catch or finally block.
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
[Link]
Syntax of try-finally block
try{
//code that may throw exception
}finally{}
[Link]
The JVM firstly checks whether the exception is
handled or not. If exception is not handled,
JVM provides a default exception handler that
performs the following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods
where the exception occurred).
• Causes the program to terminate.
[Link]
Java Multi catch block
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){[Link]("task1 is co
mpleted");}
catch(ArrayIndexOutOfBoundsException e){[Link]
ln("task 2 completed");}
catch(Exception e){[Link]("common task compl
eted");}
[Link]("rest of the code...");
}}
[Link]
• Rule: At a time only one Exception is occured
and at a time only one catch block is
executed.
• Rule: All catch blocks must be ordered from
most specific to most general i.e. catch for
ArithmeticException must come before catch
for Exception
[Link]
Java Nested try block
class Excep6{
public static void main(String args[]){
try{
try{
[Link]("going to divide");
int b =39/0;
}catch(ArithmeticException e){[Link](e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){[Link]
(e);}
[Link]("other statement);
}catch(Exception e){[Link]("handeled");}
[Link]("normal flow..");
}} [Link]
Java finally block
• Java finally block is a block that is used to
execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether
exception is handled or not.
• Java finally block must be followed by try or
catch block.
[Link]
[Link]
Why use java finally
Finally block in java can be used to put
"cleanup" code such as closing a file, closing
connection etc.
Rule: For each try block there can be zero or
more catch blocks, but only one finally block.
Note: The finally block will not be executed if
program exits(either by calling [Link]()
or by causing a fatal error that causes the
process to abort).
[Link]
Java throw keyword
The Java throw keyword is used to explicitly throw an
exception.
We can throw either checked or uncheked exception in
java by throw keyword. The throw keyword is mainly
used to throw custom exception.
throw exception;
throw new IOException("sorry device error);
[Link]
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[]){
validate(13);
[Link]("rest of the code...");
}
}
Output:
Exception in thread main
[Link]:not valid
[Link]
Java throws keyword
• The Java throws keyword is used to declare an
exception. It gives an information to the
programmer that there may occur an exception
so it is better for the programmer to provide the
exception handling code so that normal flow can
be maintained.
• Exception Handling is mainly used to handle the
checked exceptions. If there occurs any
unchecked exception such as
NullPointerException, it is programmers fault that
he is not performing check up before the code
being used. [Link]
Syntax of java throws
return_type method_name() throws exception_class_name
{
//method code
}
Rule: If you are calling a method that declares an exception,
you must either caught or declare the exception.
There are two cases:
• Case1:You caught the exception i.e. handle the exception
using try/catch.
• Case2:You declare the exception i.e. specifying throws with
the method.
[Link]
[Link]
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Multithreading in Java
• Multithreading in java is a process of
executing multiple threads simultaneously.
• Thread is basically a lightweight sub-process, a
smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve
multitasking.
• Java Multithreading is mostly used in games,
animation etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are
independent and you can perform multiple
operations at same time.
2) You can perform many operations together
so it saves time.
3) Threads are independent so it doesn't affect
other threads if exception occur in a single
thread.
What is Thread in java
• A thread is a lightweight sub process, a
smallest unit of processing. It is a separate
path of execution.
• Threads are independent, if there occurs
exception in one thread, it doesn't affect other
threads. It shares a common memory area.
Note: At a time one thread is executed only.
Life cycle of a Thread (Thread States)
The life cycle of the thread in java is controlled
by JVM. The java thread states are as follows:
• New
• Runnable
• Running
• Non-Runnable (Blocked)
• Terminated
1) New
The thread is in new state if you create an instance of
Thread class but before the invocation of start()
method.
2) Runnable
The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to
be the running thread.
3) Running
The thread is in running state if the thread scheduler has
selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is
currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run()
method exits.
How to create thread
There are two ways to create a thread:
• By extending Thread class
• By implementing Runnable interface.
Thread class:
• Thread class provide constructors and
methods to create and perform operations on
a thread.
• Thread class extends Object class and
implements Runnable interface.
Commonly used methods of Thread class:
• public void run(): is used to perform action for a
thread.
• public void start(): starts the execution of the
[Link] calls the run() method on the thread.
• public void sleep(long miliseconds): Causes the
currently executing thread to sleep (temporarily
cease execution) for the specified number of
milliseconds.
• public int getPriority(): returns the priority of the
thread.
• public int setPriority(int priority): changes the
priority of the thread.
• public String getName(): returns the name of the
thread.
• public void setName(String name): changes the
name of the thread.
• public Thread currentThread(): returns the
reference of currently executing thread.
• public int getId(): returns the id of the thread.
• public [Link] getState(): returns the state
of the thread.
• public boolean isAlive(): tests if the thread is
alive.
• public void yield(): causes the currently executing
thread object to temporarily pause and allow
other threads to execute.
• public void suspend(): is used to suspend the
thread(depricated).
• public void resume(): is used to resume the
suspended thread(depricated).
• public void stop(): is used to stop the
thread(depricated).
Starting a thread
• start() method of Thread class is used to start
a newly created thread. It performs following
tasks:A new thread starts(with new callstack).
• The thread moves from New state to the
Runnable state.
• When the thread gets a chance to execute, its
target run() method will run.
Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
}
}
Java Thread Example by implementing Runnable interface
[Link]();
[Link]();
[Link](“CSA Webtech");
[Link]("After changing name of t1:"+[Link]());
}
}
Priority of a Thread (Thread Priority)
• Each thread have a priority.
• Priorities are represented by a number
between 1 and 10.
• In most cases, thread schedular schedules the
threads according to their priority (known as
preemptive scheduling). But it is not
guaranteed because it depends on JVM
specification that which scheduling it chooses.
Three constants defined in Thread class
• public static int MIN_PRIORITY
• public static int NORM_PRIORITY
• public static int MAX_PRIORITY
Note: Default priority of a thread is 5
(NORM_PRIORITY). The value of MIN_PRIORITY is 1
and the value of MAX_PRIORITY is 10.
class TestMultiPriority1 extends Thread{
public void run(){
[Link]("running thread name is:"+[Link]
hread().getName());
[Link]("running thread priority is:"+[Link]
Thread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}}
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Java I/O
• Java I/O (Input and Output) is used to process the
input and produce the output based on the input.
• Java uses the concept of stream to make I/O
operation fast. The [Link] package contains all the
classes required for input and output operations.
Stream
• A stream is a sequence of data. In Java a
stream is composed of bytes. It's called a
stream because it's like a stream of water that
continues to flow.
In java, 3 streams are created for us automatically.
All these streams are attached with console.
1) [Link]: standard output stream
2) [Link]: standard input stream
3) [Link]: standard error stream
Code to print output and error message to the
console.
[Link]("simple message");
[Link]("error message");
OutputStream
Java application uses an output stream to write
data to a destination, it may be a file,an
array,peripheral device or socket.
InputStream
Java application uses an input stream to read
data from a source, it may be a file,an
array,peripheral device or socket.
Working of Java OutputStream and InputStream
OutputStream class
• OutputStream class is an abstract class. It is the
super class of all classes representing an output
stream of bytes. An output stream accepts output
bytes and sends them to some sink.
InputStream class
• InputStream class is an abstract class. It is the
super class of all classes representing an input
stream of bytes.
Commonly used methods of InputStream class
FileInputStream and FileOutputStream (File Handling)
}
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="
300">
</applet>
</body>
</html>
Displaying Graphics in Applet
[Link] class provides many
methods for graphics programming.
Displaying graphics in swing
Commonly used methods of Graphics class:
• public abstract void drawString(String str, int x, int y): is used to
draw the specified string.
• public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specified width and height.
• public abstract void fillRect(int x, int y, int width, int height): is
used to fill rectangle with the default color and specified width and
height.
• public abstract void drawOval(int x, int y, int width, int height): is
used to draw oval with the specified width and height.
• public abstract void fillOval(int x, int y, int width, int height): is
used to fill oval with the default color and specified width and
height.
• public abstract void drawLine(int x1, int y1, int x2, int y2): is used
to draw line between the points(x1, y1) and (x2, y2).
• public abstract boolean drawImage(Image img,
int x, int y, ImageObserver observer): is used
draw the specified image.
• public abstract void drawArc(int x, int y, int
width, int height, int startAngle, int arcAngle): is
used draw a circular or elliptical arc.
• public abstract void fillArc(int x, int y, int width,
int height, int startAngle, int arcAngle): is used to
fill a circular or elliptical arc.
• public abstract void setColor(Color c): is used to
set the graphics current color to the specified
color.
• public abstract void setFont(Font font): is used to
set the graphics current font to the specified font.
Example of Graphics in applet
import [Link];
import [Link].*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
[Link]([Link]);
[Link]("Welcome",50, 50);
[Link](20,30,20,300);
[Link](70,100,30,30);
[Link](170,100,30,30);
[Link](70,200,30,30);
[Link]([Link]);
[Link](170,200,30,30);
[Link](90,150,30,30,30,270);
[Link](270,150,30,30,0,180);
} }
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Java String
• Java String provides a lot of concepts that can be
performed on a string such as compare, concat,
equals, split, length, replace, compareTo, intern,
substring etc.
• In java, string is basically an object that represents
sequence of char values.
• An array of characters works same as java string.
For example:
char[] ch={'j','a','v','a'};
String s=new String(ch);
is same as:
String s="java";
• [Link] class
• The java String is immutable i.e. it cannot be changed
but a new instance is created.
There are two ways to create String object:
• By string literal
• By new keyword
1) String Literal
• Java String literal is created by using double quotes.
For Example:
String s="welcome";
• Each time you create a string literal, the JVM checks
the string constant pool first.
• If the string already exists in the pool, a reference to
the pooled instance is returned.
• If string doesn't exist in the pool, a new string instance
is created and placed in the pool.
For example:
String s1="Welcome";
String s2="Welcome";//will not create new instance
• In the above example only one object will be
created.
• Firstly JVM will not find any string object with
the value "Welcome" in string constant pool,
so it will create a new object.
• After that it will find the string with the value
"Welcome" in the pool, it will not create new
object but will return the reference to the
same instance.
Method Description
char charAt(int index) returns char value for the
particular index
int length() returns string length
String substring(int beginIndex) returns substring for given
begin index
String substring(int beginIndex, returns substring for given
int endIndex) begin index and end index
boolean contains(CharSequence s) returns true or false after
matching the sequence of
char value
boolean equals(Object another) checks the equality of string
with object
boolean isEmpty() checks if string is empty
String concat(String str) concatenates specified string
[Link]([Link](s2));//false
[Link]([Link](s2));//true
}
}
}
public static void main(String args[]){
First f=new First();
}}
The setBounds(int xaxis, int yaxis, int width, int height) method
is used in the above example that sets the position of
the awt button.
Example of AWT by association
import [Link].*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
[Link](30,50,80,30);
[Link](b);
[Link](300,300);
[Link](null);
[Link](true);
}
public static void main(String args[]){
First2 f=new First2();
}}
Java AWT Button
The button class is used to create a labeled button that
has platform independent implementation.
import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
Frame f=new Frame("Button Example");
Button b=new Button("Click Here");
[Link](50,100,80,30);
[Link](b);
[Link](400,400);
[Link](null);
[Link](true);
}}
Java AWT Label
The object of Label class is a component for placing text in a container.
It is used to display a single line of read only text. The text can be
changed by an application but a user cannot edit it directly.
import [Link].*;
class LabelExample{
public static void main(String args[]){
Frame f= new Frame("Label Example");
Label l1,l2;
l1=new Label("First Label.");
[Link](50,100, 100,30);
l2=new Label("Second Label.");
[Link](50,150, 100,30);
[Link](l1); [Link](l2);
[Link](400,400);
[Link](null);
[Link](true);
}}
Java AWT TextField
The object of a TextField class is a text component that allows the editing
of a single line text. It inherits TextComponent class.
import [Link].*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome to United");
[Link](50,100, 200,30);
t2=new TextField("AWT Tutorial");
[Link](50,150, 200,30);
[Link](t1); [Link](t2);
[Link](400,400);
[Link](null);
[Link](true);
} }
Java AWT TextArea
The object of a TextArea class is a multi line region that displays text. It allows
the editing of multiple line text. It inherits TextComponent class.
import [Link].*;
public class TextAreaExample
{
TextAreaExample(){
Frame f= new Frame();
TextArea area=new TextArea("Welcome to United");
[Link](10,30, 300,300);
[Link](area);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new TextAreaExample();
} }
Java AWT Checkbox
• The Checkbox class is used to create a
checkbox. It is used to turn an option on (true)
or off (false).
• Clicking on a Checkbox changes its state from
"on" to "off" or from "off" to "on".
import [Link].*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
[Link](100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
[Link](100,150, 50,50);
[Link](checkbox1);
[Link](checkbox2);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}
Java AWT CheckboxGroup
• The object of CheckboxGroup class is used to
group together a set of Checkbox.
• At a time only one check box button is allowed
to be in "on" state and remaining check box
button in "off" state. It inherits the object
class.
• Note: CheckboxGroup enables you to create
radio buttons in AWT. There is no special
control for creating radio buttons in AWT.
import [Link].*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
[Link](100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
[Link](100,150, 50,50);
[Link](checkBox1);
[Link](checkBox2);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
} }
Java AWT Choice
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on
the top of a menu. It inherits Component class.
import [Link].*;
public class ChoiceExample
{
ChoiceExample(){
Frame f= new Frame();
Choice c=new Choice();
[Link](100,100, 75,75);
[Link]("Item 1");
[Link]("Item 2");
[Link]("Item 3");
[Link]("Item 4");
[Link]("Item 5");
[Link](c);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new ChoiceExample();
} }
Java AWT List
The object of List class represents a list of text items. By the help of list, user can choose either one item
or multiple items. It inherits Component class.
import [Link].*;
public class ListExample
{
ListExample(){
Frame f= new Frame();
List l1=new List(5);
[Link](100,100, 75,75);
[Link]("Item 1");
[Link]("Item 2");
[Link]("Item 3");
[Link]("Item 4");
[Link]("Item 5");
[Link](l1);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new ListExample();
} }
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Event and Listener (Java Event Handling)
• Changing the state of an object is known as an
event. For example, click on button, dragging
mouse etc.
• The [Link] package provides many
event classes and Listener interfaces for event
handling.
Steps to perform Event Handling
Following steps are required to perform event handling:
• Implement the Listener interface and overrides its
methods
• Register the component with the Listener
For registering the component with the Listener, many
classes provide the registration methods.
For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
– public void addActionListener(ActionListener a){}
– public void addTextListener(TextListener a){}
• TextArea
– public void addTextListener(TextListener a){}
• Checkbox
– public void addItemListener(ItemListener a){}
• Choice
– public void addItemListener(ItemListener a){}
• List
– public void addActionListener(ActionListener a){}
– public void addItemListener(ItemListener a){}
Java ActionListener Interface
The Java ActionListener is notified whenever you
click on the button or menu item. It is notified
against ActionEvent. The ActionListener
interface is found in [Link] package.
It has only one method: actionPerformed().
• actionPerformed() method
• The actionPerformed() method is invoked
automatically whenever you click on the
registered component.
public abstract void actionPerformed(ActionEvent e);
Java MouseListener Interface
The Java MouseListener is notified whenever you change
the state of mouse. It is notified against MouseEvent.
The MouseListener interface is found in [Link]
package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener
interface are given below:
public abstract void mouseClicked(MouseEvent e);
public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);
MouseMotionListener Interface
• The Java MouseMotionListener is notified
whenever you move or drag mouse. It is notified
against MouseEvent. The MouseMotionListener
interface is found in [Link] package. It
has two methods.
Methods of MouseMotionListener interface
The signature of 2 methods found in
MouseMotionListener interface are given below:
public abstract void mouseDragged(MouseEvent e);
</body>
</html>
• The DOCTYPE declaration defines the
document type. The <!DOCTYPE> declaration
helps the browser to display a web page
correctly.
• The text between <html> and </html>
describes the web page
• The text between <body> and </body> is the
visible page content
• The text between <h1> and </h1> is displayed
as a heading
• The text between <p> and </p> is displayed as
a paragraph
The <!DOCTYPE> Declaration
<p>This is a paragraph</p>
<p>This is another paragraph</p>
HTML Line Breaks
<ul>
<li>Milk</li>
<li>Toilet Paper</li>
<li>Cereal</li>
<li>Bread</li>
</ul>
HTML Unordered List Type
• <ul type="square">
• <ul type="disc">
• <ul type="circle">
html - ordered lists
h1 {
color: #990000;
background-color: #FC9804;
}
Colors and backgrounds
The CSS property background-image is used to insert a
background image.
body {
background-color: #FFCC66;
background-image: url("[Link]");
}
h1 {
color: #990000;
background-color: #FC9804;
}
Repeat background image
background-repeat: repeat-x
The image is repeated horizontally
background-repeat: repeat-y
The image is repeated vertically
background-repeat: repeat
The image is repeated both horizontally and
vertically
background-repeat: no-repeat
The image is not repeated
body {
background-color: #FFCC66;
background-image: url("[Link]");
background-repeat: no-repeat;
}
h1 {
color: #990000;
background-color: #FC9804;
}
background-attachment
• The property background-attachment specifies
whether a background picture is fixed or scrolls
along with the containing element.
• Background-attachment: scroll
The image scrolls with the page - unlocked
• Background-attachment: fixed
The image is locked
background-position
• By default, a background image will be
positioned in the top left corner of the screen.
• The coordinates can be indicated as percentages
of the browser window, fixed units (pixels,
centimetres, etc.) or you can use the words top,
bottom, center, left and right.
Fonts
➢FONT-FAMILY
➢FONT-STYLE
➢FONT-WEIGHT
➢FONT-SIZE
➢FONT
Font family
The property font-family is used to set a prioritized
list of fonts to be used to display a given element
or web page. If the first font on the list is not
installed on the computer used to access the site,
the next font on the list will be tried until a
suitable font is found.
An example
td {
text-align: center;
}
p{
text-align: justify;
}
Text decoration
• The property text-decoration makes it is possible to add
different "decorations" or "effects" to text.
h1 {
text-decoration: underline;
}
h2 {
text-decoration: overline;
}
h3 {
text-decoration: line-through;
}
Letter space
• The spacing between text characters can be
specified using the property letter-spacing.
h1 {
letter-spacing: 6px;
}
p{
letter-spacing: 3px;
}
Text transformation
• The text-transform property controls the capitalization of
a [Link] are four possible values for text-transform:
capitalize
• Capitalizes the first letter of each word. For example:
"john doe" will be "John Doe".
uppercase
• Converts all letters to uppercase. For example: "john doe"
will be "JOHN DOE".
lowercase
• Converts all letters to lowercase. For example: "JOHN
DOE" will be "john doe".
none
• No transformations - the text is presented as it appears in
the HTML code.
Links
• A link can have different states. For example, it
can be visited or not visited. You can use
pseudo-classes to assign different styles to
visited and unvisited links.
• Use a:link and a:visited for unvisited and visited
links respectively. Links that are active have the
pseudo-class a:active and a:hover is when the
cursor is on the link.
Links
a {text-decoration:none;}
a:link {color: blue;text-decoration:none;}
a:visited {color: purple;text-decoration:none;}
a:active {background-color: yellow;text-
decoration:none;}
a:hover { color:red; text-decoration:none;}
Margin and Padding
• An element has four sides: right, left, top and
bottom. The margin is the distance from each
side to the neighboring element (or the borders
of the document).
body {
margin-top: 100px;
margin-right: 40px;
margin-bottom: 10px;
margin-left: 70px;
}
Padding
• Padding can also be understood as "filling". It
only defines the inner distance between the
border and the content of the element.
h1 {
background: yellow;
padding: 20px 20px 20px 80px;
}
Borders
➢border-width
➢border-color
➢border-style
Border-width
• The width of borders is defined by the property
border-width, which can obtain the values thin,
medium, and thick, or a numeric value, indicated
in pixels.
border-style
• The property border-color defines which color
the border has.
h1 {
border-width: thick;
border-style: dotted;
border-color: gold;
}
h2 {
border-width: 20px;
border-style: outset;
border-color: red;
}
p{
border-width: 1px;
border-style: dashed;
border-color: blue;
}
Floating elements
• An element can be floated to the right or to left
by using the property float. That is to say that
the box with its contents either floats to the
right or to the left in a document.
<div id="picture">
<img src="[Link]" alt="Bill Gates">
</div>
<p>causas naturales et antecedentes,
idciro etiam nostrarum voluntatum...</p>
#picture {
float:left;
width: 100px;
}
Web Technology
(KCS-602)
Unit 2
XML
Prepared By
Mr. Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Introduction to XML
•XML stands for Extensible Markup Language
•XML is a markup language much like HTML
•XML was designed to carry data, not to display
data
•XML tags are not predefined. You must define
your own tags
•XML is designed to be self-descriptive
•XML is a W3C Recommendation
•XML is platform independent and language
independent. 2
Features and Advantages of XML
The main features or advantages of XML are given below.
1) XML separates data from HTML
If you need to display dynamic data in your HTML
document, it will take a lot of work to edit the HTML
each time the data changes.
With XML, data can be stored in separate XML files. This
way you can focus on using HTML/CSS for display and
layout, and be sure that changes in the underlying data
will not require any changes to the HTML.
With a few lines of JavaScript code, you can read an
external XML file and update the data content of your
web page.
3
2) XML simplifies data sharing
In the real world, computer systems and databases
contain data in incompatible formats.
XML data is stored in plain text format. This provides a
software- and hardware-independent way of storing
data.
This makes it much easier to create data that can be
shared by different applications.
3) XML simplifies data transport
One of the most time-consuming challenges for
developers is to exchange data between incompatible
systems over the Internet.
Exchanging data as XML greatly reduces this complexity,
since the data can be read by different incompatible
applications. 4
4) XML simplifies Platform change
Upgrading to new systems (hardware or software
platforms), is always time consuming. Large amounts of
data must be converted and incompatible data is often
lost.
XML data is stored in text format. This makes it easier to
expand or upgrade to new operating systems, new
applications, or new browsers, without losing data.
5) XML increases data availability
Different applications can access your data, not only in
HTML pages, but also from XML data sources.
With XML, your data can be available to all kinds of
"reading machines" (Handheld computers, voice
machines, news feeds, etc), and make it more available
for blind people, or people with other disabilities. 5
XML is Not a Replacement for HTML
6
With XML You Invent Your Own Tags
7
HTML XML
HTML stands for Hyper Text XML stands for extensible
Markup Language. Markup Language.
HTML is static in nature. XML is dynamic in nature.
XML provides framework to
HTML is a markup language.
define markup languages.
HTML can ignore small errors. XML does not allow errors.
HTML tags are predefined tags. XML tags are user defined tags.
8
HTML does not preserve White space can be preserved
white spaces. in XML.
HTML does not carry data it XML carries the data to and
just display it. from database.
9
Example XML Document
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
10
Overall structure
•An XML document may start with one or more
processing instructions (PIs) or directives:
<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="[Link]"?>
•Following the directives, there must be exactly
one root element containing all the rest of the
XML:
<bookstore>
...
</bookstore>
11
XML Tree Structure
• XML documents are formed as element trees.
• An XML tree starts at a root element and
branches from the root to child elements.
• All elements can have sub elements (child
elements).
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
12
Elements and attributes
Attributes and elements are somewhat
interchangeable
Example using just elements:
<name>
<first>David</first>
<last>Matuszek</last>
</name>
Example using attributes:
<name first="David" last="Matuszek"></name>
You will find that elements are easier to use in your
programs--this is a good reason to prefer them
Attributes often contain metadata, such as unique
IDs
13
Well-formed XML
Every element must have both a start tag and an
end tag, e.g. <name> ... </name>
But empty elements can be abbreviated: <break />.
XML tags are case sensitive
XML tags may not begin with the letters xml, in any combination of
cases
Elements must be properly nested, e.g. not
<b><i>bold and italic</b></i>
Every XML document must have one and only one
root element
The values of attributes must be enclosed in single
or double quotes, e.g. <time unit="days">
Character data cannot contain < or &
14
Entities
•Five special characters must be written as
entities:
& for & (almost always necessary)
< for < (almost always necessary)
> for > (not usually necessary)
" for " (necessary inside double quotes)
' for ' (necessary inside single quotes)
•These entities can be used even in places
where they are not absolutely required
•These are the only predefined entities in XML
15
XML declaration
• The XML declaration looks like this:
<?xml version="1.0" encoding="UTF-8"
standalone="yes"?>
• The XML declaration is not required by browsers, but is
required by most XML processors (so include it!)
• If present, the XML declaration must be first--not even
whitespace should precede it
• Note that the brackets are <? and ?>
• version="1.0" is required (this is the only version so far)
• encoding can be "UTF-8" (ASCII) or "UTF-16" (Unicode), or
something else, or it can be omitted
• standalone tells whether there is a separate DTD
16
XML Encoding
•To avoid errors, you should specify the
encoding used, or save your XML files as UTF-8.
•Unicode is an industry standard for character
encoding of text documents. It defines (nearly)
every possible international character by a
name and a number.
•Unicode has two variants: UTF-8 and UTF-16.
•UTF = Universal character
set Transformation Format.
17
XML Encoding
19
Web Technology
(KCS-602)
Unit 2
DTD
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Introduction to DTD
2
Why Use a DTD?
•With a DTD, each of your XML files can carry a
description of its own format.
•With a DTD, independent groups of people can
agree to use a standard DTD for interchanging
data.
•Your application can use a standard DTD to
verify that the data you receive from the
outside world is valid.
•You can also use a DTD to verify your own data.
3
DTD - XML Building Blocks
PCDATA
• PCDATA means parsed character data.
• Think of character data as the text found between the start tag
and the end tag of an XML element.
• PCDATA is text that WILL be parsed by a parser. The text will
be examined by the parser for entities and markup.
• Tags inside the text will be treated as markup and entities will
be expanded.
• However, parsed character data should not contain any &, <, or
> characters; these need to be represented by the & <
and > entities, respectively.
4
CDATA
5
Declaring Elements
6
Empty Elements
• Empty elements are declared with the category
keyword EMPTY:
• <!ELEMENT element-name EMPTY>
Example:
<!ELEMENT br EMPTY>
XML example:
<br />
7
Elements with Parsed Character Data
Example:
8
Elements with any Contents
Example:
9
Elements with Children (sequences)
• Elements with one or more children are declared
with the name of the children elements inside
parentheses:
• <!ELEMENT element-name (child1)>
or
<!ELEMENT element-name (child1,child2,...)>
Example:
10
Declaring Only One Occurrence of an
Element
•<!ELEMENT element-name (child-name)>
Example:
11
Declaring Minimum One Occurrence
of an Element
<!ELEMENT element-name (child-name+)>
Example:
12
Declaring Zero or More Occurrences of an
Element
<!ELEMENT element-name (child-name*)>
Example:
13
Declaring either/or Content
Example:
14
TYPES of DTD
•Internal DTD
•External DTD
15
Internal DTD Declaration
If the DTD is declared inside the XML file, it should be
wrapped in a DOCTYPE definition with the following
syntax:
<!DOCTYPE root-element [element-declarations]>
Example XML document with an internal DTD:
<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
16
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this
weekend</body>
</note>
17
• !DOCTYPE note defines that the root element of
this document is note
• !ELEMENT note defines that the note element
contains four elements: "to,from,heading,body"
• !ELEMENT to defines the to element to be of type
"#PCDATA"
• !ELEMENT from defines the from element to be of
type "#PCDATA"
• !ELEMENT heading defines the heading element to
be of type "#PCDATA"
• !ELEMENT body defines the body element to be of
type "#PCDATA"
18
External DTD Declaration
• If the DTD is declared in an external file, it should
be wrapped in a DOCTYPE definition with the
following syntax:
• <!DOCTYPE root-element SYSTEM "filename">
• <?xml version="1.0"?>
<!DOCTYPE note SYSTEM "[Link]">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
19
And this is the file "[Link]" which contains
the DTD:
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
20
Web Technology
(KCS-602)
Unit 2
XML
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
XML PARSERS
•An XML parser is a software library or package
that provides interfaces for client applications to
work with an XML document.
•The XML Parser is designed to read the XML and
create a way for programs to use XML.
•XML parser validates the document and check
that the document is well formatted.
2
Types of XML Parsers
These are the two main types of XML
Parsers:
•DOM
•SAX
3
XML PARSERS
4
DOM (Document Object Model)
A DOM document is an object which contains all
the information of an XML document. It is
composed like a tree structure.
Features of DOM Parser
A DOM Parser creates an internal structure
in memory which is a DOM document object
and the client applications get information of
the original XML document by invoking
methods on this document object.
5
DOM
•The XML DOM defines a standard for
accessing and manipulating XML.
•The DOM is a W3C (World Wide Web
Consortium) standard.
•The DOM defines a standard for accessing
documents like XML and HTML.
6
The DOM is separated into 3 different parts /
levels:
•Core DOM - standard model for any
structured document
•XML DOM - standard model for XML
documents
•HTML DOM - standard model for HTML
documents
7
What is the XML DOM?
•The XML DOM defines the objects and
properties of all XML elements, and
the methods (interface) to access them.
•In other words: The XML DOM is a standard
for how to get, change, add, or delete XML
elements.
8
Advantages
1) It supports both read and write operations
and the API is very simple to use.
2) It is preferred when random access to
widely separated parts of a document is
required.
Disadvantages
1) It is memory inefficient. (consumes more
memory because the whole XML document
needs to loaded into memory).
2) It is comparatively slower than other
parsers.
9
XML SAX
•SAX (Simple API for XML) is an event-
based sequential
access parser API developed by the XML-
DEV mailing list for XMLdocuments.
•SAX provides a mechanism for reading data
from an XML document that is an
alternative to that provided by
the Document Object Model (DOM).
•SAX parsers operate on each piece of the
XML document sequentially.
10
Advantages
1) It is simple and memory efficient.
2) It is very fast and works for huge
documents.
Disadvantages
1) Clients never know the full information
because the data is broken into pieces.
11
Introduction to XML Schema
•XML Schema is an XML-based alternative
to DTD.
•An XML schema describes the structure of
an XML document.
12
Purpose of an XML Schema
• The purpose of an XML Schema is to define the legal
building blocks of an XML document, just like a DTD.
• defines elements that can appear in a document
• defines attributes that can appear in a document
• defines which elements are child elements
• defines the order of child elements
• defines the number of child elements
• defines whether an element is empty or can include
text
• defines data types for elements and attributes
• defines default and fixed values for elements and
attributes 13
Web Technology
(KCS-602)
Unit 2
XML
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Displaying your XML Files with CSS
With CSS (Cascading Style Sheets) you can add display information to an XML
document.
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="cd_catalog.css"?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
2
</CATALOG>
CATALOG
{
background-color: #ffffff;
width: 100%;
}
CD
{
display: block;
margin-bottom: 30pt;
margin-left: 0;
}
3
TITLE
{
color: #FF0000;
font-size: 20pt;
}
ARTIST
{
color: #0000FF;
font-size: 20pt;
}
4
COUNTRY,PRICE,YEAR,COMPANY
{
display: block;
color: #000000;
margin-left: 20pt;
}
5
Web Technology
(KCS-602)
Unit 2
DHTML
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
DHTML
• DHTML stands for Dynamic HTML, it is totally
different from HTML.
• The DHTML is based on the properties of the
HTML, javascript, CSS, and DOM (Document
Object Model which is used to access individual
elements of a document) which helps in
making dynamic content.
• It is the combination of HTML, CSS, JS, and
DOM.
• The DHTML make use of Dynamic object
model to make changes in settings and also in
properties and methods.
• It also makes uses of Scripting and it is also
part of earlier computing trends.
Why DHTML is used
DHTML is used to create interactive and
animated web pages that are generated in real-
time, also known as dynamic web pages so that
when such a page is accessed, the code within
the page is analyzed on the web server and the
resulting HTML is sent to the client’s web
browser.
Advantages
• Size of the files are compact in compared to
other interactional media like Flash or
Shockwave, and it downloads faster.
• It is supported by big browser manufacturers
like Microsoft and Netscape.
• Highly flexible and easy to make changes.
• Viewer requires no extra plug-ins for browsing
through the webpage that uses DHTML, they
do not need any extra requirements or special
software to view it.
Disadvantages
• It is not supported by all the browsers. It is
supported only by recent browsers such as
Netscape 6, IE 5.5, and Opera 5 like browsers.
• Learning of DHTML requires a lot of pre-
requisites languages such as HTML, CSS, JS,
• Implementation of different browsers are
different. So if it worked in one browser, it
might not necessarily work the same way in
another browser.
Difference between HTML and DHTML:
• HTML is a markup language while DHTML is a
collection of technologies.
• HTML is used to create static webpages while
DHTML is capable of creating dynamic
webpages.
• DHTML is used to create animations and
dynamic menus but HTML not used.
• HTML sites are slow upon client-side
technologies whereas DHTML sites are
comparatively faster.
• Web pages created using HTML are rather
simple and have no styling as it uses only one
language whereas DHTML uses HTML, CSS,
and Javascript which results in a much better
and way more presentable webpage.
Important Questions
• What is DHTML? (2014-15).
• What is advantage of using
DHTML.(Infosys Interview 2021).
Web Technology
(KCS-602)
Unit 3
Introduction to JavaScript Documents
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Index
• Introduction to JavaScript
• Documents
JavaScript Introduction
• JavaScript was designed to add
interactivity to HTML pages
• JavaScript is a scripting language
• A scripting language is a lightweight
programming language
• JavaScript is usually embedded directly
into HTML pages
• JavaScript is an interpreted language
(means that scripts execute without
preliminary compilation)
What can a JavaScript do?
• JavaScript gives HTML designers a
programming tool -
• JavaScript can put dynamic text into an
HTML page
• JavaScript can react to events -
• JavaScript can read and write HTML
elements
• JavaScript can be used to validate data.
Limitations with JavaScript
• Client-side JavaScript does not allow the
reading or writing of files. This has been
kept for security reason.
• JavaScript can not be used for
Networking applications because there is
no such support available.
• JavaScript doesn't have any
multithreading or multiprocess
capabilities.
JavaScript Vs Java
<html>
<head> </head>
<body>
<script type="text/javascript“>
[Link]("Hello World“)
</script> <p>This is web page body </p>
</body>
</html>
JavaScript in External File
<html> <head>
<script type="text/javascript" src="[Link]”>
</script>
</head>
<body> ....... </body>
</html>
JavaScript Variable
A JavaScript variable is simply a name of storage
location.
There are two types of variables in JavaScript : local
variable and global variable.
There are some rules while declaring a JavaScript
variable (also known as identifiers).
• Name must start with a letter (a to z or A to Z),
underscore( _ ), or dollar( $ ) sign.
• After first letter we can use digits (0 to 9), for
example value1.
• JavaScript variables are case sensitive
JavaScript local variable
A JavaScript local variable is declared inside
block or function. It is accessible within the
function or block only.
For example:
<script>
function abc(){
var x=10;//local variable
}
</script>
JavaScript global variable
A JavaScript global variable is accessible from any function. A variable i.e.
declared outside the function or declared with window object is
known as global variable.
For example:
<script>
var data=200;//gloabal variable
function a(){
[Link](data);
}
function b(){
[Link](data);
}
a();//calling JavaScript function
b();
</script>
Document Object Model
• The document object represents the whole html
document.
• When html document is loaded in the browser, it
becomes a document object.
• It is the root element that represents the html
document.
• it has properties and methods. By the help of
document object, we can add dynamic content to
our web page.
[Link]
Is same as
document
DOM
• According to W3C - "The W3C Document
Object Model (DOM) is a platform and
language-neutral interface that allows
programs and scripts to dynamically access
and update the content, structure, and style of
a document."
Properties of document object
Methods of document object
Example
<script type="text/javascript">
function printvalue(){
var nm=[Link];
alert("Welcome: "+nm);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="n1"/>
<input type="button" onclick="printvalue()" value="print
name"/>
</form>
[Link]() method
The [Link]() method returns the
element of specified id.
<script type="text/javascript">
function getcube(){
var number=[Link]("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/>
<br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Javascript - innerHTML
• The innerHTML property can be used to write
the dynamic html on the html document.
• It is used mostly in the web pages to generate
the dynamic html such as registration form,
comment form, links etc.
Javascript - innerText
• The innerText property can be used to write
the dynamic text on the html document. Here,
text will not be interpreted as html text but a
normal text.
• It is used mostly in the web pages to generate
the dynamic content such as writing the
validation message, password strength etc.
<script type="text/javascript" >
function validate() {
var msg;
if([Link]>5){
msg="good";
}
else{
msg="poor";
}
[Link]('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup=
"validate()">
Strength:<span id="mylocation">no strength</span>
</form>
Interview Questions
• What is the difference between Java and
JavaScript.
• Why do you think JavaScript plays important
role in web designing?
Web Technology
(KCS-602)
Unit 3
Forms, Statements
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
JavaScript Form Validation
➢ JavaScript can be used to validate data in HTML
forms before sending off the content to a server.
➢ Form data that typically are checked by a JavaScript
could be:
➢ has the user left required fields empty?
➢ has the user entered a valid e-mail address?
➢ has the user entered a valid date?
➢ has the user entered text in a numeric field?
function validateForm() {
let x =
[Link]["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
E-mail Validation
➢ The function below checks if the content has the
general syntax of an email.
➢ This means that the input data must contain an @
sign and at least one dot (.). Also, the @ must not be
the first character of the email address, and the last
dot must be present after the @ sign, and minimum
2 characters before the end.
JavaScript email validation
• email id must contain the @ and . character
• There must be at least one character before
and after the @.
• There must be at least two characters after .
(dot).
function validateemail()
{
var x=[Link];
var atposition=[Link]("@");
var dotposition=[Link](".");
if (atposition<1 || dotposition<atposition+2 ||
dotposition+2>=[Link])
{
alert("Please enter a valid e-mail address );
return false;
}
}
JavaScript form validation example
<script>
function validateform(){
var name=[Link];
var password=[Link];
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<form name="myForm" action="action_page.jsp"
onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = [Link]("numb").value;
// If x is Not a Number or less than one or greater than 10
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
[Link]("demo").innerHTML = text;
}
</script>
Interview Questions
• Write a program in JavaScript to check
whether entered text field is blank or not.
• Write a program in JavaScript to check
whether entered email id is valid or not.
• Write a program in JavaScript to validate Login
panel.
Web Technology
(KCS-602)
Unit 3
Functions, Objects
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
JavaScript Functions
• A function is a reusable code-block that will be
executed by an event, or when the function is called.
• To keep the browser from executing a script when
the page loads, you can put your script into a
function.
• A function contains code that will be executed by an
event or by a call to that function.
• You may call a function from anywhere within the
page (or even from other pages if the function is
embedded in an external .js file).
JavaScript Function Syntax
function functionname()
{
some code to be executed
}
JavaScript Functions
A function is a block of code that will be executed when
"someone" calls it.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Functions With a Return Value
• Sometimes you want your function to return a value
back to where the call was made.
• This is possible by using the return statement.
• When using the return statement, the function will
stop executing, and return the specified value.
Calling a Function with Arguments
• When you call a function, you can pass along some
values to it, these values are called arguments or
parameters.
• These arguments can be used inside the function.
<button onclick="myFunction(‘Abhishek
',’Professor')">click here</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
Functions With a Return Value
• Sometimes you want your function to return a value back to
where the call was made.
• This is possible by using the return statement.
• When using the return statement, the function will stop
executing, and return the specified value.
Syntax
function myFunction()
{
var x=5;
return x;
}
Examples
<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b
}
</script>
</head>
<body>
<script type="text/javascript">
[Link](product(4,3))
</script>
<p>The script in the body section calls a function with two parameters
(4 and 3).</p>
<p>The function will return the product of these two parameters.</p>
</body>
</html>
Browser Object Model
The Browser Object Model (BOM) is used to
interact with the browser.
The default object of browser is window means
you can call all the functions of window by
specifying window or directly. For example:
[Link]("hello javatpoint");
is same as:
alert("hello javatpoint");
Browser Object Model
Window Object
• The window object represents a window in
browser. An object of window is created
automatically by the browser.
• Window is the object of browser, it is not the
object of javascript. The javascript objects are
string, array, date etc.
Window Object
JavaScript Popup Boxes
• In JavaScript we can create three kinds of
popup boxes: Alert box, Confirm box, and
Prompt box.
Alert Box
An alert box is often used if you want to make
sure information comes through to the user.
When an alert box pops up, the user will have
to click "OK" to proceed.
Syntax:
alert("sometext")
Confirm Box
A confirm box is often used if you want the user
to verify or accept something.
When a confirm box pops up, the user will have
to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If
the user clicks "Cancel", the box returns false.
Syntax:
confirm("sometext")
Prompt Box
A prompt box is often used if you want the user to
input a value before entering a page.
When a prompt box pops up, the user will have to click
either "OK" or "Cancel" to proceed after entering an
input value.
If the user clicks "OK" the box returns the input value.
If the user clicks "Cancel" the box returns null.
Syntax:
prompt("sometext","defaultvalue“)
JavaScript Objects
• In real life, a car is an object.
• A car has properties like weight and color, and
methods like start and stop:
Properties Methods
</body>
</html>
Web Technology
(KCS-602)
Unit 3
Introduction to AJAX
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Ajax
• AJAX stands for Asynchronous JavaScript and XML. AJAX
is a new technique for creating better, faster, and more
interactive web applications with the help of XML,
HTML, CSS and Java Script.
• Ajax uses XHTML for content and CSS for presentation,
as well as the Document Object Model and JavaScript
for dynamic content display.
• Conventional web application transmit information to
and from the sever using synchronous requests. This
means you fill out a form, hit submit, and get directed to
a new page with new information from the server.
Technologies Used in AJAX
JavaScript
• Loosely typed scripting language
• JavaScript function is called when an event in a page
occurs
• Glue for the whole AJAX operation
DOM
• API for accessing and manipulating structured
documents
• Represents the structure of XML and HTML
documents
CSS
• Allows for a clear separation of the
presentation style from the content and
may be changed programmatically by
JavaScript
XMLHttpRequest
• JavaScript object that performs
asynchronous interaction with the server
AJAX Examples
Google Maps
• A user can drag the entire map by using the
mouse instead of clicking on a button or
something
• [Link]
Google Suggest
• As you type, Google will offer suggestions. Use
the arrow keys to navigate the results
• [Link]
en
Gmail
• Gmail is a new kind of webmail, built on the idea that
email can be more intuitive, efficient and useful
• [Link]
How AJAX Works
Steps of AJAX Operation
1. An event occurs in a web page (the page is loaded, a
button is clicked)
2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web
server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by
JavaScript
XMLHttpRequest
• The XMLHttpRequest object is the key to AJAX. It has
been available ever since Internet Explorer 5.5 was
released in July 2000, but not fully discovered before
people started to talk about AJAX and Web 2.0 in
2005.
• 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 web server using HTTP,
establishing an independent connection channel
between a web page's Client-Side and Server-Side.
XMLHttpRequest Methods
abort()
Cancels the current request.
getAllResponseHeaders()
Returns the complete set of HTTP headers as a
string.
open( method, URL, async, userName, password )
Specifies the method, URL, and other optional
attributes of a request.
send( content )
Sends the request.
XMLHttpRequest Properties
• onreadystatechange
An event handler for an event that fires at
every state change.
• readyState
The readyState property defines the current
state of the XMLHttpRequest object.
• responseText
Returns the response as a string.
• responseXML
Returns the response as XML. This property returns
an XML document object, which can be examined
and parsed using W3C DOM node tree methods and
properties.
• status
Returns the status as a number (e.g. 404 for "Not
Found" and 200 for "OK").
• statusText
Returns the status as a string (e.g. "Not Found" or
"OK").
Current Issues with AJAX
Complexity is increased
• Server side developers will need to understand that
presentation logic will be required in the HTML client
pages as well as in the server-side logic
• Page developers must have JavaScript technology
skills
AJAX-based applications can be difficult to debug,
test, and maintain
• JavaScript is hard to test - automatic testing is hard
• Weak modularity in JavaScript
• Lack of design patterns or best practice guidelines
yet
Toolkits/Frameworks are not mature yet
• Most of them are in beta phase
No standardization of the XMLHttpRequest yet
• Future version of IE will address this
No support of XMLHttpRequest in old browsers
• Iframe will help
JavaScript technology dependency & incompatibility
• Must be enabled for applications to function
• Still some browser incompatibilities
JavaScript code is visible to a hacker
• Poorly designed JavaScript code can invite security problem
Web Technology
(KCS-602)
Unit 3
Networking: Internet Addressing, InetAddress,
Factory Methods, Instance Methods
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Java Socket Programming
• Java Socket programming is used for
communication between the applications
running on different JRE.
• Java Socket programming can be connection-
oriented or connection-less.
• Socket and ServerSocket classes are used for
connection-oriented socket programming.
• DatagramSocket and DatagramPacket classes
are used for connection-less socket
programming.
The client in socket programming must
know two information:
• IP Address of Server, and
• Port number.
Socket class
A socket is simply an endpoint for
communications between the machines.
The Socket class can be used to create a socket.
ServerSocket class
The ServerSocket class can be used to create a
server socket. This object is used to establish
communication with the clients.
Socket
Method Description
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Datagrams
• Datagrams are collection of information sent
from one device to another device via the
established network.
• When the datagram is sent to the targeted
device, there is no assurance that it will reach to
the target device safely and completely.
• It may get damaged or lost in between. Likewise,
the receiving device also never know if the
datagram received is damaged or not.
Java DatagramSocket and DatagramPacket
• Java DatagramSocket and DatagramPacket
classes are used for connection-less socket
programming.
• Java DatagramSocket class represents a
connection-less socket for sending and
receiving datagram packets.
• A datagram is basically an information but
there is no guarantee of its content, arrival or
arrival time.
• Java DatagramPacket is a message that can be
sent or received. If you send multiple packet,
it may arrive in any order. Additionally, packet
delivery is not guaranteed.
Constructors of DatagramSocket class
• DatagramSocket() throws SocketException: it creates
a datagram socket and binds it with the available
Port Number on the localhost machine.
• DatagramSocket(int port) throws SocketException: it
creates a datagram socket and binds it with the given
Port Number.
• DatagramSocket(int port, InetAddress address)
throws SocketException: it creates a datagram socket
and binds it with the specified port number and host
address.
Java DatagramPacket Class Methods
Method Description
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Transactions
• A transaction in MySQL is a sequential group of
statements, queries, or operations such as select, insert,
update or delete to perform as a one single work unit
that can be committed or rolled back.
• If the transaction makes multiple modifications into the
database,
two things happen:
• Either all modification is successful when the transaction
is committed.
• Or, all modifications are undone when the transaction is
rollback.
Properties of Transaction
The transaction contains mainly four
properties, which referred to
as ACID property. The ACID property
stands for:
• Atomicity
• Consistency
• Isolation
• Durability
• Atomicity: This property ensures that all
statements or operations within the
transaction unit must be executed
successfully. Otherwise, if any operation is
failed, the whole transaction will be aborted,
and it goes rolled back into their previous
state.
• Consistency: This property ensures that the
database changes state only when a
transaction will be committed successfully. It
is also responsible for protecting data from
crashes.
• Isolation: This property guarantees that each
operation in the transaction unit operated
independently. It also ensures that statements
are transparent to each other.
• Durability: This property guarantees that the
result of committed transactions persists
permanently even if the system crashes or
failed.
MySQL transaction statements
By default, MySQL automatically commits the
changes permanently to the database.
To force MySQL not to commit changes
automatically, you use the following statement.
SET autocommit = 0;
➢ROLLBACK;
• START TRANSACTION;
• SELECT * FROM Orders;
• INSERT INTO Orders(order_id,
prod_name, order_num, order_date)
• VALUES (6, 'Printer', 5654, '2020-01-10');
• SAVEPOINT my_savepoint;
• INSERT INTO Orders(order_id,
prod_name, order_num, order_date)
• VALUES (7, 'Ink', 5894, '2020-03-10');
• ROLLBACK TO SAVEPOINT my_savepoint;
MySQL Stored Procedure
• A procedure (often called a stored procedure)
is a collection of pre-compiled SQL statements
stored inside the database.
• It is a subroutine or a subprogram in the
regular computing language.
• A procedure always contains a name,
parameter lists, and SQL statements.
• It was first introduced in MySQL version 5.
Presently, it can be supported by almost all
relational database systems.
How to create a procedure?
DELIMITER &&
CREATE PROCEDURE procedure_name [[IN | OUT |
INOUT] parameter_name datatype [, parameter
datatype]) ]
BEGIN
Declaration_section
Executable_section
END &&
DELIMITER ;
DROP PROCEDURE
DROP PROCEDURE [IF EXISTS]
stored_procedure_name;
Web Technology
(KCS-602)
Unit 4
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Index
• JDBC
• Types of JDBC Driver
JDBC
• Java JDBC is a java API to connect and execute
query with the database. JDBC API uses jdbc
drivers to connect with the database.
JDBC Driver
JDBC Driver is a software component that
enables java application to interact with the
database.
There are 4 types of JDBC drivers:
• JDBC-ODBC bridge driver
• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
• The JDBC-ODBC bridge driver uses ODBC
driver to connect to the database.
• The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls.
• This is now discouraged because of thin driver.
Advantages:
• easy to use.
• can be easily connected to any database.
Disadvantages:
• Performance degraded because JDBC method
call is converted into the ODBC function calls.
• The ODBC driver needs to be installed on the
client machine.
Native-API driver
• The Native API driver uses the client-side
libraries of the database.
• The driver converts JDBC method calls
into native calls of the database API.
• It is not written entirely in java.
Advantage:
• performance upgraded than JDBC-ODBC
bridge driver.
Disadvantage:
• The Native driver needs to be installed on the
each client machine.
• The Vendor client library needs to be installed
on client machine.
3) Network Protocol driver
• The Network Protocol driver uses middleware
(application server) that converts JDBC calls
directly or indirectly into the vendor-specific
database protocol.
• It is fully written in java.
Advantage:
• No client side library is required because of
application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
• Network support is required on client
machine.
• Requires database-specific coding to be done
in the middle tier.
4) Thin driver
• The thin driver converts JDBC calls directly
into the vendor-specific database protocol.
• That is why it is known as thin driver. It is fully
written in Java language.
Advantage:
• Better performance than all other drivers.
• No software is required at client side or server
side.
Disadvantage:
• Drivers depends on the Database.
AKTU Semester Questions
• What is JDBC? Explain the drivers used in
JDBC. Write a JDBC program for insert and
display the record of employees using
Prepared Statement.(2018-19)
• What do you mean by JDBC driver in Java?
Explain web database. How do you manage a
database through web? Explain with the help
of example.(2016-17)
Web Technology
(KCS-602)
Unit 4
Prepared Statements
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Index
• JDBC Connection
5 Steps to connect to the database in java
There are 5 steps to connect any java application
with the database in java using JDBC.
They are as follows
• Register the driver class
• Creating connection
• Creating statement
• Executing queries
• Closing connection
1) Register the driver class
The forName() method of Class class is used to
register the driver class.
This method is used to dynamically load the
driver class.
Syntax of forName() method
public static void forName(String className)
throws ClassNotFoundException
2) Create the connection object
The getConnection() method of DriverManager
class is used to establish connection with the
database.
Syntax of getConnection() method
1) public static Connection getConnection(String url
)
throws SQLException
2) public static Connection getConnection(String url
,String name,String password)
throws SQLException
3) Create the Statement object
The createStatement() method of Connection
interface is used to create statement. The
object of statement is responsible to execute
queries with the database.
Syntax of createStatement() method
public Statement createStatement()
throws SQLException
Example to create the statement object
Statement stmt=[Link]();
4) Execute the query
The executeQuery() method of Statement interface is
used to execute queries to the database. This method
returns the object of ResultSet that can be used to get
all the records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)
throws SQLException
Example to execute query
ResultSet rs=[Link]("select * from emp");
while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}
5) Close the connection object
By closing connection object statement and
ResultSet will be closed automatically. The
close() method of Connection interface is used
to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
[Link]();
Example to connect to the mysql database
we are using MySql as the database. So we need to know
following informations for the mysql database:
• Driver class: The driver class for the mysql database
is [Link].
• Connection URL: The connection URL for the mysql
database is jdbc:mysql://localhost:3306/united
• where jdbc is the API, mysql is the database, localhost is
the server name on which mysql is running, we may also
use IP address, 3306 is the port number and united is the
database name.
• Username: The default username for the mysql database
is root.
• Password: Password is given by the user at the time of
installing the mysql database. In this example, we are
going to use admin as the password.
Let's first create a table in the mysql database,
but before creating table, we need to create
database first.
• create database united;
• use united;
• create table emp(id int(10),name varchar(40),
age int(3));
import [Link].*;
class MysqlCon{
public static void main(String args[]){
try{
[Link]("[Link]");
Connection con=[Link](
"jdbc:mysql://localhost:3306/united","root",“admin");
Statement stmt=[Link]();
ResultSet rs=[Link]("select * from emp");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link]
tring(3));
[Link]();
}catch(Exception e){ [Link](e);}
}
}
To connect java application with the mysql
database [Link] file is
required. loaded.
DriverManager class
The DriverManager class acts as an interface
between user and drivers.
It keeps track of the drivers that are available
and handles establishing a connection
between a database and the appropriate
driver.
public static Connection getConnection(String
url,String userName,String password)
is used to establish the connection with the
specified url, username and password.
Connection interface
The Connection interface is a factory of
Statement, PreparedStatement, and
DatabaseMetaData i.e. object of Connection
can be used to get the object of Statement
and DatabaseMetaData.
The Connection interface provide many
methods for transaction management like
commit(),rollback() etc.
By default, connection commits the changes
after executing queries.
Commonly used methods of Connection
interface:
1) public Statement createStatement(): creates
a statement object that can be used to
execute SQL queries.
2) public void commit(): saves the changes
made since the previous commit/rollback
permanent.
3) public void rollback(): Drops all changes
made since the previous commit/rollback.
Statement interface
The Statement interface provides methods to
execute queries with the database.
Commonly used methods of Statement interface:
1) public ResultSet executeQuery(String sql): is
used to execute SELECT query. It returns the
object of ResultSet.
2) public int executeUpdate(String sql): is used to
execute specified query, it may be create, drop,
insert, update, delete etc.
3) public boolean execute(String sql): is used to
execute queries that may return multiple
results.
ResultSet interface
The object of ResultSet maintains a cursor
pointing to a particular row of data.
Initially, cursor points to before the first
row.
By default, ResultSet object can be moved
forward only and it is not updatable.
Commonly used methods of ResultSet interface
1) public boolean next():
is used to move the cursor to the one row next from the current
position.
2) public boolean previous():
is used to move the cursor to the one row previous from the
current position.
3) public boolean first():
is used to move the cursor to the first row in result set object.
4) public boolean last():
is used to move the cursor to the last row in result set object.
5) public boolean absolute(int row):
is used to move the cursor to the specified row number in the
ResultSet object.
7) public int getInt(int columnIndex):
is used to return the data of specified column index
of the current row as int.
8) public int getInt(String columnName):
is used to return the data of specified column name
of the current row as int.
9) public String getString(int columnIndex):
is used to return the data of specified column index
of the current row as String.
10) public String getString(String columnName):
is used to return the data of specified column name
of the current row as String.
AKTU Semester Questions
• What are the various types of JDBC drivers?
Write steps to connect database with the web
application using JDBC.(2019-20)
Web Technology
(KCS-602)
Unit 5
Servlets
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Servlets
• Servlet technology is used to create web application
(resides at server side and generates dynamic web
page).
• Servlet technology is robust and scalable because of
java language. Before Servlet, CGI (Common Gateway
Interface) scripting language was popular as a server-
side programming language. But there was many
disadvantages of this technology.
Servlets Architecture:
Advantage of Servlet
There are many advantages of servlet over CGI. The web
container creates threads for handling the multiple
requests to the servlet. Threads have a lot of benefits over
the Processes such as they share a common memory area,
lightweight, cost of communication between the threads
are low.
The basic benefits of servlet are as follows:
• better performance: because it creates a thread for each
request not process.
• Portability: because it uses java language.
• Robust: Servlets are managed by JVM so we don't need to
worry about memory leak, garbage collection etc.
• Secure: because it uses java language
Servlet API
• The [Link] and [Link] packages
represent interfaces and classes for servlet api.
• The [Link] package contains many interfaces
and classes that are used by the servlet or web
container. These are not specific to any protocol.
• The [Link] package contains interfaces
and classes that are responsible for http requests
only.
Interfaces in [Link] package
There are many interfaces in [Link] package.
They are as follows:
• Servlet
• ServletRequest
• ServletResponse
• RequestDispatcher
• ServletConfig
• ServletContext
• SingleThreadModel
• Filter
Classes in [Link] package
There are many classes in [Link] package. They are
as follows:
• GenericServlet
• ServletInputStream
• ServletOutputStream
• ServletRequestWrapper
• ServletResponseWrapper
• ServletRequestEvent
• ServletContextEvent
• ServletRequestAttributeEvent
• ServletContextAttributeEvent
• ServletException
• UnavailableException
Interfaces in [Link] package
There are many interfaces in [Link]
package. They are as follows:
• HttpServletRequest
• HttpServletResponse
• HttpSession
• HttpSessionListener
• HttpSessionAttributeListener
• HttpSessionBindingListener
• HttpSessionActivationListener
Classes in [Link] package
There are many classes in [Link]
package. They are as follows:
• HttpServlet
• Cookie
• HttpServletRequestWrapper
• HttpServletResponseWrapper
• HttpSessionEvent
• HttpSessionBindingEvent
Servlet Life Cycle
• First the HTTP requests coming to the server
are delegated to the servlet container.
• The servlet container loads the servlet before
invoking the service() method.
• Then the servlet container handles multiple
requests by spawning multiple threads, each
thread executing the service() method of a
single instance of the servlet.
Servlets - Life Cycle
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Servlets Architecture:
The init() method :
The init method is designed to be called only once. It is
called when the servlet is first created, and not called
again for each user request. So, it is used for one-
time initializations, just as with the init method of
applets.
public void init() throws ServletException { //
Initialization code... }
The service() method :
The service() method is the main method to perform
the actual task. The servlet container (i.e. web
server) calls the service() method to handle requests
coming from the client( browsers) and to write the
formatted response back to the client.
public void service(ServletRequest request,
ServletResponse response) throws ServletException,
IOException{ }
The doGet() Method
A GET request results from a normal request for a URL or
from an HTML form that has no METHOD specified and it
should be handled by doGet() method.
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException { // Servlet code }
The doPost() Method
A POST request results from an HTML form that specifically
lists POST as the METHOD and it should be handled by
doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException { // Servlet code }
The destroy() method :
The destroy() method is called only once at the end of
the life cycle of a servlet. This method gives your
servlet a chance to close database connections, halt
background threads, write cookie lists or hit counts
to disk, and perform other such cleanup activities.
public void destroy() { // Finalization code... }
Web Technology
(KCS-602)
Unit 5
Session Tracking, Cookies
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Cookies in Servlet
• A cookie is a small piece of information that is
persisted between the multiple client
requests.
• A cookie has a name, a single value, and
optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a
version number.
How Cookie works
• By default, each request is considered as a
new request.
• In cookies technique, we add cookie with
response from the servlet.
• 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. Thus, we
recognize the user as the old user
Types of Cookie
There are 2 types of cookies in servlets.
➢Non-persistent cookie
➢Persistent cookie
➢Non-persistent cookie
It is valid for single session only. It is removed
each time when user closes the browser.
➢Persistent cookie
It is valid for multiple session . It is not removed
each time when user closes the browser. It is
removed only if user logout or signout.
Advantage of Cookies
• Simplest technique of maintaining the state.
• Cookies are maintained at client side.
Disadvantage of Cookies
• It will not work if cookie is disabled from the
browser.
• Only textual information can be set in Cookie
object.
Cookie class
[Link] class provides the
functionality of using cookies. It provides a lot
of useful methods for cookies.
Constructor of Cookie class
Useful Methods of Cookie class
Other methods required for using Cookies
public void addCookie(Cookie ck):method of
HttpServletResponse interface is used to add
cookie in response object.
public Cookie[] getCookies():method of
HttpServletRequest interface is used to return
all the cookies from the browser.
How to create Cookie
Cookie ck=new Cookie("user",“Abhishek");
//creating cookie object
[Link](ck);
//adding cookie in the response
How to delete Cookie
Cookie ck=new Cookie("user","");
//deleting value of cookie
[Link](0);
//changing the maximum age to 0 seconds
[Link](ck);
//adding cookie in the response
How to get Cookies
Cookie ck[]=[Link]();
for(int i=0;i<[Link];i++)
{
[Link]("<br>"+ck[i].getName()+" "+ck[i].getValue());
//printing name and value of cookie
}
Session Tracking in Servlets
• Session simply means a particular interval of
time.
• Session Tracking is a way to maintain state
(data) of an user. It is also known as session
management in servlet.
Session Tracking in Servlets
• Http protocol is a stateless so we need to
maintain state using session tracking
techniques.
• Each time user requests to the server, server
treats the request as the new request. So we
need to maintain the state of an user to
recognize to particular user.
• HTTP is stateless that means each request is
considered as the new request.
Web Technology
(KCS-602)
Unit 5
Java Server Pages (JSP): Introduction
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Index
• About JSP
• Advantages of JSP
• Architecture of JSP
JSP
• Java Server 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.
• JSP tags can be used for a variety of purposes, such
as retrieving information from a database or
registering user preferences, accessing JavaBeans
components, passing control between pages and
sharing information between requests, pages etc.
Advantages of JSP:
• vs. Active Server Pages (ASP): The advantages of JSP
are twofold. First, the dynamic part is written in Java,
not Visual Basic or other MS specific language, so it is
more powerful and easier to use. Second, it is
portable to other operating systems and non-
Microsoft Web servers.
• vs. Pure Servlets: It is more convenient to write (and
to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
• vs. JavaScript: JavaScript can generate HTML
dynamically on the client but can hardly interact with
the web server to perform complex tasks like
database access and image processing etc.
• vs. Static HTML: Regular HTML, of course, cannot
contain dynamic information.
JSP - Architecture
• JSP page is translated into servlet by the help
of JSP translator.
• The JSP translator is a part of webserver that
is responsible to translate the JSP page into
servlet.
• After that Servlet page is compiled by the
compiler and gets converted into the class file.
• All the processes that happens in servlet is
performed on JSP later like initialization,
committing response to the browser and
destroy.
Life cycle of a JSP Page
• The JSP pages follows these phases:
• Translation of JSP Page
• Compilation of JSP Page
• Classloading (class file is loaded by the classloader)
• Instantiation (Object of the Generated Servlet is created).
• Initialization ( jspInit() method is invoked by the container).
• Reqeust processing ( _jspService() method is invoked by the
container).
• Destroy ( jspDestroy() method is invoked by the container).
• Note: jspInit(), jspService() and jspDestroy() are the life
cycle methods of JSP.
Directory structure of JSP
• The directory structure of JSP page is same as
servlet. We contains the jsp page outside the WEB-
INF folder or in any directory.
JSP API
The JSP API consists of two packages:
• [Link]
• [Link]
[Link] package
The [Link] package has two interfaces and
classes.
The two interfaces are as follows:
• JspPage
• HttpJspPage
The classes are as follows:
• JspWriter
• PageContext
• JspFactory
• JspEngineInfo
• JspException
• JspError
The JspPage interface
• According to the JSP specification, all the generated servlet
classes must implement the JspPage interface.
• It extends the Servlet interface.
• It provides two life cycle methods.
Methods of JspPage interface
• public void jspInit(): It is invoked only once
during the life cycle of the JSP when JSP page
is requested firstly. It is used to perform
initialization. It is same as the init() method of
Servlet interface.
• public void jspDestroy(): It is invoked only
once during the life cycle of the JSP before the
JSP page is destroyed. It can be used to
perform some clean up operation.
The HttpJspPage interface
• The HttpJspPage interface provides the one
life cycle method of JSP. It extends the JspPage
interface.
Method of HttpJspPage interface:
• public void _jspService(): It is invoked each
time when request for the JSP page comes to
the container. It is used to process the
request.
• The underscore _ signifies that you cannot
override this method.
Important Questions
• Explain the directory structure of JSP.
• What is the advantage of using jsp.
• What is server side language.
Web Technology
(KCS-602)
Unit 5
Scripting, Standard Actions
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Index
• JSP Scriptlet tag
• JSP Implicit object
JSP Scriptlet tag (Scripting elements)
In JSP, java code can be written inside the jsp
page using the scriptlet tag.
JSP Scripting elements
The scripting elements provides the ability to
insert java code inside the jsp.
There are three types of scripting elements:
• scriptlet tag
• expression tag
• declaration tag
JSP scriptlet tag
A scriptlet tag is used to execute java source code in
JSP. Syntax is as follows:
<% java source code %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome
message.
<html>
<body>
<% [Link]("welcome to jsp"); %>
</body>
</html>
Example of JSP scriptlet tag that prints the user name
File: [Link]
<html>
<body>
<form action="[Link]">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
File: [Link]
<html>
<body>
<%
String name=[Link]("uname");
[Link]("welcome "+name);
%>
</form>
</body>
</html>
JSP expression tag
The code placed within JSP expression tag is written to
the output stream of the response.
So you need not write [Link]() to write data. It is
mainly used to print the values of variable or method.
Syntax of JSP expression tag
<%= statement %>
Example of JSP expression tag
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Note: Do not end your statement with semicolon in case
of expression tag.
Example of JSP expression tag that prints current time
[Link]
<html>
<body>
Current Time:
<%= [Link]().getTime() %>
</body>
</html>
JSP Declaration Tag
The JSP declaration tag is used to declare fields
and methods.
The code written inside the jsp declaration tag is
placed outside the service() method of auto
generated servlet.
So it doesn't get memory at each request.
Syntax of JSP declaration tag
The syntax of the declaration tag is as follows:
<%! field or method declaration %>
Example of JSP declaration tag that declares field
[Link]
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example of JSP declaration tag that declares method
[Link]
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
AKTU SEMESTER QUESTION
• Discuss JSP in Detail. [2019-20]
• Write a program in jsp to fetch the details
of user from html page using tomcat
server.
Web Technology
(KCS-602)
Unit 5
Implicit Objects
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
JSP Implicit Objects
• There are 9 jsp implicit objects.
• These objects are created by the web
container that are available to all the jsp
pages.
• The available implicit objects are out, request,
config, session, application etc
A list of the 9 implicit objects
1) JSP out implicit object
For writing any data to the buffer, JSP provides an implicit
object named out. It is the object of JspWriter. In case
of servlet you need to write:
PrintWriter out=[Link]();
But in JSP, you don't need to write this code.
In this example we are simply displaying time.
[Link]
<html>
<body>
<% [Link]("Today is:"+[Link]().g
etTime()); %>
</body>
</html>
2) JSP request implicit object
• The JSP request is an implicit object of type
HttpServletRequest i.e. created for each jsp
request by the web container.
• It can be used to get request information such
as parameter, header information, remote
address, server name, server port, content
type, character encoding etc.
• It can also be used to set, get and remove
attributes from the jsp request scope.
Example of JSP request implicit object
[Link]
<form action="[Link]">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
[Link]
<%
String name=[Link]("uname");
[Link]("welcome "+name);
%>
3) JSP response implicit object
• In JSP, response is an implicit object of type
HttpServletResponse.
• The instance of HttpServletResponse is
created by the web container for each jsp
request.
• It can be used to add or manipulate response
such as redirect response to another resource,
send error etc.
4) JSP config implicit object
• In JSP, config is an implicit object of
type ServletConfig.
• This object can be used to get initialization
parameter for a particular JSP page.
• The config object is created by the web
container for each jsp page.
• Generally, it is used to get initialization
parameter from the [Link] file.
Example of config implicit object:
[Link]
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
[Link] file
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/[Link]</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>[Link]</param-
value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
[Link]
<%
[Link]("Welcome “
+[Link]("uname"));
String driver=[Link]("dname");
[Link]("driver name is="+driver);
%>
5) JSP application implicit object
• In JSP, application is an implicit object of
type ServletContext.
• The instance of ServletContext is created only
once by the web container when application
or project is deployed on the server.
• This object can be used to get initialization
parameter from configuaration file ([Link]).
• It can also be used to get, set or remove
attribute from the application scope.
[Link]
<%
[Link]("Welcome "+[Link]
("uname"));
String driver=[Link]("dna
me");
[Link]("driver name is="+driver);
%>
6) session implicit object
In JSP, session is an implicit object of type
[Link] Java developer can use this object to
set,get or remove attribute or to get session
information.
[Link]
<html>
<body>
<form action="[Link]">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
[Link]
<html>
<body>
<%
String name=[Link]("uname");
[Link]("Welcome "+name);
[Link]("user",name);
<a href="[Link]">second jsp page</a>
%>
</body>
</html>
[Link]
<html>
<body>
<%
String name=(String)[Link]("user");
[Link]("Hello "+name);
%>
</body>
</html>
7) pageContext implicit object
In JSP, pageContext is an implicit object of type
PageContext class.
The pageContext object can be used to set,get
or remove attribute from one of the following
scopes:
• page
• request
• session
• application
Example of pageContext implicit object
[Link]
<html>
<body>
<form action="[Link]">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
[Link]
<html>
<body>
<%
String name=[Link]("uname");
[Link]("Welcome "+name);
[Link]("user",name,[Link]
SSION_SCOPE);
<a href="[Link]">second jsp page</a>
%>
</body>
</html>
[Link]
<html>
<body>
<%
String name=(String)[Link]("use
r",PageContext.SESSION_SCOPE);
[Link]("Hello "+name);
%>
</body>
</html>
8) page implicit object:
In JSP, page is an implicit object of type Object
class.
his object is assigned to the reference of auto
generated servlet class. It is written as:
Object page=this;
9) exception implicit object
• In JSP, exception is an implicit object of type
[Link] class.
• This object can be used to print the exception. But it
can only be used in error pages.
Example of exception implicit object:
[Link]
<%@ page isErrorPage="true" %>
<html>
<body>
Sorry following exception occured:<%= exception %>
</body>
</html>
Web Technology
(KCS-602)
Unit 5
Directives
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
JSP directives
The jsp directives are messages that tells the
web container how to translate a JSP page
into the corresponding servlet.
There are three types of directives:
• page directive
• include directive
• taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>
JSP page directive
The page directive defines attributes that apply to an
entire JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>
Attributes of JSP page directive
• import
• contentType
• Language
• isThreadSafe
• session
• pageEncoding
• errorPage
• isErrorPage
import
The import attribute is used to import
class,interface or all the members of a [Link]
is similar to import keyword in java class or
interface.
Example of import attribute
<html>
<body>
<%@ page import="[Link]" %>
Today is: <%= new Date() %>
</body>
</html>
contentType
The contentType attribute defines the
MIME(Multipurpose Internet Mail Extension)
type of the HTTP [Link] default value is
"text/html;charset=ISO-8859-1".
Example of contentType attribute
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new [Link]() %>
</body>
</html>
language
• The language attribute specifies the scripting
language used in the JSP page.
• The default value is "java".
errorPage
The errorPage attribute is used to define the error
page, if exception occurs in the current page, it
will be redirected to the error page.
Example of errorPage attribute
//[Link]
<html>
<body>
<%@ page errorPage="[Link]" %>
<%= 100/0 %>
</body>
</html>
isErrorPage
The isErrorPage attribute is used to declare that the current
page is the error page.
Note: The exception object can only be used in the error
page.
//[Link]
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body>
</html>
Jsp Include Directive
• The include directive is used to include the
contents of any resource it may be jsp file, html
file or text file.
• The include directive includes the original
content of the included resource at page
translation time (the jsp page is translated only
once so it will be better to include static
resource).
Syntax of include directive
<%@ include file="resourceName" %>
Example of include directive
In this example, we are including the content of the
[Link] file.
<html>
<body>
<%@ include file="[Link]" %>
Today is: <%= [Link]().getTime
() %>
</body>
</html>
Note: The include directive includes the original
content, so the actual page size grows at runtime.
JSP Taglib directive
The JSP taglib directive is used to define a tag
library that defines many tags. We use the TLD
(Tag Library Descriptor) file to define the tags
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixo
ftaglibrary" %>
<html>
<body>
<%@ taglib uri="[Link]
prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>
JSP Action Tags
• There are many JSP action tags or elements.
• Each JSP action tag is used to perform some
specific tasks.
• The action tags are used to control the flow
between pages and to use Java Bean.
jsp:forward action tag
The jsp:forward action tag is used to forward the
request to another resource it may be jsp, html or
another resource.
Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL | <%= expression %>" />
Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="paramete
rvalue | <%=expression%>" />
</jsp:forward>
Example of jsp:forward action tag
without parameter
[Link]
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="[Link]" />
</body>
</html>
Example of jsp:forward action tag with
parameter
<html>
<body>
<h2>this is index page</h2>
</body>
</html>
[Link]
<html>
<body>
<% [Link]("Today is:"+[Link]
nce().getTime()); %>
<%= [Link]("name") %>
</body>
</html>
jsp:include action tag
• The jsp:include action tag is used to include the
content of another resource it may be jsp, html
or servlet.
• The jsp include action tag includes the resource
at request time so it isbetter for dynamic
pages because there might be changes in future.
• The jsp:include tag can be used to include static
as well as dynamic pages.
Syntax of jsp:include action tag without
parameter
<jsp:include page="relativeURL | <%= expression %>" />
Syntax of jsp:include action tag with parameter
<jsp:include page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parameterval
ue | <%=expression%>" />
</jsp:include>
File: [Link]
<h2>this is index page</h2>
<jsp:include page="[Link]" />
<h2>end section of index page</h2>
File: [Link]
<% [Link]("Today is:"+[Link]
nce().getTime()); %>
Web Technology
(KCS-602)
Unit 5
Custom Tag Libraries
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
JSP Taglib directive
The JSP taglib directive is used to define a tag
library that defines many tags. We use the TLD
(Tag Library Descriptor) file to define the tags
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixo
ftaglibrary" %>
<html>
<body>
<%@ taglib uri="[Link]
prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>
JSP Action Tags
• There are many JSP action tags or elements.
• Each JSP action tag is used to perform some
specific tasks.
• The action tags are used to control the flow
between pages and to use Java Bean.
jsp:forward action tag
The jsp:forward action tag is used to forward the
request to another resource it may be jsp, html or
another resource.
Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL | <%= expression %>" />
Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="paramete
rvalue | <%=expression%>" />
</jsp:forward>
Example of jsp:forward action tag
without parameter
[Link]
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="[Link]" />
</body>
</html>
Example of jsp:forward action tag with
parameter
<html>
<body>
<h2>this is index page</h2>
</body>
</html>
[Link]
<html>
<body>
<% [Link]("Today is:"+[Link]
nce().getTime()); %>
<%= [Link]("name") %>
</body>
</html>
jsp:include action tag
• The jsp:include action tag is used to include the
content of another resource it may be jsp, html
or servlet.
• The jsp include action tag includes the resource
at request time so it isbetter for dynamic
pages because there might be changes in future.
• The jsp:include tag can be used to include static
as well as dynamic pages.
Syntax of jsp:include action tag without
parameter
<jsp:include page="relativeURL | <%= expression %>" />
Syntax of jsp:include action tag with parameter
<jsp:include page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parameterval
ue | <%=expression%>" />
</jsp:include>
File: [Link]
<h2>this is index page</h2>
<jsp:include page="[Link]" />
<h2>end section of index page</h2>
File: [Link]
<% [Link]("Today is:"+[Link]
nce().getTime()); %>