0% found this document useful (0 votes)
8 views762 pages

Web Technology Complete Notes Computer Science 3rd Year

The document outlines the course structure and outcomes for a Web Technology course, detailing key concepts such as web development strategies, internet protocols, and client-server computing. It provides a historical overview of the World Wide Web and Java, along with essential programming concepts and data types in Java. Additionally, it includes important questions for assessment related to the course content.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views762 pages

Web Technology Complete Notes Computer Science 3rd Year

The document outlines the course structure and outcomes for a Web Technology course, detailing key concepts such as web development strategies, internet protocols, and client-server computing. It provides a historical overview of the World Wide Web and Java, along with essential programming concepts and data types in Java. Additionally, it includes important questions for assessment related to the course content.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Web Technology

(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

World Wide Web:

The World Wide Web is a system of interlinked


hypertext documents accessed via the
Internet.
Web is a huge collection of pages of information
linked to each other around the globe.
History of WWW
• WWW is created by Sir Tim Berners Lee
in 1989 at CERN in Geneva.
• In 1990, the first text only browsers
were setup and CERN scientist could
access hypertext files and other
information at CERN.
• To transfer HTML document to remote
sites a new protocol was devised called
HTTP (Hyper Text Transfer Protocol).
• In 1993, there are only about 50 websites
world wide.
• A browser that allowed user to take
advantage of the web’s graphical
capabilities was developed at the
National center for Super Computing
application (NCSA).
• NCSA called the browser Mosaic.
Web Development Planning Process
1. Strategy:
· Decide Goals and objectives
· Team building
· Review your Strategy
· Create Final Project proposal
2. Design and Specification:
· Developing concept
· Content planning
· Rough design
· Final design

3. Produced desired Result:


· Build prototype
· Prototype testing
· Original design
· Satisfy the clients need
4. Testing and maintenance:

· Test the code


· Maintain the web server.

5. Register with ISP:

· Register domain name


· Get web space

6. Launch:

· Connect domain name with web server


· Finally host the web accordingly.
Important Questions
• What is a web project? (2017-18 AKTU)
CO1,(K1,k2)
• What is internet? Discuss the various internet
services. (2015-16 AKTU) CO1,(K1,k2)
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Unit -1
Lecture 2
• Protocols Governing Web
• Writing Web Projects
• Connecting to Internet
Protocols Governing Web
Protocol: A protocol is a set of rules that is used to communicate
applications to each other.
OR
A protocol is the interface required for communicating the
different applications.
Classification:

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

• Step 1: Choose an internet service provider (ISP).


This could be the company that provides your
telephone line or it could be one of the many
independent providers.
• Step 2: Having chosen an ISP and signed the
contract, you’ll have to wait a few days while your
line is converted to broadband. During this time, you
should receive a letter with your username and
password and the hardware you’ll need: a small box
called a 'router' and its attachments.
Step 3: Once you’re told that your broadband is
active, you can set up your router. It should
have come with three cables:
• a network cable to connect the router to your computer
• a power cable
• a cable that will go between your router and a micro filter
• Plug one end of the network cable into the appropriately
shaped socket in the router, and the other end in a similarly
appropriately shaped socket in your computer.
• Step 4: When you get the router, you should
also receive a CD. Once you’ve set up the
router, all you need to do is put the CD into
your computer and follow the step-by-step
instructions. Create the broadband
connection.
Important Questions
• Explain client-server architecture with
diagram? (2017-18) CO1,(K1,k2)
• What is internet? Discuss the various internet
services. (2015-16) CO1,(K1,k2)
• What do you mean by web projects .Describe
the various protocol governing the web
project? (2015-16) CO1,(K1,K2,K3)
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Unit -1
Lecture 3
• Introduction to Internet services and
tools
• Introduction to client-server computing.
Internet Services

• World Wide Web


• Telnet
• Electronic Mail
• FTP - File Transfer Protocol
• Chat
• Newsgroups
Client-Server Computing
Client-Server Computing
• Client/server computing is a software
engineering technique often used within
distributed computing that allows two
independent processes to exchange
information, through a dedicated
connection.
• Client/Server computing is NOT
concerned directly with communications
over the network.
The client's responsibility is usually to:
1. Handle the user interface.
2. Translate the user's request into the desired
protocol.
3. Send the request to the server.
4. Wait for the server's response.
5. Translate the response into "human-
readable" results.
6. Present the results to the user.
The server's functions include:
1. Listen for a client's query.
2. Process that query.
3. Return the results back to the client.
Client/Server interaction goes like this:

• The user runs client software to create a query.


• The client connects to the server.
• The client sends the query to the server.
• The server analyzes the query.
• The server computes the results of the query.
• The server sends the results to the client.
• The client presents the results to the user.
• Repeat as necessary.
Important Questions
• Explain client-server architecture with
diagram? (2017-18) CO1,(K1,k2)
• What is internet? Discuss the various internet
services. (2015-16) CO1,(K1,k2)
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Lecture 4
• Core Java: Introduction
• Operator
• Data type
History of Java
• Java is an Object-Oriented
programming language developed by James
Gosling in the early 1990s.
• The team initiated this project to develop a
language for digital devices such as set-top
boxes, television, etc.
• Originally C++ was considered to be used in the
project but the idea was rejected for several
reasons.
• James Gosling and his team called their project
“Greentalk” and its file extension was .gt and
later became to known as “OAK”.
History of various Java versions
VERSION RELEASE DATE
JDK Beta 1995
JDK 1.0 January 1996
JDK 1.1 February 1997
J2SE 1.2 December 1998
J2SE 1.3 May 2000
J2SE 1.4 February 2002
J2SE 5.0 September 2004
JAVA SE 6 December 2006
JAVA SE 7 July 2011
JAVA SE 8 March 2014
JAVA SE 9 September 2017
JAVA SE 10 March 2018
JAVA SE 11 September 2018
JAVA SE 12 March 2019
Features of Java
• Object Oriented : In java everything is an Object.
• Platform independent: Unlike many other
programming languages including C and C++
when Java is compiled, it is not compiled into
platform specific machine, rather into platform
independent byte code.
• Simple :Java is designed to be easy to learn. If
you understand the basic concept of OOP java
would be easy to master.
• Secure : With Java's secure feature it enables to
develop virus-free, tamper-free systems.
• Architectural- neutral :Java compiler generates
an architecture-neutral object file format which
makes the compiled code to be executable on
many processors.
• Portable :being architectural neutral and having
no implementation dependent aspects of the
specification makes Java portable.
• Robust :Java makes an effort to eliminate error
prone situations by emphasizing mainly on
compile time error checking and runtime
checking.
• Multi-threaded : With Java's multi-threaded
feature it is possible to write programs that can
do many tasks simultaneously.
• Interpreted :Java byte code is translated on
the fly to native machine instructions and is
not stored anywhere.
• Distributed :Java is designed for the
distributed environment of the internet.
Difference between JDK, JRE and JVM
JVM
• JVM (Java Virtual Machine) is an abstract
machine. It is a specification that provides
runtime environment in which java byte code
can be executed.
• JVMs are available for many hardware and
software platforms. JVM, JRE and JDK are
platform dependent because configuration of
each OS differs. But, Java is platform
independent.
JRE
• JRE is an acronym for Java Runtime
Environment.
• It is used to provide runtime environment. It is
the implementation of JVM.
• It physically exists.
• It contains set of libraries + other files that
JVM uses at runtime.
JRE
JDK
• JDK is an acronym for Java Development [Link] physically
[Link] contains JRE + development tools.
OOPs (Object Oriented Programming System)
• Object means a real word entity such as pen,
chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program
using classes and objects. It simplifies the
software development and maintenance by
providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object - Objects have states and behaviors.
Example: A dog has states - color, name, breed
as well as behaviours -wagging, barking,
eating. An object is an instance of a class.
Class - A class can be defined as a template/blue
print that describes the behaviors/states that
object of its type support
Inheritance
When one object acquires all the properties and
behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is
used to achieve runtime polymorphism.
Polymorphism
• When one task is performed by different ways i.e. known
as polymorphism. For example. shape or rectangle etc.
• In java, we use method overloading and method overriding
to achieve polymorphism.
Abstraction
• Hiding internal details and showing functionality is known
as abstraction. For example: phone call, we don't know the
internal processing.
• In java, we use abstract class and interface to achieve
abstraction.
Encapsulation
• Binding (or wrapping) code and data together into a single
unit is known as encapsulation. For example: capsule, it is
wrapped with different medicines.
• A java class is the example of encapsulation. Java bean is
the fully encapsulated class because all the data members
are private here.
Interview Questions Asked in different Company
1. What do you understand by Java virtual
machine? [Infosys,TCS,IBM]
2. What is object-oriented programming
system? [TCS]
3. What is the difference between JDK,
JRE, and JVM? [Infosys].
Java Basic Data Types

There are two data types available in Java:


• Primitive Data Types
• Reference/Object Data Types
Primitive Data Types:
• There are eight primitive data types supported
by Java. Primitive data types are predefined by
the language and named by a key word.
byte:
• Minimum value is -128 (-2^7)
• Maximum value is 127 (inclusive)(2^7 -1)
short:
• Minimum value is -32,768 (-2^15)
• Maximum value is 32,767(inclusive) (2^15 -1)
int:
• Minimum value is - 2,147,483,648.(-2^31)
• Maximum value is
2,147,483,647(inclusive).(2^31 -1)
long:
• Minimum value is -
9,223,372,036,854,775,808.(-2^63)
• Maximum value is 9,223,372,036,854,775,807
(inclusive). (2^63 -1)
Interview Questions Asked in different Company

1. Name some OOPS Concepts in Java?


2. What do you mean by platform
independence of Java?[Infosys Interview]
3. What is JVM and is it platform independent?
4. What is the difference between JDK and
JVM? [Infosys Interview]
5. What is the difference between JVM and
JRE?
Operators in java
Operator in java is a symbol that is used to perform
operations. For example: +, -, *, / etc.
There are many types of operators in java which are
given below:
• Unary Operator,
• Arithmetic Operator,
• shift Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Ternary Operator and
• Assignment Operator.
Java Unary Operator Example: ++ and --
class OperatorExample{
public static void main(String args[]){
int x=10;
[Link](x++);//10 (11)
[Link](++x);//12
[Link](x--);//12 (11)
[Link](--x);//10
}}
Output:
10
12
12
10
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
[Link](a++ + ++a);//10+12=22
[Link](b++ + b++);//10+11=21
}}
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
[Link](a+b);//15
[Link](a-b);//5
[Link](a*b);//50
[Link](a/b);//2
[Link](a%b);//0
}}
Java AND Operator Example:
Logical && and Bitwise &
• The logical && operator doesn't check second
condition if first condition is false. It checks
second condition only if first one is true.
• The bitwise & operator always checks both
conditions whether first condition is true or
false.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
[Link](a<b&&a<c);//false && true = false
[Link](a<b&a<c);//false & true = false
}}
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
[Link](a<b&&a++<c);//false && true = false
[Link](a);//10 because second condition is not
checked
[Link](a<b&a++<c);//false & true = false
[Link](a);//11 because second condition is chec
ked
}}
Java OR Operator Example: Logical ||
and Bitwise |

• The logical || operator doesn't check second


condition if first condition is true. It checks
second condition only if first one is false.
• The bitwise | operator always checks both
conditions whether first condition is true or
false.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
[Link](a>b||a<c);//true || true = true
[Link](a>b|a<c);//true | true = true
//|| vs |
[Link](a>b||a++<c);//true || true = true
[Link](a);//10 because second condition is no
t checked
[Link](a>b|a++<c);//true | true = true
[Link](a);//11 because second condition is ch
ecked
}}
Java Ternary Operator
class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
[Link](min);
}}
Output:
2
Java Assignment Operator
class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;//10+3 a=a+3
[Link](a);
a-=4;//13-4
[Link](a);
a*=2;//9*2
[Link](a);
a/=2;//18/2
[Link](a);
}}
Java Shift Operator Example: Left Shift
class OperatorExample{
public static void main(String args[]){
[Link](10<<2);//10*2^2=10*4=40
[Link](10<<3);//10*2^3=10*8=80
[Link](20<<2);//20*2^2=20*4=80
[Link](15<<4);//15*2^4=15*16=240

}}
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");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}
• If you make any class constructor private, you
cannot create the instance of that class from
outside the class.
Note: A class cannot be private or protected
except nested class.
default access modifier
• If you don't use any modifier, it is treated as default by
default. The default modifier is accessible only within
package.
package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
protected access modifier
• The protected access modifier is accessible
within package and outside the package but
through inheritance only.
• The protected access modifier can be applied
on the data member, method and constructor.
It can't be applied on the class.
//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;

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;

Student4(int i,String n){


id = i;
name = n;
}
void display(){[Link](id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
[Link]();
[Link]();
}
}
Constructor Overloading in Java
• Constructor overloading is a technique in Java
in which a class can have any number of
constructors that differ in parameter lists.
• The compiler differentiates these constructors
by taking into account the number of
parameters in the list and their type.
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){[Link](id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}
}
Interview Questions Asked in different Company

• How many constructors do we create in


java in a single class?
• What is constructor chaining?
Java Copy Constructor
• There is no copy constructor in java. But, we
can copy the values of one object to another
like copy constructor in C++.
• There are many ways to copy the values of
one object into another in java. They are:
• By constructor
• By assigning the values of one object into
another
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}

Student6(Student6 s){
id = [Link];
name =[Link];
}
void display(){[Link](id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
[Link]();
[Link]();
}
}
Java static method
If you apply static keyword with any method, it
is known as static method.
• A static method belongs to the class rather
than object of a class.
• A static method can be invoked without the
need for creating an instance of a class.
• static method can access static data member
and can change the value of it.
Final Keyword In Java
The final keyword in java is used to restrict the
user. The java final keyword can be used in
many context. Final can be:
• variable
• method
• class
• The final keyword can be applied with the
variables, a final variable that have no value it
is called blank final variable or uninitialized
final variable.
• It can be initialized in the constructor only.
• The blank final variable can be static also
which will be initialized in the static block only.
If you make any variable as final, you cannot change
the value of final variable(It will be constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
[Link]();
}
}//end of class
Output:Compile Time Error
Java final method
If you make any method as final, you cannot override it.
class Bike{
final void run(){[Link]("running");}
}

class Honda extends Bike{


void run(){[Link]("running safely with 100kmph
");}

public static void main(String args[]){


Honda honda= new Honda();
[Link]();
}
}
Output:Compile Time Error
Java final class
If you make any class as final, you cannot extend it.

final class Bike{}

class Honda1 extends Bike{


void run(){[Link]("running safely with 100k
mph");}

public static void main(String args[]){


Honda1 honda= new Honda();
[Link]();
}
}
Output:Compile Time Error
• A final variable that is not initialized at the
time of declaration is known as blank final
variable.
• If you want to create a variable that is
initialized at the time of creating object and
once initialized may not be changed, it is
useful.
Can we initialize blank final variable?
Yes, but only in constructor. For example:
class Bike10{
final int speedlimit;//blank final variable

Bike10(){
speedlimit=70;
[Link](speedlimit);
}

public static void main(String args[]){


new Bike10();
}
}
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Lecture 7
• Inheritance
Inheritance in Java
• Inheritance in java is a mechanism in which
one object acquires all the properties and
behaviours of parent object.
• The idea behind inheritance in java is that you
can create new classes that are built upon
existing classes.
• Inheritance represents the IS-A relationship,
also known as parent-child relationship.
Why use inheritance in java
• For Method Overriding (so runtime
polymorphism can be achieved).
• For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are
making a new class that derives from an
existing class.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link])
;
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
Types of inheritance in java
Why multiple inheritance is not supported in java?

• To reduce the complexity and simplify the


language, multiple inheritance is not
supported in java.
• Consider a scenario where A, B and C are
three classes. The C class inherits A and B
classes. If A and B classes have same method
and you call it from child class object, there
will be ambiguity to call method of A or B
class.
• Since compile time errors are better than
runtime errors.
class A{
void msg(){[Link]("Hello");}
}
class B{
void msg(){[Link]("Welcome");}
}
class C extends A,B{//suppose if it were

Public Static void main(String args[]){


C obj=new C();
[Link]();//Now which msg() method would be invoked?
}
}

Compile Time Error


Java Method Overloading

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");}

public static void main(String args[]){


Bike obj = new Bike();
[Link]();
}
}
Question Asked in Interview
• How is Inheritance implemented/achieved in
Java?[TCS]
• Which class in Java is superclass of every other
class? [Infosys]
• Can we extend (inherit) final class?
• Ans: No, a class declared with final keyword cannot
be inherited.
• Can a final method be overridden?
• Ans: No, a final method cannot be overridden.
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Lecture 8
• Package and Interface
Java Package
• A java package is a group of similar types of
classes, interfaces and sub-packages.
• Package in java can be categorized in two
form, built-in package and user-defined
package.
• There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.

[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 Honda4 extends Bike{


void run(){[Link]("running safely..");}

public static void main(String args[]){


Honda4 obj = new Honda4();
[Link]();
}
}
abstract class Bank{
abstract double getRateOfInterest();
}

class SBI extends Bank{


double getRateOfInterest(){return 7.5;}
}
class PNB extends Bank{
double getRateOfInterest(){return 7;}
}

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+" %");
}}

• Rate of Interest is: 7.5 %


An abstract class can have data member, abstract method,
method body, constructor and even main() method.
File: [Link]
//example of abstract class that have method body
abstract class Bike{
Bike(){[Link]("bike is created");}
abstract void run();
void changeGear(){[Link]("gear changed");}
}
class Honda extends Bike{
void run(){[Link]("running safely..");}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
[Link]();
[Link]();
} }
• Rule: If you are extending any abstract class
that have abstract method, you must either
provide the implementation of the method
or make this class abstract.
• Rule: If there is any abstract method in a
class, that class must be abstract.
The abstract class can also be used to provide some
implementation of the interface. In such case, the
end user may not be forced to override all the
methods of the interface.
interface A{
void a();
void b();
void c();
void d();
}

abstract class B implements A{


public void c(){[Link]("I am C");}
}
class M extends B{
public void a(){[Link]("I am a");}
public void b(){[Link]("I am b");}
public void d(){[Link]("I am d");}
}

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();
}

class A6 implements printable{


public void print(){[Link]("Hello");}

public static void main(String args[]){


A6 obj = new A6();
[Link]();
}
}
Multiple inheritance in Java by interface
• If a class implements multiple interfaces, or an
interface extends multiple interfaces i.e.
known as multiple inheritance.
interface Printable{
void print();
}

interface Showable{
void show();
}

class A7 implements Printable,Showable{

public void print(){[Link]("Hello");}


public void show(){[Link]("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
[Link]();
[Link]();
}
}
Interface inheritance
A class implements interface but one interface extends another
interface .
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{

public void print(){[Link]("Hello");}


public void show(){[Link]("Welcome");}

public static void main(String args[]){


Testinterface2 obj = new Testinterface2();
[Link]();
[Link]();
}}
Can we define private and protected modifiers for data
members (fields) in interfaces?
• Ans: No, we cannot define private and protected
modifiers for variables in interface because the fields
(data members) declared in an interface are by default
public, static, and final.
Which modifiers are allowed for methods in an
Interface?
• Ans: Only abstract and public modifiers are allowed for
methods in interfaces.
Suppose A is an interface. Can we create an object using
new A()?
• Ans: No, we cannot create an object of interface using
new operator. But we can create a reference of
interface type and interface reference refers to objects
of its implementation classes.
[Link]
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Exception Handling in Java
• The exception handling in java is one of the
powerful mechanism to handle the runtime errors so
that normal flow of the application can be
maintained.
• In java, exception is an event that disrupts the
normal flow of the program. It is an object which is
thrown at runtime.
• Exception Handling is a mechanism to handle
runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
Advantage of Exception Handling
• The core advantage of exception handling is to maintain
the normal flow of the application. Exception normally
disrupts the normal flow of the application that is why
we use exception handling.
• statement 1;
• statement 2;
• statement 3;
• statement 4;
• statement 5;//exception occurs
• statement 6;
• statement 7;
• statement 8;
• statement 9;
• statement 10;
• Suppose there is 10 statements in your
program and there occurs an exception at
statement 5, rest of the code will not be
executed i.e. statement 6 to 10 will not run. If
we perform exception handling, rest of the
statement will be executed. That is why we
use exception handling in java.

[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{}

• Java catch block is used to handle the


Exception. It must be used after the try block
only.
• You can use multiple catch block with a single
try.
[Link]
Internal working of java try-catch block

[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

class Multi3 implements Runnable{


public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
[Link]();
}
}
Sleep method in java
• The sleep() method of Thread class is used to
sleep a thread for the specified amount of
time.
Syntax of sleep() method in java
public static void sleep(long miliseconds)throws
InterruptedException
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{[Link](500);}catch(InterruptedException e)
{[Link](e);}
[Link](i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
[Link]();
[Link]();
}
}
Naming Thread
The Thread class provides methods to change
and get the name of a thread. By default, each
thread has a name i.e. thread-0, thread-1 and
so on.
public String getName(): is used to return the
name of a thread.
public void setName(String name): is used to
change the name of a thread.
class TestMultiNaming1 extends Thread{
public void run(){
[Link]("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
[Link]("Name of t1:"+[Link]());
[Link]("Name of t2:"+[Link]());

[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)

In Java, FileInputStream and FileOutputStream


classes are used to read and write data in file. In
another words, they are used for file handling in
java.
Java FileOutputStream class
Java FileOutputStream is an output stream for
writing data to a file.
If you have to write primitive values then use
FileOutputStream. Instead, for character-oriented
data, prefer [Link] you can write byte-
oriented as well as character-oriented data.
import [Link].*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("[Link]");
String s="Sachin Tendulkar is my favourite player";
byte b[]=[Link]();//converting string into byte array
[Link](b);
[Link]();
[Link]("success...");
}catch(Exception e){[Link](e);}
}
}
Output:success...
Java FileInputStream class
Java FileInputStream class obtains input bytes from a [Link] is used for
reading streams of raw bytes such as image data. For reading
streams of characters, consider using [Link] should be used
to read byte-oriented data for example to read image, audio, video
etc.
import [Link].*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("[Link]");
int i=0;
while((i=[Link]())!=-1){
[Link]((char)i);
}
[Link]();
}catch(Exception e){[Link](e);}
} }
Output:Sachin is my favourite player.
Reading the data of current java file and writing
it into another file
import [Link].*;
class C{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("[Link]");
FileOutputStream fout=new FileOutputStream("[Link]");
int i=0;
while((i=[Link]())!=-1){
[Link]((byte)i);
}
[Link]();
}
}
We can read the data of any file using the FileInputStream
class whether it is java file, image file, video file etc
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Java Applet
Applet is a special type of program that is embedded in
the webpage to generate the dynamic content. It runs
inside the browser and works at client side.
Advantage of Applet
• There are many advantages of applet. They are as
follows:
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many
plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
• Plugin is required at client browser to execute applet.
Hierarchy of Applet
Lifecycle of Java Applet
• Applet is initialized.
• Applet is started.
• Applet is painted.
• Applet is stopped.
• Applet is destroyed.
Lifecycle methods for Applet
For creating any applet [Link] class
must be inherited. It provides 4 life cycle methods
of applet.
• public void init(): is used to initialized the Applet.
It is invoked only once.
• public void start(): is invoked after the init()
method or browser is maximized. It is used to
start the Applet.
• public void stop(): is used to stop the Applet. It is
invoked when Applet is stop or browser is
minimized.
• public void destroy(): is used to destroy the
Applet. It is invoked only once.
public void paint(Graphics g): is used to paint
the Applet. It provides Graphics class object
that can be used for drawing oval, rectangle,
arc etc.
How to run an Applet?
There are two ways to run an applet
• By html file.
• By appletViewer tool (for testing
purpose).
Applet by html file
import [Link];
import [Link];
public class First extends Applet
{
public void paint(Graphics g){
[Link]("welcome",150,150);
}}
Applet by appletviewer tool
import [Link];
import [Link];
public class First extends Applet{

public void paint(Graphics g){


[Link]("welcome to applet",150,150);
}

}
/*
<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

String replace(char old, char new) replaces all occurrences of


specified char value
String trim() returns trimmed string
omitting leading and trailing
spaces
String toUpperCase() returns string in uppercase.

int indexOf(int ch) returns specified char value


index
Immutable String in Java
• In java, string objects are immutable. Immutable simply
means unmodifiable or unchangeable.
• Once string object is created its data or state can't be
changed but a new string object is created.
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
[Link](" Tendulkar");//concat() method appends the stri
ng at the end
[Link](s);//will print Sachin because strings ar
e immutable objects
}
}
1) String compare by equals() method
• The String equals() method compares the original content of the string. It
compares values of string for equality. String class provides two methods:
• public boolean equals(Object another) compares this string
to the specified object.
• public boolean equalsIgnoreCase(String another) compares
this String to another string, ignoring case.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
[Link]([Link](s2));//true
[Link]([Link](s3));//true
[Link]([Link](s4));//false
}}
Output: true true false
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";

[Link]([Link](s2));//false
[Link]([Link](s2));//true
}
}

Output: false true


2) String compare by == operator
The = = operator compares references not values.
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
[Link](s1==s2);//true
(because both refer to same instance)
[Link](s1==s3);
//false(because s3 refers to instance created in non
pool)
}
}
3) String compare by compareTo() method
The String compareTo() method compares values lexicographically and
returns an integer value that describes if first string is less than, equal to
or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2));//0
[Link]([Link](s3));//1(because s1>s3)
[Link]([Link](s1));//-1(because s3 < s1 )
}}
Output:0 1 -1
String Concatenation in Java
In java, string concatenation forms a new string that is the
combination of multiple strings.
There are two ways to concat string in java:
By + (string concatenation) operator
By concat() method
1) String Concatenation by + (string concatenation) operator
Java string concatenation operator (+) is used to add strings.
For Example:
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
[Link](s);//Sachin Tendulkar
}}
Output:Sachin Tendulkar
Java String split
public class SplitExample{
public static void main(String args[]){
String s1="java string split method by javatpoint";
String[] words=[Link](“ ");//splits the string based on whitespace
for(String w:words){
[Link](w);
}
}}
Java String endsWith
public class EndsWithExample{
public static void main(String args[]){
String s1="java by javatpoint";
[Link]([Link]("t"));
[Link]([Link]("point"));
}}
Output:
true true
substring() method
public class SubstringExample{
public static void main(String args[]){
String s1="javatpoint";
[Link]([Link](2,4));//returns va
[Link]([Link](2));//returns vatpoint
}}
Java String join() method example
public class StringJoinExample{
public static void main(String args[]){
String joinString1=[Link]("-
","welcome","to","javatpoint");
[Link](joinString1);
}}
welcome-to-javatpoint
Web Technology
(KCS-602)
Unit 1
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Java AWT Tutorial
• Java AWT (Abstract Windowing Toolkit) is an
API to develop GUI or window-based
application in java.
• Java AWT components are platform-
dependent i.e. components are displayed
according to the view of operating system.
AWT is heavyweight i.e. its components uses
the resources of system.
• The [Link] package provides classes for AWT
api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Java AWT Hierarchy
Container
The Container is a component in AWT that can contain
another components like buttons, textfields, labels etc.
The classes that extends Container class are known as
container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and
menu bars. You must use frame, dialog or another
window for creating a window.
Panel
The Panel is the container that doesn't contain title bar
and menu bars. It can have other components like
button, textfield etc.
Frame
The Frame is the container that contain title bar and can
have menu bars. It can have other components like
button, textfield etc.
Useful Methods of Component class
Java AWT Example
To create simple awt example, you need a
frame.
There are two ways to create a frame in AWT.
• By extending Frame class (inheritance)
• By creating the object of Frame class
(association)
Simple example of AWT by inheritance
import [Link].*;
class First extends Frame{
First(){
Button b=new Button("click me");
[Link](30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible

}
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);

public abstract void mouseMoved(MouseEvent e);


ItemListener Interface
The Java ItemListener is notified whenever you
click on the checkbox. It is notified against
ItemEvent. The ItemListener interface is found
in [Link] package. It has only one
method: itemStateChanged().
• The itemStateChanged() method is invoked
automatically whenever you click or unclick on
the registered checkbox component.
public abstract void itemStateChanged(ItemEvent e);
KeyListener Interface
The Java KeyListener is notified whenever you
change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in
[Link] package. It has three methods.
Methods of KeyListener interface
The signature of 3 methods found in KeyListener
interface are given below:
• public abstract void keyPressed(KeyEvent e);
• public abstract void keyReleased(KeyEvent e);
• public abstract void keyTyped(KeyEvent e);
WindowListener Interface
The Java WindowListener is notified whenever you change the
state of window. It is notified against WindowEvent. The
WindowListener interface is found in [Link]
package. It has three methods.
Methods of WindowListener interface
The signature of 7 methods found in WindowListener
interface are given below:
• public abstract void windowActivated(WindowEvent e);
• public abstract void windowClosed(WindowEvent e);
• public abstract void windowClosing(WindowEvent e);
• public abstract void windowDeactivated(WindowEvent e);
• public abstract void windowDeiconified(WindowEvent e);
• public abstract void windowIconified(WindowEvent e);
• public abstract void windowOpened(WindowEvent e);
LayoutManagers
The LayoutManagers are used to arrange components
in a particular manner. LayoutManager is an interface
that is implemented by all the classes of layout
managers.
There are following classes that represents the
layout managers:
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
BorderLayout
• The BorderLayout is used to arrange the components in five
regions: north, south, east, west and center. Each region (area) may
contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
• public static final int NORTH
• public static final int SOUTH
• public static final int EAST
• public static final int WEST
• public static final int CENTER
Constructors of BorderLayout class:
• BorderLayout(): creates a border layout but with no gaps between
the components.
• JBorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.
GridLayout
The GridLayout is used to arrange the components
in rectangular grid. One component is displayed
in each rectangle.
Constructors of GridLayout class
• GridLayout(): creates a grid layout with one
column per component in a row.
• GridLayout(int rows, int columns): creates a grid
layout with the given rows and columns but no
gaps between the components.
• GridLayout(int rows, int columns, int hgap, int
vgap): creates a grid layout with the given rows
and columns alongwith given horizontal and
vertical gaps.
FlowLayout
The FlowLayout is used to arrange the
components in a line, one after another (in a
flow). It is the default layout of applet or
panel.
Fields of FlowLayout class
• public static final int LEFT
• public static final int RIGHT
• public static final int CENTER
• public static final int LEADING
• public static final int TRAILING
Web Technology
(KCS-602)
Unit 2
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Index
• Introduction to HTML
• HTML List
What is HTML?

• HTML stands for Hyper Text Markup Language


• HTML is a markup language
• A markup language is a set of markup tags
• The tags describe document content
• HTML documents contain HTML tags and plain
text
• HTML documents are also called web pages
HTML Basic Structure
<!DOCTYPE html>
<html>
<head>This is header Part</head>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

</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

The <!DOCTYPE> declaration helps the browser


to display a web page correctly.
There are many different documents on the
web, and a browser can only display an HTML
page 100% correctly if it knows the HTML type
and version used.
HTML Attributes

• HTML elements can have attributes


• Attributes provide additional information
about an element
• Attributes are always specified in the start tag
• Attributes come in name/value pairs like:
name="value"
HTML Headings

• Headings are defined with the <h1> to <h6>


tags.
• <h1> defines the most important heading.
<h6> defines the least important heading.
<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
HTML Lines

The <hr>tag creates a horizontal line in an HTML


page.
The hr element can be used to separate content:
HTML Paragraphs

HTML documents are divided into paragraphs.


Paragraphs are defined with the <p> tag.

<p>This is a paragraph</p>
<p>This is another paragraph</p>
HTML Line Breaks

Use the <br> tag if you want a line break (a


new line) without starting a new paragraph:
HTML <head>
• The <head> element is a container for all the
head elements. Elements inside <head> can
include scripts, instruct the browser where to
find style sheets, provide meta information,
and more.
• The following tags can be added to the head
section: <title>, <style>, <meta>, <link> and
<script>.
Semester Questions
• What is HTML (2016-17)
• What do you understand by hyperlinks in
HTML? Write mark-up for an image Hyperlink.
(2016-17)
HTML Lists
• HTML lists appear in web browsers as bulleted
lines of text.
• There are actually three different types of
HTML lists,
• unordered lists (bullets)
• ordered lists (numbers)
• definition lists (think: dictionaries).
html - unordered lists
• An unordered list (<ul>) signifies to a web
browser that all list items contained inside the
<ul> tag should be rendered with a bullet
preceding the text.
• The default bullet type for most web
browsers is a full disc (black circle), but this
can be adjusted using an HTML attribute
called type.
html - unordered lists

<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

• An ordered list is defined using the <ol> tag,


and list items placed inside of an ordered list
are preceded with numbers instead of bullets.
• The start attribute allows you to further
customize an HTML ordered list by setting a
new starting digit for the ordered list element.
HTML Numbered List Start Attribute

<ol type=“a” start="4" >


<li>Buy Food</li>
<li>Enroll in College</li>
<li>Get a Degree</li>
</ol>
<ol type="a“> <ol type="A">
<ol type="i"> <ol type="I">
html - definition term lists

HTML definition lists (<dl>) are list elements that


have a unique array of tags and elements; the
resulting listings are similar to those you'd see
in a dictionary.
• <dl> - opening clause that defines the start of
the list
• <dt> - list item that defines the definition term
• <dd> - definition of the list item
Design the following nested list.
Web Technology
(KCS-602)
Unit 2
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Index
• HTML Table
HTML Tables
• HTML tables allow web developers to
arrange data into rows and columns.
• Tables are defined with the <table> tag.
Table Cells
• Each table cell is defined by a <td> and a
</td> tag.
• td stands for table data.
• Everything between <td> and </td> are
the content of the table cell.
Table Rows
• Each table row starts with a <tr> and
ends with a </tr> tag.
• tr stands for table row.
Table Headers
• When want your cells to be headers. In
that case use <th> tag instead of the <td>
tag:
Rowspan and Colspan
• rowspan to span multiple rows merging
together table rows and colspan to span
across multiple columns.
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<td>100</td>
<td>200</td>
<td>300</td>
</tr>
<tr>
<td>400</td>
<td>500</td>
<td>600</td>
</tr>
</table>
</body>
</html>
<table border="5px" bgcolor="red">
<tr><th>Col1</th><th>Col2</th><th>Col3</th></tr>
<tr><td rowspan="2" bgcolor="green">Row 1
Cell1</td><td>Row 1 Cell2</td><td>Row 1
Cell3</td></tr>
<tr><td>Row 2 Cell 2</td><td>Row 2 Cell 3</td></tr>
<tr><td colspan="3" align="center">Row 3 Cell
1</td></tr>
</table>
Output
<table border="1" cellpadding="10“ >
<tr>
<td>
<b>Column 1</b>
</td>
<td>
<b>Column 2</b>
</td>
</tr>
<tr> <td>Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
</tr>
<tr>
<td>Row 2 Cell 1</td>
<td>Row 2 Cell 2</td>
</tr>
</table>
Design the Following Table
AKTU Semester Questions
• Explain the anchor and table tag in HTML?
(2017-18)
• Create an HTML page named as “[Link]”
to display your class time table. Provide the
title as time table. Provide the various color
options to the cells. (2018-19)
Web Technology
(KCS-602)
Unit 2
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
HTML Links

• Links are found in nearly all Web pages. Links


allow users to click their way from page to page.
• The HTML <a> tag defines a hyperlink.
• A hyperlink (or link) is a word, group of words, or
image that you can click on to jump to another
document.
• When you move the cursor over a link in a Web
page, the arrow will turn into a little hand.
• The most important attribute of the <a> element
is the href attribute, which indicates the link’s
destination.
HTML Links
By default, links will appear as follows in all
browsers:
• An unvisited link is underlined and blue
• A visited link is underlined and purple
• An active link is underlined and red.
<a href="url">Link text</a>
Example
<!DOCTYPE html>
<html>
<body>
<a href="[Link] target="new">Visit
[Link]!</a>
<p>If you set the target attribute to "_blank", the
link will open in a new browser window/tab.</p>
</body>
</html>
How to use an image as a link.
<!DOCTYPE html>
<html>
<body>
<p>Create a link of an image:
<a href="[Link]">
<img src="[Link]" alt="HTML tutorial"
width="32" height="32"></a></p>
</body>
</html>
HTML Images

• In HTML, images are defined with the <img>


tag.
• The <img> tag is empty, which means that it
contains attributes only, and has no closing
tag.
• To display an image on a page, you need to
use the src attribute. Src stands for "source".
The value of the src attribute is the URL of the
image you want to display
HTML Images
<img src="url" alt="some_text“ width="304"
height="228">
The URL points to the location where the image
is stored.
alt attribute specifies an alternate text for an
image, if the image cannot be displayed.
The height and width attributes are used to
specify the height and width of an image.
Semester Questions
1. What is the use of alternative text in image
mapping? (2018-19)
2. Explain the anchor and table tag in HTML?
(2017-18)
3. What do you understand by hyperlinks in
HTML? Write mark-up for an image
Hyperlink. (2016-17)
Web Technology
(KCS-602)
Unit 2
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
HTML Frames
Frames divide a browser window into several
pieces or panes, each pane containing a
separate HTML document.
One of the key advantages that frames offer is
that you can then load and reload single
panes without having to reload the entire
contents of the browser window.
A collection of frames in the browser window is
known as a frameset.
• The window is divided up into frames in a similar
pattern to the way tables are organized: into rows
and columns.
• The simplest of framesets might just divide the
screen into two rows, while a complex frameset
could use several rows and columns.
• To create a frameset document, first you need
the <frameset> element, which is used instead of
the <body> element.
• The frameset defines the rows and columns your
page is divided into, which in turn specify where
each individual frame will go. Each frame is then
represented by a <frame> element.
Example
<html>
<head>
<title>Frames example</title> </head> <frameset
rows="10%,80%,10%">
<frame src="/html/top_frame.htm" />
<frame src="/html/main_frame.htm" />
<frame src="/html/bottom_frame.htm" />
<noframes>
<body> Your browser does not support
frames. </body>
</noframes>
</frameset>
</html>
<frameset> Element Attributes:
• cols: specifies how many columns are
contained in the frameset and the size of each
column. You can specify the width of each
column in one of four ways:
• Absolute values in pixels. For example to
create three vertical frames, use cols="100,
500,100".
• A percentage of the browser window. For
example to create three vertical frames, use
cols="10%, 80%,10%".
• rows: attribute works just like the cols attribute
and can take the same values, but it is used to
specify the rows in the frameset.
• border: attribute specifies the width of the
border of each frame in pixels.
• frameborder: specifies whether a three-
dimensional border should be displayed between
frames. This attrubute takes value either 1 (yes)
or 0 (no). For example frameborder="0" specifies
no border.
• framespacing: specifies the amount of space
between frames in a frameset. This can take any
integer value.
<frame> Element Attributes:
• src: indicates the file that should be used in the
frame. Its value can be any URL.
• name: attribute allows you to give a name to a
frame. It is used to indicate which frame a
document should be loaded into..
• frameborder: attribute specifies whether or not
the borders of that frame are shown. This can
take values either 1 (yes) or 0 (no).
• marginwidth: allows you to specify the width of
the space between the left and right of the
frame's borders and the frame's content. The
value is given in pixels. For example
marginwidth="10".
• marginheight: allows you to specify the height of
the space between the top and bottom of the
frame's borders and its contents. The value is
given in pixels. For example marginheight="10".
• noresize: By default you can resize any frame by
clicking and dragging on the borders of a frame.
The noresize attribute prevents a user from being
able to resize the frame. For example
noresize="noresize".
• scrolling: controls the appearance of the
scrollbars that appear on the frame. This takes
values either "yes", "no" or "auto". For example
scrolling="no" means it should not have scroll
bars.
The <noframes> Element

• If a user is using any old browser or any browser


which does not support frames then <noframes>
element should be displayed to the user.
• In XHTML you must place a <body> element
inside the <noframes> element because the
<frameset> element is supposed to replace the
<body> element, but if a browser does not
understand the <frameset> element it should
understand what is inside the <body> element
contained in the <noframes> element.
Frame's name and target attributes
• One of the most popular uses of frames is to
place navigation bars in one frame and then
load the pages with the content into a
separate frame.
• <frame> element can carry the name attribute
to give each frame a [Link] name is used
in the links to indicate which frame the new
page should load into.
<a href=[Link]
target="main_page">Google</a>
Inline Frames - The <iframe> Element:
• You can define an inline frame with the <iframe>
tag.
• The <iframe> tag is not used within a <frameset>
tag. Instead, it appears anywhere in your
document.
• The <iframe> tag defines a rectangular region
within the document in which the browser
displays a separate document, including
scrollbars and borders.
• Use the src attribute with <iframe> to specify the
URL of the document that occupies the inline
frame.
Example
<html>
<head></head>
<body>
<iframe src=“URL" width="75" height="200"
align="right">
</iframe>
</body>
</html>
Semester Questions
1. When is it appropriate to use frames? (2018-
19)
Web Technology
(KCS-602)
Unit 2
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
HTML Forms
• HTML Forms are required when you want to
collect some data from the site visitor. For
example registration information: name, email
address, credit card, etc.
• A form will take input from the site visitor and
then will post your back-end application such as
CGI, ASP Script or PHP script etc. Then your back-
end application will do required processing on
that data in whatever way you like.
• Form elements are like text fields, textarea fields,
drop-down menus, radio buttons, checkboxes,
etc. which are used to take information from the
user.
Syntax of using <form>
<form action="back-end script"
method="posting method"> form elements
like input, textarea etc.
</form>
Form attributes
• name: This is the name of the form.
• action: Here you will specify any script
URL which will receive uploaded data.
• method: Here you will specify method to
be used to upload data. It can take
various values but most frequently used
are GET and POST.
There are different types of form controls that
you can use to collect data from a visitor to
your site.
• Text input controls
• Buttons
• Checkboxes and radio buttons
• Select boxes
• File select boxes
• Hidden controls
• Submit and reset button
HTML Forms - Text Input
• Single-line text input controls are created using an <input>
element whose type attribute has a value of text.
list of attributes for <input> tag.
• type: Indicates the type of input control you want to create.
This element is also used to create other form controls such
as radio buttons and checkboxes.
• name: Used to give the name part of the name/value pair
that is sent to the server, representing each form control
and the value the user entered.
• value: Provides an initial value for the text input control that
the user will see when the form loads.
• size: Allows you to specify the width of the text-input
control in terms of characters.
• maxlength: Allows you to specify the maximum number of
characters a user can enter into the text box.
Password input controls
• This is also a form of single-line text input
controls are created using an <input> element
whose type attribute has a value of password.
• <input type=“password“>
Multiple-Line Text Input Control
• If you want to allow a visitor to your site to enter
more than one line of text, you should create a
multiple-line text input control using the
<textarea> element
Attributes for <textarea> tag.
• name: The name of the control. This is used in
the name/value pair that is sent to the server.
• rows: Indicates the number of rows of text area
box.
• cols: Indicates the number of columns of text
area box.
HTML Forms - Creating Button
• There are various ways in HTML to create
clickable buttons. You can create clickable
button using <input> tag.
• When you use the <input> element to create a
button, the type of button you create is
specified using the type attribute.
• There are various ways in HTML to create
clickable buttons. You can create clickable
button using <input> tag.
• When you use the <input> element to create a
button, the type of button you create is
specified using the type attribute
Button Type
• submit: This creates a button that
automatically submits a form.
• reset: This creates a button that automatically
resets form controls to their initial values.
• button: This creates a button that is used to
trigger a client-side script when the user clicks
that button.
HTML Forms - Checkboxes Control
• Checkboxes are used when more than one option
is required to be selected.
Checkbox Attributes
• type: Indicates that you want to create a
checkbox.
• name: Name of the control.
• value: The value that will be used if the checkbox
is selected. More than one checkbox should share
the same name only if you want to allow users to
select several items from the same list.
HTML Forms - Raidobox Control:
• Radio Buttons are used when only one option
is required to be selected.
Radiobox attributes:
• type: Indicates that you want to create a
radiobox.
• name: Name of the control.
• value: Used to indicate the value that will be
sent to the server if this option is selected.
HTML Forms - Select box Control
• Drop Down Box is used when we have many
options available to be selected but only one will
be selected.
Attributes of <select>:
• name: This is the name for the control.
• size: This can be used to present a scrolling list
box.
• multiple: If set to "multiple" then allows a user to
select multiple items from the menu
• value: The value that is sent to the server if this
option is selected
HTML Forms - File Select Boxes
• If you want to allow a user to upload a file to
your web site from his computer, you will
need to use a file upload box, also known as a
file select box. This is also created using the
<input type=“file”> element.
Semester Questions
1. What are forms and how they are created in
HTML? (2017-18)
Web Technology
(KCS-602)
Unit 2
Prepared By
Mr. Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
CSS
• Cascading Style Sheets, fondly referred to as
CSS, is a simple design language intended to
simplify the process of making web pages
presentable.
• CSS handles the look and feel part of a web
page.
• Using CSS, you can control the color of the
text, the style of fonts, the spacing between
paragraphs etc.
Advantages of CSS
• CSS saves time -
• Pages load faster -
• Easy maintenance-
• Superior styles to HTML-
• Multiple Device Compatibility-
• Global web standards-
CSS Versions
• Cascading Style Sheets, level 1 (CSS1) was
came out of W3C as a recommendation in
December 1996.
• CSS2 was became a W3C recommendation in
May 1998 and builds on CSS1.
• The earliest CSS 3 drafts were published in
June 1999.
CSS Syntax – Selectors
A CSS comprises of style rules that are interpreted
by the browser and then applied to the
corresponding elements in your document. A
style rule is made of three parts:
• Selector: A selector is an HTML tag at which style
will be applied. This could be any tag like <h1> or
<table> etc.
• Property: A property is a type of attribute of
HTML tag. Put simply, all the HTML attributes are
converted into CSS properties. They could
be color or border etc.
• Value: Values are assigned to properties. For
example color property can have value
either red or #F1F1F1 etc.
CSS Inclusion - Associating Styles
There are four ways to associate styles with your
HTML document. Most commonly used
methods are inline CSS and External CSS.
Embedded CSS
Inline CSS
External CSS
Imported CSS
Embedded CSS
• You can put your CSS rules into an HTML
document using the <style> element. This tag is
placed inside <head>...</head> tags.
Syntax:
<head>
<style type="text/css”>
Style Rules............
</style>
</head>
Inline CSS
• You can use style attribute of any HTML
element to define style rules. These rules will
be applied to that element only.
• <element style="...style rules....">
<h1 style ="color:#36C;"> This is inline CSS</h1>
External CSS
• The <link> element can be used to include an
external stylesheet file in your HTML
document.
• An external style sheet is a separate text file
with .css extension.
<head><link rel=”stylesheet” type="text/css"
href="...“ ></head>
Imported CSS
• @import is used to import an external
stylesheet in a manner similar to the <link>
element.
<head>
<style>
@import url("[Link]");
</style>
</head>
The Type Selectors
In this type simply apply selector name and set
the attribute value you have to change.
h1 { color: #36CFFF; }
The Descendant Selectors
• Suppose you want to apply a style rule to a
particular element only when it lies inside a
particular element.
ul em { color: #000000; }
The Class Selectors
• You can define style rules based on the class
attribute of the elements.
.black { color: #000000; }
<h1 class="black">Hello Welcome </h1>
The ID Selectors
• All the elements having that id will be
formatted according to the defined rule.
#black { color: #000000; }
<h1 id=“black">Hello Welcome </h1>
The Child Selectors
body > p { color: #000000; }
• This rule will render all the paragraphs in black
if they are direct child of <body> element.
Multiple Style Rules
• You may need to define multiple style rules for
a single element.
h1 {color: #36C;
font-weight: normal;
letter-spacing: .4px;
margin-bottom: 1px;
text-transform: lowercase;
}
Grouping Selectors
• You can apply a style to many selectors if you
like.
h1, h2, h3 {color: #36C;font-weight:
normal;letter-spacing: .4em;margin-bottom:
1em;text-transform: lowercase;}
CSS Rules Overriding
• Any inline style sheet takes highest priority. So
it will override any rule defined in
<style>...</style> tags or rules defined in any
external style sheet file.
• Any rule defined in <style>...</style> tags will
override rules defined in any external style
sheet file.
• Any rule defined in external style sheet file
takes lowest priority.
CSS - Measurement Units
CSS - Colors
Web Technology
(KCS-602)
Unit 2
Prepared By
Mr. Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Colors and backgrounds
➢ color
➢ background-color
➢ background-image
➢ background-repeat
➢ background-attachment
➢ background-position
➢ Background
The color property describes the foreground color of
an element.
h1 {
color: #ff0000;
}
Colors and backgrounds
• The background-color property describes the
background color of elements.
body {
background-color: #FFCC66;
}

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

h1 {font-family: arial, verdana, sans-serif;}


h2 {font-family: "Times New Roman", serif;}
Font style Font weight
• The property font-style defines the chosen font
either in normal, italic or oblique.
h2 {font-family: "Times New Roman", serif; font-
style: italic;}
• The property font-weight describes how bold or
"heavy" a font should be presented. A font can
either be normal or bold.
td {font-family: arial, verdana, sans-serif; font-
weight: bold;}
Font size
The size of a font is set by the property font-size.
h1 {font-size: 30px;}
h2 {font-size: 12pt;}
h3 {font-size: 120%;}
p {font-size: 1em;}
Text
CSS gives you to add layout to text.
The following properties will be described:
➢text-align
➢text-decoration
➢letter-spacing
➢text-transform
Text alignment
• The CSS property text-align corresponds to the
attribute align used in old versions of HTML.
th {
text-align: right;
}

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

•It is important to understand that XML is


not a replacement for HTML. In most web
applications, XML is used to transport data,
while HTML is used to format and display
the data.

6
With XML You Invent Your Own Tags

•The tags used in HTML are predefined.


HTML documents can only use tags
defined in the HTML standard (like <p>,
<h1>, etc.).
•XML allows the author to define his/her
own tags and his/her own document
structure.

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 is not Case sensitive. XML is Case sensitive.

HTML tags are predefined tags. XML tags are user defined tags.

There are limited number of tags


XML tags are extensible.
in HTML.

8
HTML does not preserve White space can be preserved
white spaces. in XML.

XML tags are used for


HTML tags are used for
describing the data not for
displaying the data.
displaying.

In HTML, closing tags are not In XML, closing tags are


necessary. necessary.

HTML is used to display the


XML is used to store data.
data.

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:
&amp; for & (almost always necessary)
&lt; for < (almost always necessary)
&gt; for > (not usually necessary)
&quot; for " (necessary inside double quotes)
&apos; 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

• UTF-8 uses a single byte (8-bits) to represent


commonly used characters and two (or three) bytes
for the rest.
• UTF-16 uses two bytes (16 bits) for most characters,
and three bytes for the rest.
• UTF-8 Web Standard
• UTF-8 is the standard character encoding on the
web.
• UTF-8 is the default character encoding for HTML-5,
CSS, JavaScript, PHP, SQL, and XML.
18
Comments
<!-- This is a comment in both HTML and XML -->
 Comments can be put anywhere in an XML
document
 Comments are useful for:
Explaining the structure of an XML document
Commenting out parts of the XML during
development and testing

19
Web Technology
(KCS-602)
Unit 2
DTD
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Introduction to DTD

•A Document Type Definition (DTD) defines


the legal building blocks of an XML
document. It defines the document structure
with a list of legal elements and attributes.
•A DTD can be declared inline inside an XML
document, or as an external reference.

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 &amp; &lt;
and &gt; entities, respectively.

4
CDATA

• CDATA means character data.


• CDATA is text that will NOT be parsed by a parser.
Tags inside the text will NOT be treated as markup
and entities will not be expanded.

5
Declaring Elements

•In a DTD, XML elements are declared with an


element declaration with the following
syntax:
•<!ELEMENT element-name category>
or
<!ELEMENT element-name (element-
content)>

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

•Elements with only parsed character data are


declared with #PCDATA inside parentheses:
•<!ELEMENT element-name (#PCDATA)>

Example:

<!ELEMENT from (#PCDATA)>

8
Elements with any Contents

•Elements declared with the category


keyword ANY, can contain any combination of
parsable data:
•<!ELEMENT element-name ANY>

Example:

<!ELEMENT note ANY>

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:

<!ELEMENT note (to,from,heading,body)>

10
Declaring Only One Occurrence of an
Element
•<!ELEMENT element-name (child-name)>

Example:

<!ELEMENT note (message)>

11
Declaring Minimum One Occurrence
of an Element
<!ELEMENT element-name (child-name+)>

Example:

<!ELEMENT note (message+)>

12
Declaring Zero or More Occurrences of an
Element
<!ELEMENT element-name (child-name*)>

Example:

<!ELEMENT note (message*)>

13
Declaring either/or Content
Example:

<!ELEMENT note (to,from,header,(message|body))>


The example above declares that the "note" element
must contain a "to" element, a "from" element, a
"header" element, and either a "message" or a
"body" element

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

• Java is purely an object-oriented language,


JavaScript is just a scripting tool
• JavaScript is not compiled and executed; the
client directly interprets it
• Object references must exist at compile-time
in Java (static binding) whereas they are
checked only at runtime in JavaScript
(dynamic binding)
Advantages of JavaScript
➢Less server interaction:
➢Immediate feedback to the visitors:
➢Increased interactivity:
➢Richer interfaces:
➢Form validation in the client’s place
itself, thereby reducing the burden on
the server
➢Javascript timer on the client to check
how much time he/she takes to fill a
form.
JavaScript Syntax
JavaScript in <head>
• JavaScript function is placed in the <head>
section of an HTML page.
JavaScript in <body>
• JavaScript function is placed in the <body>
section of an HTML page.
External JavaScript
• Scripts can also be placed in external [Link]
scripts are practical when the same code is used in
many different web pages.
• JavaScript files have the file extension .js.
JavaScript in <head></head> section
<html>
<head>
<script type="text/javascript">
function sayHello()
{
alert("Hello World")
}</script>
</head>
<body><input type="button" onclick="sayHello()"
value="Say Hello“ > </body> </html>
JavaScript in <body></body> section:

<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

[Link] = Fiat [Link]()

[Link] = 500 [Link]()

[Link] = 850kg [Link]()

[Link] = white [Link]()


<p id="demo"></p>
<script>
// Create an object:
const person = {firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"};
// Display some data from the object:
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years
old.";
</script>
JavaScript Date Object
The JavaScript date object can be used to
get year, month and day.
Method Description

getFullYear() Get year as a four digit number (yyyy)

getMonth() Get month as a number (0-11)

getDate() Get day as a number (1-31)

getDay() Get weekday as a number (0-6)

getHours() Get hour (0-23)

getMinutes() Get minute (0-59)

getSeconds() Get second (0-59)

getMilliseconds() Get millisecond (0-999)


<html>
<body>
Current Date and Time: <span id="txt"></span>
<script>
var today=new Date();
[Link]('txt').innerHTML=today;
</script>
</body>
</html>
JavaScript Math Object
• The JavaScript math object provides several
constants and methods to perform mathematical
operation. Unlike date object, it doesn't have
constructors.
<!DOCTYPE html>
<html>
<body>
Round of 4.3 is: <span id="p6"></span><br>
Round of 4.7 is: <span id="p7"></span>
<script>
[Link]('p6').innerHTML=[Link](4.3);
[Link]('p7').innerHTML=[Link](4.7);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>

Absolute value of -4 is: <span id="p8"></span>


<script>
[Link]('p8').innerHTML=[Link](-4);
</script>

</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

1) public InputStream returns the InputStream


getInputStream() attached with this socket.

2) public OutputStream returns the OutputStream


getOutputStream() attached with this socket.

3) public synchronized void closes this socket


close()
ServerSocket class
Method Description

1) public Socket accept() returns the socket and establish a


connection between server and
client.

2) public synchronized void closes the server socket.


close()
Web Technology
(KCS-602)
Unit 3
URL, URL Connection
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
Java URL
• The Java URL class represents an URL.
• URL is an acronym for Uniform Resource
Locator.
• It points to a resource on the World Wide
Web.
For example:
[Link]
A URL contains many information
• Protocol: In this case, http is the protocol.
• Server name or IP Address: In this case,
[Link] is the server name.
• Port Number: It is an optional attribute. If we
write .If port number is not mentioned in the
URL, it returns -1.
• File Name or directory name: In this case,
[Link] is the file name.
Commonly used methods of Java URL class
Java URLConnection class
• The Java URLConnection class represents a
communication link between the URL and the
application.
• This class can be used to read and write data
to the specified resource referred by the URL.
• The openConnection() method of URL class
returns the object of URLConnection class.
• The getInputStream() method returns all the
data of the specified URL in the stream that
can be read and displayed.
Packages Required for URL
import [Link].*;
import [Link].*;
try{
URL url = new
URL("[Link]
URLConnection urlcon = [Link]();
InputStream stream = [Link]();
int i;
while((i=[Link]())!=-1){
[Link]((char)i);
}
}catch(Exception e){
[Link](e);
}
Web Technology
(KCS-602)
Unit 3

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

1) InetAddress It returns the IP address of the machine to


getAddress() which the datagram is being sent or from
which the datagram was received.

2) byte[] getData() It returns the data buffer.


3) int getLength() It returns the length of the data to be sent or
the length of the data received.

4) int getPort() It returns the port number on the remote


host to which the datagram is being sent or
from which the datagram was received.
Web Technology
(KCS-602)
Unit 4
Enterprise Java Bean
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
EJB
• EJB is an acronym for enterprise java bean. It is a
specification provided by Sun Microsystems to
develop secured, robust and scalable distributed
applications.
• To run EJB application, you need an application
server (EJB Container) such as Jboss, Glassfish,
Weblogic, Websphere etc
• EJB application is deployed on the server, so it is
called server side component also.
• EJB is like COM (Component Object Model)
provided by Microsoft. But, it is different from
Java Bean, RMI and Web Services.
It performs:
• life cycle management,
• security,
• transaction management, and
• object pooling.
When use Enterprise Java Bean?
[Link] needs Remote Access. In
other words, it is distributed.
[Link] needs to be scalable. EJB
applications supports load balancing,
clustering and fail-over.
[Link] needs encapsulated
business logic. EJB application is
separated from presentation and
persistent layer.
Types of Enterprise Java Bean
There are 3 types of enterprise bean in java.
Session Bean
Session bean contains business logic that can be
invoked by local, remote or webservice client.
Message Driven Bean
Like Session Bean, it contains the business logic but
it is invoked by passing message.
Entity Bean
It encapsulates the state that can be persisted in
the database. It is deprecated. Now, it is replaced
with JPA (Java Persistent API).
Session Bean
Session bean encapsulates business logic only, it
can be invoked by local, remote and
webservice client.
It can be used for calculations, database access
etc.
The life cycle of session bean is maintained by
the application server (EJB Container).
Types of Session Bean
There are 3 types of session bean.
1) Stateless Session Bean: It doesn't maintain
state of a client between multiple method
calls.
2) Stateful Session Bean: It maintains state of a
client across multiple requests.
3) Singleton Session Bean: One instance per
application, it is shared between clients and
supports concurrent access.
Stateless Session Bean
• Stateless Session bean is a business object
that represents business logic only. It doesn't
have state (data).
• In other words, conversational state between
multiple method calls is not maintained by the
container in case of stateless session bean.
• It can be accessed by one client at a time. In
case of concurrent access, EJB container
routes each request to different instance.
Stateful Session Bean
• Stateful Session bean is a business object that
represents business logic like stateless session
bean. But, it maintains state (data).
• In other words, conversational state between
multiple method calls is maintained by the
container in stateful session bean.
Message Driven Bean
• A message driven bean (MDB) is a bean that
contains business logic. But, it is invoked by
passing the message. So, it is like JMS Receiver.
• MDB asynchronously receives the message and
processes it.
• A message driven bean receives message from
queue or topic, so you must have the knowledge
of JMS API.
• A message driven bean is like stateless session
bean that encapsulates the business logic and
doesn't maintain state.
Entity Bean
• Entity bean represents the persistent data
stored in the database. It is a server-side
component.
• In EJB 2.x, there was two types of entity
beans: bean managed persistence (BMP) and
container managed persistence (CMP).
Disadvantages of EJB
• Requires application server
• Requires only java client. For other language
client, you need to go for webservice.
• Complex to understand and develop ejb
applications
Web Technology
(KCS-602)
Unit 4
Merging Data from Multiple Tables: Joining,
Manipulating
Prepared By
Abhishek Kesharwani
Assistant Professor,UCER Naini,Allahabad
SQL JOIN
A JOIN clause is used to combine rows from two or more
tables, based on a related column between them.
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values
in both tables
LEFT (OUTER) JOIN: Returns all records from the left
table, and the matched records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right
table, and the matched records from the left table
FULL (OUTER) JOIN: Returns all records when there is a
match in either left or right table
Create Database and Tables
➢ mysql> create database united;
➢ Query OK, 1 row affected (0.13 sec)
➢ mysql> use united;
➢ Database changed

➢ mysql> create table student (sname varchar(40),id int,mob


varchar(10));
➢ Query OK, 0 rows affected (0.19 sec)
➢ mysql> create table student_info (fname varchar(40),id
int,address varchar(80));
➢ Query OK, 0 rows affected (0.16 sec)
Inserting Values in Tables
➢mysql> insert into student_info
values('fname2',2,"Lucknow");
➢Query OK, 1 row affected (0.04 sec)
➢mysql> insert into student_info
values('fname3',3,"Varanasi");
➢Query OK, 1 row affected (0.06 sec)
➢mysql> insert into student_info
values('fname1',1,"Prayagraj");
➢Query OK, 1 row affected (0.27 sec)
➢ mysql> insert into student values('stud1',1,"7765628932");
➢ Query OK, 1 row affected (0.05 sec)
➢ mysql> insert into student values('stud2',2,"5865628932");
➢ Query OK, 1 row affected (0.05 sec)
➢ mysql> insert into student values('stud3',3,"5865628932");
➢ Query OK, 1 row affected (0.05 sec)
➢ mysql> insert into student values('stud4',4,"65628932");
➢ Query OK, 1 row affected (0.06 sec)
➢ mysql> insert into student values('stud5',5,"2365628932");
➢ Query OK, 1 row affected (0.05 sec)
Display Data from Table
• mysql> select * from student;
• +-------+------+------------+
• | sname | id | mob |
• +-------+------+------------+
• | stud1 | 1 | 7765628932 |
• | stud2 | 2 | 5865628932 |
• | stud3 | 3 | 5865628932 |
• | stud4 | 4 | 65628932 |
• | stud5 | 5 | 2365628932 |
• +-------+------+------------+
• mysql> select * from student_info;
• +--------+------+------------+
• | fname | id | address |
• +--------+------+------------+
• | fname2 | 2 | Lucknow |
• | fname3 | 3 | Varanasi |
• | fname1 | 1 | Prayagraj |
• | fname5 | 9 | 8744628932 |
• +--------+------+------------+
join
• mysql> select
[Link],student_info.fname,student_info.a
ddress from student inner join student_info on
[Link]=student_info.id;
• +-------+--------+-----------+
• | sname | fname | address |
• +-------+--------+-----------+
• | stud1 | fname1 | Prayagraj |
• | stud2 | fname2 | Lucknow |
• | stud3 | fname3 | Varanasi |
• +-------+--------+-----------+
• mysql> select
[Link],student_info.fname,student_info.address from
student left join student_info on [Link]=student_info.id;
• +-------+--------+-----------+
• | sname | fname | address |
• +-------+--------+-----------+
• | stud1 | fname1 | Prayagraj |
• | stud2 | fname2 | Lucknow |
• | stud3 | fname3 | Varanasi |
• | stud4 | NULL | NULL |
• | stud5 | NULL | NULL |
• +-------+--------+-----------+
• 5 rows in set (0.03 sec)
• mysql> select
[Link],student_info.fname,student_inf
[Link] from student right join student_info
on [Link]=student_info.id;
• +-------+--------+------------+
• | sname | fname | address |
• +-------+--------+------------+
• | stud2 | fname2 | Lucknow |
• | stud3 | fname3 | Varanasi |
• | stud1 | fname1 | Prayagraj |
• | NULL | fname5 | 8744628932 |
• +-------+--------+------------+
• mysql> select * from student full join student_info;
• +-------+------+------------+--------+------+------------+
• | sname | id | mob | fname | id | address |
• +-------+------+------------+--------+------+------------+
• | stud1 | 1 | 7765628932 | fname2 | 2 | Lucknow |
• | stud1 | 1 | 7765628932 | fname3 | 3 | Varanasi |
• | stud1 | 1 | 7765628932 | fname1 | 1 | Prayagraj |
• | stud1 | 1 | 7765628932 | fname5 | 9 | 8744628932 |
• | stud2 | 2 | 5865628932 | fname2 | 2 | Lucknow |
• | stud2 | 2 | 5865628932 | fname3 | 3 | Varanasi |
• | stud2 | 2 | 5865628932 | fname1 | 1 | Prayagraj |
• | stud2 | 2 | 5865628932 | fname5 | 9 | 8744628932 |
• | stud3 | 3 | 5865628932 | fname2 | 2 | Lucknow |
• | stud3 | 3 | 5865628932 | fname3 | 3 | Varanasi |
• | stud3 | 3 | 5865628932 | fname1 | 1 | Prayagraj |
• | stud3 | 3 | 5865628932 | fname5 | 9 | 8744628932 |
• | stud4 | 4 | 65628932 | fname2 | 2 | Lucknow |
• | stud4 | 4 | 65628932 | fname3 | 3 | Varanasi |
• | stud4 | 4 | 65628932 | fname1 | 1 | Prayagraj |
• | stud4 | 4 | 65628932 | fname5 | 9 | 8744628932 |
• | stud5 | 5 | 2365628932 | fname2 | 2 | Lucknow |
• | stud5 | 5 | 2365628932 | fname3 | 3 | Varanasi |
• | stud5 | 5 | 2365628932 | fname1 | 1 | Prayagraj |
• | stud5 | 5 | 2365628932 | fname5 | 9 | 8744628932 |
• +-------+------+------------+--------+------+------------+
Web Technology
(KCS-602)
Unit 4
Transaction Processing, Stored Procedures

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;

SET autocommit = OFF


COMMIT example
In order to use a transaction, you first have to
break the SQL statements into logical portions
and determine when data should be committed
or rolled back.
• INSERT INTO Orders(order_id, prod_name,
order_num, order_date) VALUES (8,
'Speaker', 6065, '2020-02-18');
• COMMIT;
ROLLBACK example
➢START TRANSACTION;

➢DELETE FROM orders;

➢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

• A servlet life cycle can be defined as the entire


process from its creation till the destruction. The
following are the paths followed by a servlet
• The servlet is initialized by calling the init ()
method.
• The servlet calls service() method to process a
client's request.
• The servlet is terminated by calling the destroy()
method.
• Finally, servlet is garbage collected by the garbage
collector of the JVM.
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
Handling HTTP Requests

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>

<jsp:forward page="[Link]" >


<jsp:param name="name" value="[Link]" />
</jsp:forward>

</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>

<jsp:forward page="[Link]" >


<jsp:param name="name" value="[Link]" />
</jsp:forward>

</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()); %>

You might also like