Nothing Special   »   [go: up one dir, main page]

Computer Concept and Web Technology: Cse 3Rd Semester Jkie Bilaspur

Download as pdf or txt
Download as pdf or txt
You are on page 1of 98

2013

COMPUTER CONCEPT AND


WEB TECHNOLOGY
CSE 3RD SEMESTER JKIE BILASPUR
BY ATUL SINGH

ATUL
ATUL SINGH-JKIE BILASPUR
9/4/2013
1

devices such as the keyboard or from other computers over digital communication
Unit-1 lines. The information received is either stored in the memory for later reference or
Computer Organization immediately used by the Arithmetic and Logic circuitry to perform the desired
operation. Finally the result is sent back to the outside through the output unit. The
Computer is a device that operates upon information or data. It is an electronic device keyboard is wired so that whenever a key is pressed, the corresponding letter or digit is
which input data, stores the data, does arithmetic and logic operation and outputs the automatically translated into its corresponding code and sent directly to either the
information in desired format. memory or the processor. Other kinds of input devices: Joy stick, track ball, mouse
Even though the size, shape, performance, reliability and cost of computers have been (pointing devices), scanner etc.
changing over the years, the basic logical structure proposed by Von Neumann has not
change. The internal architecture of computers differs from one system model to MEMORY UNIT
another. The memory unit stores program and data. There are two classes of memory devices: -
A block diagram of the basic computer organization specifying different functional  Primary memory
units is shown below. Here the solid lines indicate the flow of instruction and data and  Secondary memory
the dotted lines represent the control exercised by the control unit
Primary memory (Main memory)
Primary storage (or main memory or internal memory), often referred to simply
as memory, is the only one directly accessible to the CPU. The CPU continuously
reads instructions stored there and executes them as required. Any data actively
operated on is also stored there in uniform manner
 Fast memory
 Temporary memory
E g. Random Access Memory (RAM)
Secondary storage
Secondary storage (also known as external memory or auxiliary storage), differs from
primary storage in that it is not directly accessible by the CPU. The computer usually
uses its input/output channels to access secondary storage and transfers the desired
data using intermediate area in primary storage. Secondary storage does not lose the
data when the device is powered down—it is non-volatile
 They are used when large amount of data have to be stored permanent.
 E.g. Hard Disk, Compact Disk, Floppy Disk, Magnetic Tapes etc.

PROCESSOR UNIT

 The heart of the computer system is the Processor unit.


FUNCTIONAL UNITS OF A COMPUTER  It consists of Arithmetic and Logic Unit and Control Unit.

INPUT UNIT Arithmetic and Logic Unit (ALU)


Input unit accepts coded information from human operators through electromechanical  Most computer operations (Arithmetical and logical) are executed in ALU

1 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
2

of the processor.
 For example: Suppose two numbers (operands) located in the main
memory are to be added. These operands are brought into arithmetic unit – Steps:-
actual addition is carried. The result is then stored in the memory or 1. Instruction is fetched from the main memory into the processor Memory
retained in the processor itself for immediate use.
 Note that all operands may not reside in the main memory. Processor contains 2. Operand at LOCA is fetched access
a number of high speed storage elements called Registers, which may be used operation
for temporary storage of frequently used operands. Each register can store one
word of data. 3. Add the contents to the contents of R0 ALU operation
 Access times to registers are 5 to 10 times faster than access time to memory. 4. Finally store the result in R0

Control Unit Note: Data transfer between the main memory and the processor are started by sending
the address of the memory location to be accessed to the memory unit and issuing the
 The operations of all the units are coordinated by the control unit (act as the
appropriate control signal by the control unit.
nerve centre that sends control signal to other units)
 Timing signal that governs the I/O transfers are generated by the Control Unit.
 Synchronization signals are also generated by the Control Unit GENERATION OF COMPUTERS
 By selecting, interpreting and executing the program instructions the program Generations of computers has been divided into five according to the development of
instructions the control unit is able to maintain order and direct the operation technologies used to fabricate the processors, memories and I/O units.
of the entire system. I Generation : 1945 – 55
II Generation: 1955 – 65
OUTPUT UNIT
III Generation: 1965 – 75
 Counter part of input unit
IV Generation: 1975 – 89
 Output devices accept binary data from the computer - decodes it into original V Generation: 1989 to present
form and supplies this result to the outside world.
E.g. Printer, Video terminals (provides both input & output functions), graphic The first electronic computer was designed and built at the University of Pennsylvania
displays etc based on vacuum tube technology. Vacuum tubes were used to perform logic
operations and to store data.
Basic Operational Concepts:-
 Activity in a computer is governed by instructions First Generation
 To perform a given task, a set of instructions called program must be there in the ENIAC - Electronic Numerical Integrator and Calculator
main memory EDSAC – Electronic Delay Storage Automatic Calculator
 Individual instructions are brought from the memory into the processor which EDVAC – Electronic Discrete Variable Automatic Computer
executes the specific operation.
UNIVAC – Universal Automatic Computer IBM 701)
 Data to be used as operands are also stored in the memory.
 Vacuum tubes were used – basic arithmetic operations took few milliseconds
 Bulky
E.g. Add LOCA, R
 Consume more power with limited performance
 High cost
This instruction adds the operand at the memory location LOCA to the operand in the
Processor R0 and places the sum into the register R0. Here the original contents of  Uses assembly language – to prepare programs. These were translated into
LOCA are preserved whereas those of R0 are overwritten. machine level language for execution.

2 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
3

 Fixed point arithmetic was used  Smaller & better performance


 100 to 1000 fold increase in speed relative to the earlier mechanical and relay  Comparatively lesser cost
based electromechanical technology  Faster processors
 Punched cards and paper tape were invented to feed programs and data and to  In the beginning magnetic core memories were used. Later they were replaced
get results. by semiconductor memories (RAM & ROM)
 Magnetic tape / magnetic drum were used as secondary memory  Introduced microprogramming
 Mainly used for scientific computations.  Microprogramming, parallel processing (pipelining, multiprocessor system
etc), multiprogramming, multi-user system (time shared system) etc were
introduced.
Second Generation (Manufacturers – IBM 7030, Digital Data Corporation’s  Operating system software were introduced (efficient sharing of a computer
PDP 1/5/8 system by several user programs)
Honeywell 400)  Cache and virtual memories were introduced (Cache memory makes the main
 Transistors were used in place of vacuum tubes. (invented at AT&T Bell lab memory appear faster than it really is. Virtual memory makes it appear larger)
in 1947)  High level languages were standardized by ANSI e.g. ANSI FORTRAN,
 Small in size ANSI COBOL etc
 Lesser power consumption and better performance  Database management, multi-user application, online systems like closed loop
 Lower cost process control, airline reservation, interactive query systems, automatic
 Magnetic ferrite core memories were used as main memory which is a industrial control etc emerged during this period.
random-access Non-volatile memory
 Magnetic tapes and magnetic disks were used as secondary memory Fourth Generation (Intel’s 8088,80286,80386,80486 .., Motorola’s 68000, 68030,
68040, Apple II, CRAY I/2/X/MP etc)
 Hardware for floating point arithmetic operations was developed.
 Microprocessors were introduced as CPU– Complete processors and large
 Index registers were introduced which increased flexibility of programming.
section of main memory could be implemented in a single chip
 High level languages such as FORTRAN, COBOL etc were used - Compilers
 Tens of thousands of transistors can be placed in a single chip (VLSI design
were developed to translate the high-level program into corresponding
implemented)
assembly language program which was then translated into machine language.
 CRT screen, laser & ink jet printers, scanners etc were developed.
 Separate input-output processors were developed that could operate in parallel
with CPU.  Semiconductor memory chips were used as the main memory.
 Punched cards continued during this period also.  Secondary memory was composed of hard disks – Floppy disks & magnetic
tapes were used for backup memory
 1000 fold increase in speed.
 LAN and WANS were developed (where desktop work stations
 Increasingly used in business, industry and commercial organizations for
interconnected)
preparation of payroll, inventory control, marketing, production planning,
research, scientific & engineering analysis and design etc.  Introduced C language and Unix OS
 Introduced Graphical User Interface
Third Generation (System 360 Mainframe from IBM, PDP-8 Mini Computer from  Less power consumption
Digital Equipment Corporation)  High performance, lower cost and very compact
 ICs were used  Much increase in the speed of operation
 Small Scale Integration and Medium Scale Integration technology were
implemented in CPU, I/O processors etc. Fifth Generation (IBM notebooks, Pentium PCs-Pentium 1/2/3/4/Dual core/Quad
core.. SUN Work stations, Origin 2000, PARAM 10000, IBM SP/2)
3 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
4

 Generation number beyond IV, have been used occasionally to describe some
An analog computer (spelt analogue in British English) is a form of computer that
current computer system that have a dominant organizational or application
driven feature. uses continuous physical phenomena such as electrical, mechanical, or hydraulic
 Computers based on artificial intelligence are available quantities to model the problem being solved
 Computers use extensive parallel processing, multiple pipelines, multiple
processors etc
Digital Computer
 Massive parallel machines and extensively distributed system connected by
communication networks fall in this category. A computer that performs calculations and logical operations with quantities
 Introduced ULSI (Ultra Large Scale Integration) technology – Intel’s
Pentium 4 microprocessor contains 55 million transistors millions of represented as digits, usually in the binary number system
components on a single IC chip.
 Superscalar processors, Vector processors, SIMD processors, 32 bit micro Hybrid Computer (Analog + Digital)
controllers and embedded processors, Digital Signal Processors (DSP) etc
have been developed. A combination of computers those are capable of inputting and outputting in both
 Memory chips up to 1 GB, hard disk drives up to 180 GB and optical disks digital and analog signals. A hybrid computer system setup offers a cost effective
up to 27 GB are available (still the capacity is increasing)
method of performing complex simulations.
 Object oriented language like JAVA suitable for internet programming has
been developed.
 Portable note book computers introduced On the basis of Size
 Storage technology advanced – large main memory and disk storage available
Super Computer
 Introduced World Wide Web. (And other existing applications like e-mail, e
Commerce, Virtual libraries/Classrooms, multimedia applications etc.)
The fastest and most powerful type of computer Supercomputers are very expensive
 New operating systems developed – Windows 95/98/XP/…, LINUX, etc.
 Got hot pluggable features – which enable a failed component to be replaced and are employed for specialized applications that require immense amounts of
with a new one without the need to shut down the system, allowing the uptime mathematical calculations. For example, weather forecasting requires a supercomputer.
of the system to be very high.
 The recent development in the application of internet is the Grid technology Other uses of supercomputers include animated graphics, fluid dynamic calculations,
which is still in its upcoming stage. nuclear energy research, and petroleum exploration.
 Quantum mechanism and nanotechnology will radically change the phase of
computers. Mainframe Computer

Classifications of computer A very large and expensive computer capable of supporting hundred, or even
thousands, of users simultaneously. In the hierarchy that starts with a simple
According to functionality, computers are classified as:
microprocessor (in watches, for example) at the bottom and moves to supercomputers
Analog Computer at the top, mainframes are just below supercomputers. In some ways, mainframes are

4 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
5

more powerful than supercomputers because they support more simultaneous connected to a local area network and run multi-user operating systems. The
programs. But supercomputers can execute a single program faster than a mainframe. term workstation has also been used to refer to a mainframe computer terminal or a PC
connected to a network.
The chief difference between a supercomputer and a mainframe is that a
supercomputer channels all its power into executing a few programs as fast as Algorithm
possible, whereas a mainframe uses its power to execute many programs concurrently. Algorithm is a method of representing the step-by-step logical procedure for solving a
Mini Computer problem. An algorithm is a recipe for finding the right-answer to a problem or to a
difficult problem by breaking down the problem into simple cases.
A mid-sized computer. In size and power, minicomputers lie According to D.E. Knuth, a pioneer in the computer science discipline, an algorithm
must possess the following properties
between workstations and mainframes. In the past decade, the distinction between (i) Finiteness: An algorithm must terminate in a finite number of steps
large minicomputers and small mainframes has blurred, however, as has the distinction (ii) Definiteness: Each step of the algorithm must be precisely and unambiguously
stated
between small minicomputers and workstations. But in general, a minicomputer is a (iii) Effectiveness: Each step must be effective, in the sense that it should be primitive
multiprocessing system capable of supporting from 4 to about 200 users (easily convertible into program statement) can be performed exactly in a finite
amount of time.
simultaneously. (iv) Generality: The algorithm must be complete in itself so that it can be used to solve
all problems of a specific type for any input data.
Micro Computer or Personal Computer (v) Input/Output: Each algorithm must take zero, one or more quantities as input data
produce one or more output values.
An algorithm can be written in English like sentences or in any standard representation
 Desktop Computer: a personal or micro-mini computer sufficient to fit on
Sometimes, algorithm written in English like languages are called Pseudo Code
a desk. Example:
1. Suppose we want to find the average of three numbers, the algorithm is as follows
 Laptop Computer: a portable computer complete with an integrated screen
Step 1 Read the numbers a, b, c
and keyboard. It is generally smaller in size than a desktop computer and larger Step 2 Compute the sum of a, b and c
Step 3 Divide the sum by 3
than a notebook computer.
Step 4 Store the result in variable d
 Palmtop Computer/Digital Diary /Notebook /PDAs: a hand-sized Step 5 Print the value of d
computer. Palmtops have no keyboard but the screen serves both as an input and Characteristics of Computers
output device. 1. Speed
A computer is a very fast device. It can carry out instructions at a very high speed
Workstations obediently, It can perform in a few seconds the amount of work that a human being can
do in an entire year. The speed of computer is calculated in MHz that is one million
A workstation is a high-end microcomputer designed for technical or scientific instructions per second.
2. Accuracy
applications. Intended primarily to be used by one person at a time, they are commonly

5 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
6

Accuracy of a computer is consistently high and the degree of accuracy of a particular


computer depends on the instructions and the type of processor.
3. Versatility
Multi-processing features of computer makes it quiet versatile in nature. It can perform Input Devices
different types of tasks with same ease
4. Reliability Keyboard
Computers provide very high speed accompanied by an equality high level for The computer keyboard is used to enter text information into the computer, as when
reliability. Thus computers never make mistakes of their own accord. you type the contents of a report. The keyboard can also be used to type commands
5. Power of Remembering directing the computer to perform certain actions.
A computer can store and recall any amount of information because of its secondary
storage capability.
6. No I.Q
A computer is a magical device. It can only perform tasks that a human being can. The
difference is that it performs these tasks with unthinkable speed and accuracy.
7. Common Data Used
One item can be involved in several different procedures or accessed, update and Mouse
inspected by a number of different users. This can hinder the work of those who need The mouse pointing device sits on your work surface and is moved with your hand.
access to data.
8. Diligence
The computer is a machine, does not suffer from the human traits of tiredness. It can
perform long and complex calculations with same speed and accuracy from the start
till the end.
9. Storage Touch pad
The computers have a lot of a storage device which can store a large amount of data Most laptop computers today have a touch pad pointing device. You move the on-
second storage devices like CD, pen drive can store a large amount of data screen cursor by sliding your finger along the surface of the touch pad. The buttons are
permanently. located below the pad, but most touch pads allow you to perform “mouse clicks” by
tapping on the pad itself.
Input and Output Devices
Before a computer can process your data, you need some method to input the data
into the machine. The device you use will depend on what form this data takes (be it
text, sound, artwork, etc.).
Similarly, after the computer has processed your data, you often need to produce
output of the results. This output could be a display on the computer screen, Trackball
The trackball is sort of like an upside-down mouse, with the ball located on top. You
hardcopy on printed pages, or even the audio playback of music you composed on use your fingers to roll the trackball, and internal rollers (similar to what’s inside a
the computer. mouse) sense the motion which is transmitted to the computer.
The terms “input” and “output” are used both as verbs to describe the process of
entering or displaying the data.

6 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
7

Microphone
A microphone can be attached to a computer to record sound (usually through a sound
card input or circuitry built into the motherboard). The sound is digitized—turned into
numbers that represent the original analog sound waves—and stored in the computer to
later processing and playback.
Joysticks Output Devices
Joysticks and other game controllers can also be connected to a computer as pointing
devices. They are generally used for playing games, and not for controlling the on- CRT Monitor
screen cursor in productivity software. The traditional output device of a personal computer has been the CRT (Cathode Ray
Tube) monitor. Just like a television set (an older one, anyway) the CRT monitor
Touch screen contains a large cathode ray tube that uses an electron beam of varying strength to
“paint” a picture onto the color phosphorescent dots on the inside of the screen.
Some computers, especially small hand-held PDAs, have touch sensitive display
screens. The user can make choices and press button images on the screen. You often
use a stylus, which you hold like a pen, to “write” on the surface of a small touch
screen.
Graphics tablet
A graphics tablet consists of an electronic writing area and a special “pen” that works
with it. Graphics tablets allow artists to create graphical images with motions and
actions similar to using more traditional drawing tools. The pen of the graphics tablet Flat Panel Monitor
is pressure sensitive, so pressing harder or softer can result in brush strokes of different A flat panel display usually uses an LCD (Liquid Crystal Display) screen to display
width (in an appropriate graphics program). output from the computer. The LCD consists of several thin layers that polarize the
light passing through them. The polarization of one layer, containing long thin
molecules called liquid crystals, can be controlled electronically at each pixel, blocking
varying amounts of the light to make a pixel lighter or darker.

Scanners
A scanner is a device that images a printed page or graphic by digitizing it, producing
an image made of tiny pixels of different brightness and color values which are Ink Jet Printer
represented numerically and sent to the computer. Scanners scan graphics, but they can For hardcopy (printed) output, you need some kind of printer attached to your
also scan pages of text which are then run through OCR (Optical Character computer (or available over a network). The most common type of printer for home
Recognition) software that identifies the individual letter shapes and creates a text file systems is the color ink jet printer. These printers form the image on the page by
of the page's contents. spraying tiny droplets of ink from the print head. The printer needs several color of ink
7 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
8

(cyan, yellow, magenta, and black) to make color images. Some photo-quality ink jet
printers have more color of ink. n General Purpose Registers (R0 to Rn-1) – Facilitates communication with the main
memory. Access to data in these registers is much faster than to data stored in memory
locations because the registers are inside the processor. Most modern computers have 8
to 32 general purpose registers.

Memory Address Register (MAR) – holds the address of the location to or from
which data are to be transferred

Laser Printer Memory Data Register (MDR) – contains the data to be written into or read out of
A laser printer produces good quality images by the same technology that the address location.
photocopiers use. A drum coated with photosensitive material is charged, and then an
image is written onto it by a laser (or LEDs) which makes those areas lose the charge.
The drum then rolls through toner (tiny plastic particles of pigment) that is attracted to
the charged areas of the drum. The toner is then deposited onto the paper, and then
fused into the paper with heat.
Other printer
Dot matrix printers use small electromagnetically activated pins in the print head, and
an inked ribbon, to produce images by impact. These printers are slow and noisy, and
are not commonly used for personal computers anymore (but they can print multi-layer
forms, which neither ink jet nor laser printers can).
Sound Output
Computers also produce sound output, ranging from simple beeps alerting the user, to
impressive game sound effects, to concert quality music. The circuitry to produce
sound may be included on the motherboard, but high quality audio output from a PC
usually requires a sound card in one of the expansion slots, connected to a set of good
quality external speakers or headphones.

INTERNAL ORGANIZATION (description) OF PROCESSOR Steps involved during operation:-


Processor contains a number of registers used for temporary storage of data other than 1. Program is stored in the main memory.
ALU and Control circuitry 2. PC is set to point to the first instruction of the program.
Instruction Register (IR) – holds the instruction that is currently being executed – its 3. Contents of the PC are transferred to the MAR and a Read Control signal sent
output is available to the control circuits which generate the timing signals that control to the memory.
the various processing elements involved in executing the instruction. 4. After the access time, the addressed word (in this case the first instruction) is
read out of the memory and is loaded into the MDR.
Program Counter (PC) – It contains the address of the instruction currently being 5. Contents of the MDR are transferred to the IR. Now the instruction is ready to
executed. During the execution of an instruction, the contents of the program counter be decoded and executed.
are updated to hold the address of the next instruction to be executed. i.e. PC points to 6. If the instruction involves an operation to be performed by the ALU, the
the next instruction that is to be fetched from the memory. required operands are to be fetched from the memory (or CPU registers). This
8 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
9

is done by sending its address to the MAR and initiating a Read cycle.
High level Languages
7. Operands are read from the memory into the MDR and are transferred from
MDR to the ALU.
8. ALU will perform the desired operation.
9. If the result is to be stored in the memory, then it is sent to the MDR.
10. The address of the location where the result is to be stored is sent to the MAR Interpreters Compilers
and a Write cycle is initiated.
Assembly Language
11. At some point during the execution of the current instruction, the contents of
the PC are incremented so that the PC now points to the next instruction to be
executed. Assembler
12. As soon as the execution of the current instruction is completed, a new
instruction fetch may be started.
Machine Code

Programming Language Machine Language


The process of designing, writing, testing, debugging, documenting and Machine language is a system of instructions and data which is directly understandable
maintaining a program is known as programming. A language is a medium, which by a computer's central processing unit. In this instructions are patterns of bits.
is used for understanding each other ideas. Communicating medium should be such Every CPU model has its own machine code, although there is considerable overlap
that one has to understand, what we are expressing i.e., medium of communication between some. Depending on the processing architecture, a given instruction may
should be common between the two. Similarly we need computer languages for specify:
giving instructions to the computer. A language used to write a program that a  Particular registers for arithmetic, addressing, or control functions
computer can execute. Almost, 200 different programming languages exist  Particular memory locations or offsets
Programming languages provide various ways of specifying programs for computers to  Particular addressing modes used to interpret the operands
run. They are generally either translated into machine language before being run by a Some operations which are available in most instruction sets include:
compiler or an assembler or translated directly at run time by an interpreter. 1. Moving
Programming languages are classified as follows: a) set a register to a fixed constant value
 Machine Language. b) move data from a memory location to a register, or vice
 Assembly Language. versa. This is done to obtain the data to perform a computation on
 High Level Language. it later, or to store the result of a computation.
c) read and write data from hardware devices
2. Computing
a) Add, subtract, multiply, or divide the values of two registers, placing
the result in a register.
b) compare two values in registers
The programs written in this language are non-portable. These are the language which
are understood by the machine directly as it consist of a binary digit. Instruction
written in machine language has two parts, first is opcode which tells the
computer what operation has to be performed. The second part of the instruction is
operands that specify the address of the data.

9 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
10

Advantages Of machine Language has been developed. It is a problem oriented language. A high-level programming
1. The machine easily understands these languages. language is a programming language that, in comparison to low-level programming
2. Processing is faster. languages, may be more abstract, easier to use, or more portable across platforms.
Limitations of Machine Language High-level languages deal with variables, arrays and complex arithmetic or
1. It is machine dependent; it is different from one computer to another. Boolean expressions. In addition, they have no opcode that can directly compile the
2. All the instructions are to be given into binary digits, therefore it is very difficult to language into machine code, unlike low-level languages like Assembly language.
program. In general, high-level languages make complex programming simpler, while low-
3. It is difficult to rectify a program written in machine language. level languages tend to produce more efficient code. In a high-level language,
4. It is very time consuming and tedious task to write a program in machine complex elements can be broken up into simpler.
language. The advantage of high level language program is that they are portable from computer
to computer. But the computer can only understand the machine language, so we have
B. Assembly Language to translate the instruction from high level language to machine language. For that, we
Writing the programs in machine language is a very complicated and boring job. To need language translator which is interpreter and compiler. Language translator is a
solve this problem, assembly languages is developed which makes use of program which is used to translate a language into a low-level programming language
alphanumeric symbols for writing the set of instruction instead of 0 and 1 for which native code compilers are already widely available.
A program written in assembly language consists of a series of instructions in symbolic
code i.e. mnemonics that correspond to a stream of executable instructions, Compiler: The name "compiler" is primarily used for programs that translate
when translated by an assembler, that can be loaded into memory and executed. The source code from a high level language to a lower level language or machine
equivalent assembly language representation is easier to remember (more mnemonic): language.
 mov al, 061h
This instruction means, Move the hexadecimal value 61 (97 decimal) into the Interpreter: An interpreter is a program, which translates a high-level language
processor register named "al". program into machine level language. But, it translates one instruction of a program at
The mnemonic “mov" is an operation code or opcode, and was chosen by the a time.
instruction set designer to abbreviate "move." A comma-separated list of arguments or Advantages of High Level Language
parameters follows the opcode; this is a typical assembly language statement. 1. It is a machine independent language.
Transforming assembly into machine language is accomplished by an assembler, and 2. They are easier to learn and understand.
the reverse by a disassembler. 3. Programs written in this language are portable and easier to maintain.
Advantages of Assembly Language 4. In this program can be easily written because natural language English is used.
1. Easy to understand because of mnemonic code. Limitations
2. Easy to detect and correct error. 1. The high level language programs take more time to run.
3. Easily modified 2. Computers are unable to understand instruction given in high level language.
4. It saves time and reduces complexity than machine language program.
5. The computation time of assembly language program is less.
Limitations
1. The assembly language is machine oriented. This means that program must have
OPERATING SYSTEM: -
the detailed knowledge of the structure of the computer.
2. Assembly language program contains more instruction as compared to high-level An operating system is a software program that provides an interface between the user
languages. and the computer and manages thousands of applications.
Most computer systems are sold with an operating system installed. Computers that are
C. High Level Language
designed for individual users are called personal Computers (PCs). PC operating
To overcome the difficulties associated with assembly language, high level language

10 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
11

systems are designed to control the operations of programs such as Web browsers,
word processors, and e-mail programs.
The operating system is stored on disk, but it needs to be loaded into memory (RAM)
once the computer is switched on and before any other program can be run. How is
this done?

The operating system is automatically loaded into memory as soon as you turn on, or
boot, the computer. The term booting refers to the process of loading an operating
system into a computer’s memory. This process is done by a program (called the
bootstrap loader) that is stored permanently in the computer’s electronic circuitry
(usually on a ROM chip).

 Operating System is software, which makes a computer to actually work.


 It is the software the enables all the programs we use. The structure of OS consists of 4 layers:
 The OS organizes and controls the hardware. 1. Hardware
 OS acts as an interface between the application programs and the machine Hardware consists of CPU, Main memory, I/O Devices, etc,
hardware. 2. Software (Operating System)
 Examples: Windows, Linux, Unix and Mac OS, etc., Software includes process management routines, memory management routines, I/O
control routines, file management routines.
What Operating System does? 3. Shell (System programs)
An operating system performs basic tasks such as, This layer consists of compilers, Assemblers, linker etc.
 controlling and allocating memory, 4. Application programs
 prioritizing system requests, Software that do specific task or solve a specific problem. This is dependent on
 controlling input and output devices, users need. Ex. Railway reservation system, Bank database management etc.
 Facilitating networking 5. Users
 Managing file systems. Users normally interact with the system via the user interfaces provided by the
application software.
Structure of Operating System:
Basic functions of any operating system
All operating systems perform the same basic functions:
 Process management
Process management module takes care of creation and deletion of processes,
scheduling of system resources to different processes requesting them, and providing
mechanisms for synchronization and communication among processes.
 Memory management
This module takes care of allocation and de-allocation of memory space to programs in
need of this resource.
 File management
File management module takes care of file related activities such as organization,

11 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
12

storage, retrieval, naming, sharing, and protection of files.  Users did not interact directly with the computer systems, but he prepared a
 Security job (comprising of the program, the data, & some control information).
This module protects the resources and information of a computer system against Multiprogramming
destruction and unauthorized access.
 Command interpretation  Multiprogramming is a technique to execute number of programs
Command interpretation module takes care of interpreting user commands and simultaneously by a single processor.
directing system resources to process the commands.  In Multiprogramming, number of processes resides in main memory at a
 Resources management – These programs coordinate all the computer’s time.
resources including keyboard, mouse, printer, monitor, storage devices and
memory.  The OS picks and begins to execute one of the jobs in the main memory.
 Providing a user interface – Users interact with application programs and  If any I/O wait happened in a process, then CPU switches from that job to
computer hardware through a user interface. Almost all operating systems today another job.
provide a windows-like Graphical User Interface (GUI) in which graphic objects  Hence CPU in not idle at any time.
called icons are used to represent commonly used features. OS
 Running applications – These programs load and run applications such as
word processors and spread sheets. Most operating systems support multitasking, JOB 1
or the ability to run more than one application at a time.
 Control to the computer hardware – The operating system sits between the JOB 2
programs and the Basic Input Output System (BIOS). The BIOS controls the
hardware. All programs that need hardware resources must go through the JOB 3
operating system. The operating system can either access the hardware through the
BIOS or through the device drivers.  Figure depicts the layout of multiprogramming system.
 The main memory consists of 3 jobs at a time, the CPU executes one by one.
Types of Operating systems Advantages:
Batch Processing:-  Efficient memory utilization
Batch processing was the very first method of processing which was adapted. The  Throughput increases
main purpose of this system was to enable the computer to move automatically from  CPU is never idle, so performance increases.
one job to another, without the operator having to intervene. Time Sharing Systems:
 Time sharing, or multitasking, is a logical extension of
 In Batch processing same type of jobs batch (BATCH- a set of jobs with
multiprogramming.
similar needs) together and execute at a time.
 The OS was simple, its major task was to transfer control from one job to the  Multiple jobs are executed by switching the CPU between them.
next.  In this, the CPU time is shared by different processes, so it is called as
 The job was submitted to the computer operator in form of punch cards. At “Time sharing Systems”.
some later time the output appeared.  Time slice is defined by the OS, for sharing CPU time between processes.
 The OS was always resident in memory. (Ref. Fig. next slide)  Examples: Multics, Unix, etc.,
 Common Input devices were card readers and tape drives.
 Common output devices were line printers, tape drives, and card punches. Types of OS:

12 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
13

 Single User Systems The term software refers to a set of computer programs, procedures, and associated
 Multi User Systems documents (flowcharts, manual, etc.) describing the programs, and how they are to be
Single User Systems: used.
Single user systems, as their name implies, provide a computer system for only one
A software package is a group of programs that solve a specific problem or perform a
user at a time. They are appropriate for computer dedicated to a single function, or
specific type of job.
which are so inexpensive as to make sharing not worthwhile. Most microcomputer
operating systems are of the single user type. Single user systems generally provide a Category: -
simple computer system, which facilitates the running of a variety of software 1. System software
packages (e.g. word processing or spread sheet) as well as allowing uses to develop 2. Application software
and execute programs of their own. The major emphasis is on the provision of an
System software:-
easily used interface, a simple file system, and I/O facilities for keyboard, display, disk It is a set of one or more programs designed to control the operation and extend the
and printer. processing capability of a computer system.
 Provides a platform for only one user at a time. It performs following function: -
 They are popularly associated with Desktop operating system which runs 1. Supports development of other application software.
on standalone systems where no user accounts are required. 2. Supports execution of other application software.
Example: DOS 3. Monitors effective use of various hardware resources such as CPU, memory,
Multi-User Systems: peripherals, etc.
In an interactive system, the user sits at a terminal, which is hooked up to the 4. Communicates with and controls operation of peripheral devices such as
computer. The user can execute the job, and the output is expected to be reasonably printer, disk, tape, etc.
instantaneous, even if other users are executing their own jobs on the same computer. System software makes the operation of computer system more effective and efficient.
To meet these situations, the principle of time-sharing was introduced in the design of The programs included in a system software package are called system programs. The
operating systems. The aim of a time-sharing operating system is to give each terminal programmers who prepare system software are referred to as system programmers.
user a response time (called time-slice) of about three to five seconds. Some commonly known types of system software are: -
A time-sharing system works on the same principles as a multiprogramming system,  operating system
except that now the jobs are interactive Operating system software takes care of effective and efficient utilization of
 Provides regulated access for a number of users by maintaining a database all hardware and software components of a computer system.
of known users.  Programming language translators
 Refers to computer systems that support two or more simultaneous users. It transforms the instructions prepared by programmers in programming
 Another term for multi-user is time sharing. language into a form that can be interpreted and executed by a computer
 Ex: All mainframes and are multi-user systems. system.
 Example: Unix  Communications software :-
Software: - In a network environment communications software enables transfer of data
and programs from one computer system to another.
 Utility programs :-

13 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
14

Utility programs are a set of programs that help user is system maintenance tasks, and  Digital Video Disk Read-Only Memory (DVD-ROM)
in performing tasks of routine nature.  CD-Recordable (CD-R)
Application software: -  CD-Rewritable (CD-RW)
It is a set of one or more programs designed to solve a specific problem, or do a
 PhotoCD
specific task. The programs included in an application software package are called
application programs. The programmers who prepare application software are referred How Magnetic Storage Works e.g. hard disk
to as application programmers.  A magnetic disk's medium contains iron particles, which can be
There is literally millions of application software available for a wide range of polarized—given a magnetic charge—in one of two directions.
application. They range from simple applications to complex scientific and engineering  Each particle's direction represents a 1 (on) or 0 (off), representing each
applications. bit of data that the CPU can recognize.
Some commonly known application software is:  A disk drive uses read/write heads containing electromagnets to create
1. Word processing software magnetic charges on the medium.
2. Spread sheet software
3. Database software
4. Graphics software
5. Personal assistance software
6. Education software
7. Entertainment software

STORAGE DEVICES
 Storage devices hold data, even when the computer is turned off.
 The physical material that actually holds data is called storage medium.
The surface of a floppy disk is storage medium.
 The hardware that writes data to or reads data from a storage medium is
called a storage device. A floppy disk drive is a storage device.
 The two primary storage technologies are magnetic and optical.
Primary types of magnetic storage are:
 Diskettes (floppy disks)
 Hard disks
 High-capacity floppy disks
 Disk cartridges Magnetic Storage Devices – Formatting
 Magnetic tape  Before a magnetic disk can be used, it must be formatted—a process that
The primary types of optical storage are: maps the disk's surface and determines how data will be stored.
 Compact Disk Read-Only Memory (CD-ROM)

14 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
15

 During formatting, the drive creates circular tracks around the disk's
surface, then divides each track into sectors.
 The OS organizes sectors into groups, called clusters, then tracks each
file's location according to the clusters it occupies.
Formatted Disk

Magnetic Storage Devices - Hard Disks


Track  Hard disks use multiple platters, stacked on a spindle. Each platter has
Magnetic Storage Devices - Disk Areas two read/write heads, one for each side.
When a disk is formatted, the OS creates four areas on its surface:  Hard disks use higher-quality media and a faster rotational speed than
 Boot sector – stores the master boot record, a small program that runs diskettes.
when you first start (boot) the computer  Removable hard disks combine high capacity with the convenience of
 File allocation table (FAT) – a log that records each file's location and diskettes.
each sector's status
 Root folder – enables the user to store data on the disk in a logical way
 Data area – the portion of the disk that actually holds data

 Hard disks store large amounts of data. New PCs feature hard disks with
capacities of 10 GB and higher. Now its storage capacity is available in 80
GB, 160GB, 320GB, 500GB, 750GB, and 1000GB.
Optical Storage Devices

15 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
16

 CD-ROM  Early CD-ROM drives were called single speed, and read data at a rate of
 DVD-ROM 150 KBps. (Hard disks transfer data at rates of 5 – 15 MBps).
How Optical Storage Works  CD-ROM drives now can transfer data at speeds of up to 7800 KBps.
 An optical disk is high-capacity storage medium. An optical drive Data transfer speeds are getting faster.
uses reflected light to read data.  CD-ROM is typically used to store software programs. CDs can store
 To store data, the disk's metal surface is covered with tiny dents (pits) and audio and video data, as well as text and program instructions.
flat spots (lands), which cause light to be reflected differently. Optical Storage Devices - DVD-ROM
 When an optical drive shines light into a pit, the light cannot be reflected  A variation of CD-ROM is called Digital Video Disk Read-Only Memory
back. This represents a bit value of 0 (off). A land reflects light back to (DVD-ROM), and is being used in place of CD-ROM in many newer
its source, representing a bit value of 1 (on). PCs.
 Standard DVD disks store up to 9.4 GB of data—enough to store an entire
movie. Dual-layer DVD disks can store up to 17 GB.
 DVD disks can store so much data because both sides of the disk are used,
along with sophisticated data compression technologies.
Other Optical Storage Devices
• A CD-Recordable (CD-R) drive lets you record your own CDs, but data
cannot be overwritten once it is recorded to the disk.
• A CD-Rewritable (CD-RW) drive lets you record a CD, then write new data
over the already recorded data.
• PhotoCD technology is used to store digital photographs.
Blu-Ray Disk
The name Blu-ray Disc is derived from the blue laser (violet coloured) used to read
and write this type of disc. Because of its shorter wavelength (405 nm), substantially
more data can be stored on a Blu-ray Disc than on the DVD format, which uses a
Optical Storage Devices – CD-ROM red (650 nm) laser. A dual layer Blu-ray Disc a store 50GB, almost six times the
capacity of a dual layer DVD.
 In PCs, the most commonly used optical storage technology is called Compact
Blu-ray Disc was developed by the Blu-ray Disc Association, a group of companies
Disk Read-Only Memory (CD-ROM). representing consumer electronics, computer hardware, and motion picture production.
 A standard CD-ROM disk can store up to 650 MB of data, or about 70 As of July 2, 2008 more than 650 Blu-ray Disc films have been commercially released
minutes of audio. in the United States and more than 410
 Once data is written to a standard CD-ROM disk, the data cannot be altered or Blu-ray Disc titles have been released in Japan.
overwritten.
Blu-ray Disc uses a "blue" (technically violet) laser operating at wavelength of 405nm
to read and write data. Conventional DVDs and CDs use red and near infrared lasers at
CD-ROM Speeds and Uses 650 nm and 780 nm respectively.

16 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
17

The blue-violet laser's shorter wavelength makes it possible to store more information
on a 12 cm CD/DVD sized disc. The minimum "spot size" on which a laser can be
focused is limited by diffraction, and depends on the wavelength of the light and the 2nd unit
numerical aperture of the lens used to focus it. By decreasing the wavelength,
increasing the numerical aperture from 0.60 to 0.85 and making the cover layer thinner
to avoid unwanted optical effects, the laser beam can be focused to a smaller spot. This
allows more information to be stored in the same area. For Blu-ray Disc, the spot size
is 580nm.

 It is an optical disc storage media format.


 Its main uses are high-definition video and data storage.
 The disc has the same dimensions as a standard DVD or CD.
 Uses a 405nm blue laser to read/write data.
 Blu-ray Disc was developed by the Blu-ray Disc Association.

 HD video recording.
 More recording time UNIT - 2
Network
for standard video.
 High storage capacity: A network consists of 2 or more computers connected together, and they can
communicate and share resources (e.g. information)
 25GB (single layer)
 50GB (double layer) Computer network
 A computer network is a group of interconnected computers.
 It allows computers to communicate with each other and to share resources
and information.
 First Network : The Advanced Research Projects Agency (ARPA) funded the
design of the "Advanced Research Projects Agency Network" (ARPANET)
for the United States Department of Defense

 25GB Type (single layer):


 BD-ROM (read-only) - for pre-recorded content
 BD-R (recordable) - for PC data storage
 BD-RW (rewritable) - for PC data storage
 BD-RE (rewritable) - for HDTV recording
 Mini-BD
17 (7.5
CSEGB) – 8cm
3rd sem diameter CONCEPT AND WEB TECHNLOGY |
COMPUTER By ATUL SINGH-JKIE BILASPUR
 BD9 / BD5 (lower capacity type) - 8152MB BD9, 4489MB BD5
18

Computer network classification: -


1. Local Area Network (LAN)
2. Metropolitan Area Network (MAN)
3. Wide Area Network (WAN) Metropolitan Area Network (MAN)
4. INTERNET
A metropolitan area network (MAN) is a computer network in which two or more
Local Area Network (LAN) computers or communicating devices or networks which are geographically separated
A local area network (LAN) is a privately owned computer network that but in same metropolitan city and are connected to each other are said to be connected
on MAN. The limits of Metropolitan cities are determined by local municipal
connects computers and other information processing device within a limited corporations and we cannot define them. Hence, the bigger the Metropolitan city the
area (few kilometres) such as a home, school/classroom, building, bigger the MAN, smaller a metro city smaller the MAN.
manufacturing plant, computer laboratory, or office building using network MAN is optimized for a larger geographical area than a LAN, ranging from several
media. In many organizations, it has become common place for LANs to blocks of buildings to entire cities. MANs can also depend on communications
provide telecommunications network capabilities that link end users in channels of moderate-to-high data rates. A MAN might be owned and operated by a
single organization, but it usually will be used by many individuals and organizations.
departments, offices, and other workgroups. Coaxial cable, ordinary wiring, MANs might also be owned and operated as public utilities. They will often provide
and even wireless radio and infrared systems, to interconnect microcomputer means for inter-networking of local networks.
workstations and computer peripherals are some examples of LANs that are
used with telecommunications media.
Network Interface card is circuit board that are usually in a PC that are used to
communicate over the network. LANs use a more powerful microcomputer
with a larger hard disk capacity, called a file or network server.
In general a local area network can have the one of the following four
configurations 1.Bus 2.Ring 3.Star 4.Ring-star hybrid. Different configuration
use different network access technique and yield different performance.

18 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
19

 Modem
Device that enables computers to communicate through phone lines.
When we start internet our modem communicates to modem of ISP.
 Computer
In addition to a modem, you need a client capable of handling multiple data
types.
 Software
Two types of software are required to enable your PC as an Internet PC.
 Communication software to establish connection
 Client software for browsing, e-mail, news.
This software’s are provided with windows itself.

Wide Area Network (WAN)

A wide area network (WAN) is a network that covers a broad area (i.e.,
any telecommunications network that links across metropolitan, regional, or national
boundaries) using private or public network transports. Business and government
entities utilize WANs to relay data among employees, clients, buyers, and suppliers
from various geographical locations.

• Wide area networks (WANs) carry message at a lower speed between


computers that are separated by large distance.
• Many WANs and LANs can be combined to produce a single internetwork – a
communication system that interconnects large collections of geographically
dispersed computers.
• The computers interconnected by a WAN are called host computers. The
communication medium is a set of communication circuits linking a set of
dedicated computers called packet switches or packet switching exchanges
(PSEs). Applications of Internet
The OSI layer architecture, TCP/IP layer architecture, or other layer architectures can  Download programs and files
be used in building WANs  E-Mail
 Voice and Video Conferencing
Internet: -  E-Commerce
 It is a Global network of computers, (servers or clients) to exchange  File Sharing
information.  Information browsing
 It is a "network of networks" that includes millions of private and public,  Search the web addresses for access through search engine
academic, business, and government networks (local or Global), linked by  Chatting and many more…
copper wires, wireless connections, and other technologies. Intranet
Variety of hardware and software are used to make Internet functional.

19 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
20

 Internal company network that uses Internet standards (HTML, HTTP &
TCP/IP protocols) & software. DATA TRANSMISSION
 Accessed only by authorized persons, especially members or employees of the
organization The transmission of binary data across a link can be accomplished in either parallel
 Two levels of Security required: or serial mode.
 Internal
o It can be imposed by Public Key Security & Encryption Key.
 External
o Through Firewall.

 Security device located between firm’s internal network (intranet) & external
network (internet).
 Regulates access into & out of a company’s network based on a set of rules.

Parallel transmission: In parallel mode, multiple bits are sent with each
clock tick.

Applications of Intranet

 Sharing of company policies/rules & regulations


 Access employee database
 Distribution of circulars/Office Orders
 Access product & customer data
 Sharing of information of common interest
 Launching of personal/departmental home pages
 Submission of reports
 Corporate telephone directories
20 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
21

Serial Transmission: In serial mode, 1 bit is sent with each clock tick. The advantage of synchronous transmission is speed. With no extra bits or gaps to
introduce at the sending end and remove at the receiving end, and, by extension, with
fewer bits to move across the link, synchronous transmission is faster than
asynchronous transmission.
Synchronous Transmission diagram

Asynchronous Transmission Isochronous Transmission


In asynchronous transmission, we send 1 start bit (0) at the beginning and 1 or more The term isochronous refers to a periodic signal, pertaining to transmission in which
stop bits (1s) at the end of each byte. There may be a gap between each byte. the time interval separating any two corresponding transitions is equal to the unit
Asynchronous here means “asynchronous at the byte level,” but the bits are still interval or to a multiple of the unit interval. For example, an end-to-end network
synchronized; their durations are the same. connection is said to be isochronous such as real-time audio or motion video.
Asynchronous Transmission diagram
The isochronous transmission guarantees that the data arrive at a fixed rate.

Synchronous Transmission
In synchronous transmission, we send bits one after another without start or stop bits or
gaps. It is the responsibility of the receiver to group the bits. The bits are usually sent
as bytes and many bytes are grouped in a frame. A frame is identified with a start and
an end byte.
Timing becomes very important, therefore, because the accuracy of the received Isochronous data transfer guarantees bandwidth but not data integrity. As each device
information is completely dependent on the ability of the receiving device to keep an is placed on the bus, it requests bandwidth on the bus. The amount of bandwidth the
accurate count of the bits as they come in. device requests is determined by its packet size (in KB/packet). The bus is divided into

21 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
22

125 microsecond cycles. Each cycle begins with an Asynchronous cycle start packet. • Full-Duplex: Data can travel in both directions simultaneously.allows
Devices that have requested isochronous bandwidth are guaranteed a single packet transmission in two directions simultaneously
during each cycle. Once the packets are sent from each device, the remainder of the – It is analogous to a voice telephone conversation
cycle is left for any other asynchronous transfers that need to take place. Overall, – in which a participant can speak even if they are able to hear
approximately 80% of each cycle is dedicated to isochronous data transfers. Because background music at the other end
the recipient does not acknowledge that it receives a packet, there is no guarantee that
the data made it across the bus. However, data received at one end is guaranteed to be
in time with the data transmitted. In most cases (particularly those configurations that
have only two devices on the bus), the transmission is successful
Transmission Mode
A communications channel is classified as one of three types: (Depending on the Internet
direction of transfer) The Internet is a global system of interconnected computer networks that use the
• Simplex standard Internet protocol suite (TCP/IP) to serve several billion users worldwide. It is
• Full-Duplex a network of networks that consists of millions of private, public, academic, business,
• Half-Duplex and government networks, of local to global scope, that are linked by a broad array of
• Simplex: Data in a simplex channel is always one way. Sender can send
electronic, wireless and optical networking technologies. The Internet carries an
receiver can receive only. a simplex mechanism can only transfer data in a extensive range of information resources and services, such as the inter-
single direction linked hypertext documents of the World Wide Web (WWW), the infrastructure to
– It is analogous to broadcast radio or television
support email, and peer-to-peer networks.

HISTORY

In the late 1950's the Advanced Research Projects Agency (ARPA) was founded
in the United States with the primary focus of developing information
• Half-Duplex: A half-duplex channel can send and receive, but not at the same
technologies that could survive a nuclear attack. In 1967 ARPA University and
time.A half-duplex mechanism involves a shared transmission medium
private sector contractors met with representatives of the Department of
– The shared medium can be used for communication in each direction Defense to discuss possible protocols for sharing information via computers. In
– But the communication cannot proceed simultaneously 1969, ARPANET was born. It connected four sites at the University of California
– It is analogous to using walkie-talkies where only one side can at Los Angeles, the University of California at Santa Barbara, Stanford Research
transmit at a time Institute, and the University of Utah. Throughout the 1970's researchers
concentrated on developing protocols for controlling networks, moving
messages across a system of networks, and allowing for remote access to the
networks. There were computers connected at about two dozen sites when the
first email was sent in 1972, but the number of sites and messages soon
mushroomed. By 1975 there were 63 sites. In 1980, 200 host computers were
connecting 20,000 people at university, military, and government locations.
22 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
23

Twelve years later the number of hosts had grown to more than a million  Dial-up connections today are considered the slowest but the reputation of
internationally and in January of 1999 there were more than 43 million. being most inexpensive. Connection rates for dial-up modems tend to fall
between 24 kbps to 56 kbps.
If the 1970's were a time of research, the 1980's were a time of development. The Features of dial up
TCP/IP protocol was introduced in 1983, and at the University of Wisconsin the name
 Uses POTS (Plain Old Telephone System)
server was developed. The next year domain name server (DNS) was established. In
1986, the National Science Foundation developed a system to connect the growing  Provides a low cost need based access.
number of hosts. Regional networks were connected to a backbone network, which  Bandwidth 24 to 56 Kbps
became known as the NSFNET. As the "Internet" continued to grow and prosper,  On the Customer End Modem is connected to a Telephone Line.
ARPANET came to an end in 1989) just before HTML protocol was introduced in  Achievable bandwidth depends on the line quality
1990. HTML allowed graphics to be sent along with text to create hypertext pages
customized to the sender's preference. Everything was now in place for explosive
growth.
Connecting to Internet:
We are basically connected with internet by Internet Service Provider (ISP) / Internet
Access Provider (IAP) Wireless Service Provider (WSP)
Internet Service Provider (ISP)
 ISP is a business or organization that provides access
 To Internet and related services to consumers.
 Mostly, an ISP is a telephone company.
 Common offer is Dialup and DSL Connection
Wireless Service Provider (WSP)
 A company that provides wireless Internet access to the users with wireless
modems.
 Notebooks/laptops and Cellular phones are example of wireless devices
accessing the internet. Cable Connection
TYPE OF INTERNET CONNECTIONS  Cable connection offers very fast and reliable connections with fixed monthly
– Dialup fee. Because cable connections use a different medium to connect you to the
– Cable Connection Internet, it will not affect how you use your telephone.
– DSL Broadband  Cable broadband Internet connections offer data transfer rates of
– Dedicated Leased Line approximately 1.5 Mbps up to 7.5 Mbps.
– ISDN
– Wireless Connection
Dial up connection
 Dial-up connections are the most common type of Internet Connection for
home users.

23 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
24

whether the cable TV networks can handle the traffic that would ensue if millions
of users begin using the system for Internet access.
Cost: Installation costs $100 or more. Monthly fees are between $40 to $60, which
often includes an Internet service package with unlimited access, specific software
and content, and the option to lease a cable modem.
Availability: Cable access has no such restriction as limitation of distance for
DSL, but the availability is still an issue with cable access. Not all cable providers
offer internet access, but they are steadily increasing service availability. To find
Cable is another broadband option which takes advantage of another setup found out whether one’s home qualifies, call one’s cable provider or visit the sites of
in homes-cable TV. A cable modem uses the cable TV provider’s hybrid Fiber/Co- some of the larger, national providers. (See below)
ax infrastructure as a shared data network. All of the devices connected to the National cable modem service providers (These carriers are not available in all
neighbourhood co-ax network talk and listen to each other. areas, and most have exclusive contracts with local cable operators.)

Internet service provider (ISP)


o Any company that provides individuals or companies with access to
the Internet
o Thousands of providers including large communications companies
o Need an account with the ISP and software that links with TCP/IP
An Internet service provider (ISP, also called Internet access provider) is a
business or organization that offers users’ access to the Internet and related
Speed: Cable TV systems were originally designed to deliver large amounts of services. Many but not all ISPs are telephone companies or other
bandwidth (TV pictures and audio) from the head end (central distribution point) telecommunication providers. They provide services such as Internet access,
to the user (TV sets). These networks are capable of carrying large amounts of Internet transit, domain name registration and hosting, dial-up access, leased
computer data in the downstream direction, but the other direction is not the same. line access and colocation. Internet service providers may be organized in various
Theoretically cable modes can operate at speeds of up to 50 Mbps for forms, such as commercial, community-owned, non-profit, or otherwise privately
downloading, 10 Mbps for uploading. But practically, these can deliver 1 Mbps to owned.
10 Mbps for downloading and 200 Kbps to 2Mbps for uploading. One problem is
variability of speed. If many users are using the network simultaneously, the
connection speed will decrease, because cable network users share a semi-LAN
connection to the internet with other members of their neighbourhood. It is
basically impossible to precisely predict connection speeds. Also, it is unknown

24 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
25

Satellite Internet is the ability to transmit and receive data from a relatively small
satellite dish on Earth and communicate with an orbiting geostationary satellite
22,300 miles above Earth's equator. The orbiting satellite transmits (and receives)
its information to a location on Earth called the Network Operations
Center or NOC (pronounced "knock"). The NOC itself is connected to the
Internet (or private network), so all communication made from a satellite dish
connection to the Internet must flow through the NOC.

1. Internet services were launched in India on 15th August, 1995 by Videsh Sanchar
Nigam Limited. In Nov, 1998, the Government opened up the sector for providing
Internet services by private operators. A liberal licensing regime was put in place with
a view to increase Internet penetration across the country. The New Telecom Policy
envisaged opening up of internet Telephony where upon Government decided to
permit ISPs to process and carry voice signals (Restricted Internet Telephony) with
effect from 1st April 2002. Data communication via satellite is not much different than someone using a land
2. In year 2007, the Government decided to issue a single licence under ISP guidelines based data provider, at least from the end-users standpoint. The key to remember
is that once the satellite system is configured by the installer, the service acts
dated 24.08.07 which permits restricted Internet Telephony for the ISPs.
nearly identically as any other data service and may be configured as such. Those
3. Subsequent to ISP Guidelines dated 24.08.07
differences will be described later.
Category Entry Fee Rs. PBG Rs. FBG Rs. A satellite Internet connection is an arrangement in which the upstream (outgoing)
and the downstream (incoming) data are sent from, and arrive at, a computer
A (All India) 30 Lakh 2 Crore 10 Lakh through a satellite. Each subscriber's hardware includes a satellite dish antenna and
B ( a service Area out of 23 areas) 15 Lakh 20 Lakh 1Lakh a transceiver (transmitter/receiver) that operates in the microwave portion of the
radio spectrum.

SATELLITE CONNECTION

25 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
26

 Email travels via the Internet from one computer to another.


 Computers known as mail servers direct outgoing mail and store
incoming the mail.
 Once email reaches your mail server, it waits in an electronic mail
box, the "Inbox” for you to collect it.
o Compose and Send: write an email and send it to others.
o Reply: reply to an email that you received.
o Forward: pass on an email that you received to others.
o Attachment: You can send files with your email such as: pictures, music,
software and documents

Rahul_singh@gmail.co
m

In a two-way satellite Internet connection, the upstream data is usually sent at a Unique User Name Domain Name
slower speed than the downstream data arrives. Thus, the connection is Chosen by the email Company/organization
asymmetric. A dish antenna, measuring about two feet high by three feet wide by Account owner Providing the email service
three feet deep, transmits and receives signals. Uplink speeds are nominally 50 to
150 Kbps for a subscriber using a single computer. The downlink occurs at speeds
ranging from about 150 Kbps to more than 1200 Kbps, depending on factors such
as Internet traffic, the capacity of the server, and the sizes of downloaded files.
E-Mail
Electronic mail, most commonly referred to as email since approximately 1993.
It is a method of exchanging digital messages from an author to one or more
recipients. Modern email operates across the Internet or other computer networks.
Some early email systems required that the author and the recipient both
Post Office Protocol In a POP3 email account, email messages are downloaded to
be online at the same time, in common with instant messaging. Today's email
the client device (i.e. a computer) and then they are deleted from the mail server.
systems are based on a store-and-forward model. Email servers accept, forward,
deliver, and store messages. Neither the users nor their computers are required to Simple Mail Transfer Protocol (SMTP), first published as Internet standard 10
be online simultaneously; they need connect only briefly, typically to an email in 1982. In the process of transporting email messages between systems, SMTP
server, for as long as it takes to send or receive messages. communicates delivery parameters using a message envelope separate from the
message (header and body) itself.
How does Email Work?

26 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
27

Voice/Audio conference While audio conference calls can come on many forms, it can include web-based
Audio refers to sound. A conference is a meeting. Audio conferencing usually refers to VOIP (voice Over Internet protocol). Most audio conferences happen over the phone
meetings held by people in different places using devices that allow sounds to be sent
using either with regular analog or cell phones.
and received. These meetings may only involve two parties, but in many cases, there
are numerous parties involved. The fundamental concept of audio conferencing utilizes two or more speakerphones
Audio conferencing allows multiple parties to connect using devices such as phones or and several dial up numbers. These numbers can be local or toll free long distance
computers. This can be a solution for a number of problems that can arise when numbers. You can also choose to make the conference call on your own and then run
multiple parties need to meet. People who are distant and busy do not have to sacrifice the long distance charges on your own or you can also have the option of signing up
the travel time since the meeting can be conducted from a nearby phone or computer.
for one of several audio conferencing services. These services will provide a wide
A person who would otherwise be excluded due to a bedridden illness can participate.
Money that would be needed to book a meeting facility or host a lunch meeting can be range of package types that will support the dial up, long distance and logins
saved. differently depending on the type of package that you get.

Video conferencing
Video conferencing is a set of telecommunication technologies which allow two or
more locations to communicate by simultaneous two-way video and audio
transmissions. It has also been called 'visual collaboration' and is a type of groupware.
Video conferencing in its most basic form is the transmission of image (video) and
speech (audio) back and forth between two or more physically separate locations.”
There are numerous methods and technologies that support audio conferencing. Many Videoconferencing Components
telephone companies offer the capability of three-way calling. This allows a person to  Cameras (to capture and send video from your local endpoint)
call two other people on separate lines and join them together to form a group. Each  Video displays (to display video received from remote endpoints)
person in the group who has three-way calling has the ability to expand the meeting by  Microphones (to capture and send audio from your local endpoint)
adding two more people.  Speakers (to play audio received from remote endpoints)
 Codec - "compressor/de-compressor“ - makes the audio/video data "small
Conferencing services offer various features to their clients that can make telephone enough" to be practical for sending over expensive network connections.
audio conferencing an even more attractive option. A codec takes analog signals, compresses and digitizes them, and
transmits the signals over digital phone lines.
 The Supporting System and the Network Connection
Audio conferencing can also be conducted using a computer and the Internet. If a
ITU H.320, H.323 standard
person is only listening, he will only need speakers. If he plans to speak, he will need a  Standard for interoperability in audio, video and data transmissions as
microphone as well. well as Internet phone and voice-over-IP (VoIP)
 Enables videoconferencing without usage fees
 But does not have QOS (quality of service)

27 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
28

Point-to-point – A videoconference that connects two locations. Protocols exist at several levels in a telecommunication connection. For example, there
are protocols for the data interchange at the hardware device level and protocols for
 Each site sees and hears the other sites at all times
data interchange at the application program level. In the standard model known as
Point-to-multipoint – A videoconference that connects to more than two sites through Open Systems Interconnection (OSI), there are one or more protocols at each layer in
the use of a multi-point control unit, or MCU. the telecommunication exchange that both ends of the exchange must recognize and
 Participants at all sites can hear one another at all times and see the site that is observe.
currently speaking. Voice activated switching The TCP/IP Internet protocols, a common example, consist of:
 Multi-point conferencing can be effective although the scheduling, technical, and  Transmission Control Protocol (TCP), which uses a set of rules to exchange
logistical dimensions of MCU conferences can be imposing.
messages with other Internet points at the information packet level
 Internet Protocol (IP), which uses a set of rules to send and receive messages at
the Internet address level
 Additional protocols that include the Hypertext Transfer Protocol (HTTP) and File
Transfer Protocol (FTP), each with defined sets of rules to use with corresponding
programs elsewhere on the Internet

Developing an Effective Web Strategy


1. Analysis and need of solution
The web development process begins with this phase. At this point of
initiation a detailed study is carried out as to what is the actual requirement of
the customer and how it can be accomplished.
2. Planning and designing
Protocol governing the web What to do: this section includes the conceptualization of design and what all
• Protocols define how messages are sent and received, i.e. the format and order technologies are to be undertaken.
of them, what happens when messages are transmitted and received. When to do: at this stage of planning the entire process of website making is
• Efficient protocols are what allow the Internet to operate in the decentralized classified with respect to time period.
manner that they do. How to do: in this phase of designing the techniques of what all features are
• Packet routing using these protocols also allows for reasonably good error to be included and what all techniques are to be utilized for same are finalized.
checking/correcting methods, and reliability of transmissions. 3. Implementation
In information technology, a protocol is the special set of rules that end points in a Once done with the planning and designing of the solution to be proposed
telecommunication connection use when they communicate. Protocols specify comes the actual implementation process. In this after a design has been
interactions between the communicating entities. finalized comes the process of programming. At this level features like login
and shopping cart are inculcated.

28 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
29

4. Testing  Application [Software]: “Application software, also known as an


After completing the process of designing and implementation comes the application or an ‘app’, is computer software designed to help
testing phase. In this the product is tested for its error free working and
the user to perform singular or multiple related specific tasks.”
efficiency.
 Web technologies: Flash, Silverlight, JavaScript, HTML & CSS, Java, various
5. Maintenance and post implementation
The process of web development comes to an end at the stage of other programming languages and other computer technology intended for the use
maintenance and implementation. In this the outcome is taken care of. across networks.
 Network: The internet or intranet.
 Browser: Firefox, Chrome, Safari, Opera, Internet Explorer and various others

The figure below details the three-layered web application model. The first layer is
normally a web browser or the user interface; the second layer is the dynamic content
generation technology tool such as Java servlets (JSP) or Active Server Pages (ASP),
Web Application and the third layer is the database containing content (e.g., news) and customer data
(e.g., usernames and passwords, social security numbers and credit card details).
A web-based application is any application that uses a web browser as a
client. The term may also mean a computer software application that is coded in a
browser-supported programming language (such as JavaScript, combined with a
browser-rendered markup language like HTML) and reliant on a common web
browser to render the application executable

29 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
30

o Caches – many interesting implementations


o Internet – the global infrastructure which facilitates data transfer
 Semantic Components
o Hyper Text Transfer Protocol (HTTP)
o Hyper Text Markup Language (HTML)
o eXtensible Markup Language (XML)
o Uniform Resource Identifiers (URIs)
WWW Structure
 Clients use browser application to send URIs via HTTP to servers requesting a
Web page.
 Web pages constructed using HTML (or other markup language) and consist
of text, graphics, and sounds plus embedded files.
 Servers respond with requested Web page or with error message.
 Client’s browser renders Web page returned by server
o Page is written using Hyper Text Markup Language (HTML)
o Displaying text, graphics and sound in browser
o Writing data as well
 The entire system runs over standard networking protocols (TCP/IP, DNS,)

UNIT 3
World Wide Web (WWW)

The World Wide Web, abbreviated as WWW and commonly known as the Web,
is a system of interlinked hypertext documents accessed via the Internet.
In 1989 to 1990 - English engineer and computer scientist Sir Tim Berners-Lee
WWW consist following -
invents the World Wide Web at CERN (European Organization for Nuclear
 Website - A collection of related web pages
Research)
 Web browser - a software tool that retrieves and displays Web pages
WWW Components –
 Web server- A computer set up to respond to requests for Web pages
 Structural Components  Uniform Resource Locator (URL) - A standard way of specifying the
o Clients/browsers – to dominant implementations location of a Web page, containing the hostname, "/", and a file
o Servers – run on sophisticated hardware  Search Engine - A website that helps you find other websites

30 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
31

 Hypertext Markup Language (HTML) - The language used to create or


build a Web page
 Markup language - A language that uses tags to annotate the information
in a document
 Tags - The syntactic element in a markup language that indicate how
information should be displayed
 HTTP - Protocol for client/server communication. Very simple
request/response protocol. Client sends request message, server replies
with response message.

Emergence of Web –
The World Wide Web (WWW) has been through many changes since its
beginnings and has become the largest information platform worldwide. When
Tim Berners-Lee published his ideas for hypertext in 1989, he could not have
guessed how he would change our lives. Due to technical progress made since
then, its use has become more and more intuitive and users can provide their own Web 0.5(The Rise of Tim Berners-Lee’s Vision) services are distributed and
content for public use more and more easily. Similarly, when O'Reilly Media content-offering precursors to Web pages using non-standard technologies,
coined the term "Web 2.0" in 2004, they combined a set of concepts under one protocols, and tools. Examples are systems such as Gopher, FTP, or Usenet.
notion. In addition, version numbers can be used to differentiate evolutionary steps Web 1.0 (1990 – 2000 Growth of the Web: The First Mainstream Websites)
of the Web, as it is common practice with software systems. services are presentation-oriented content viewing services based on technologies
supporting static Web pages (mainly hard-coded HTML pages) without much
interaction, used to display information. Typical examples were simple homepages
or directory services, such as AltaVista, Yahoo, or Netscape, as well as basic
supportive tools (e.g. HTML editors) and basic search engines, such as AliWeb.
Web 1.5 (The Web of Experts) services are commerce-oriented content-viewing
services based on technologies supporting dynamic pages (e.g., DHTML) and
form-based interaction that often had closed APIs and closed IDs for presenting
company-generated content. Typical examples are Google, Amazon, or eBay, as
well as basic supportive tools such as Content Management Systems or
WYSIWYG Web development tools.
Web 2.0 – (The Social web) services are user-oriented, content-sharing (upload,
edit, and download), social networking (personal data), or static mashup services
based on technologies supporting dynamic micro pages that harness collective
intelligence. They may support an open API with closed data and closed ID in

31 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
32

order to use the Web as a distributed file system (user-generated content) or A web server program is software that runs on the web site hosting Server
collaboration system (networking effects). Typical examples are YouTube, Flickr, computer. Its main purpose is serving web pages; which mean it waits for
Digg, Del.icio.us, LinkedIn, or MySpace, as well as basic supportive tools, such as requests from web browsers (also known as clients) and responds by sending the
Wikis or blogs. required data back.
Web 2.5 – (The Mobile Web) services will be (mobile) device-oriented, user-,
link-, or time-sensitive, cross-site, content-moving, virtual-reality-based, or
dynamic mashup services based on technologies supporting rich user interfaces
and user-sensitive interfaces that might support an Open ID and Open Data in Web Browser –
order to support RUE (Rich User Experiences) and personal data portability.
Examples are Second Life, Diigo, or Yahoo pipes. Web browser as a computer program used for accessing sites or information on a
Web 3.0 – (The Semantic Web) services will be content-oriented, semantic- network (as the World Wide Web). The browser application retrieves or fetches
based, context-sensitive services based on technologies supporting semantically code, usually written in HTML (HyperText Markup Language) and/or another
enriched websites that might support portable IDs in order to use the Web as a language, from a web server, interprets this code, and renders (displays) it as a
database and an operating system. Examples are Eurekster, AskWiki, Twine, or web page for you to view.
Freebase.
The web address or URL (Uniform Resource Locator), that you type into the
Web 3.5 – (The Ubiquitous Web) services will be fully pervasive, interactive,
and autonomous agents considering the personal context based on advanced browser's address bar tells the browser where to obtain a page or pages from. For
semantic technologies supporting reasoning and basic AI that might bring the example, let's say that you typed the following URL into the browser's address bar:
virtual and the real world closer together. Examples might be 3D-enhanced virtual http://about.com/compute/.
social networks, natural language services, or fully interactive real-life
environments (e.g., RFID, ambient sensors).
Web 4.0 – (The Intelligent Web) Web 4.0 services will be autonomous,
proactive, content-exploring, self-learning, collaborative, and content-generating
agents based on fully matured semantic and reasoning technologies as well as AI.
They will support adaptive content presentation that will use the Web database via
an intelligent agent. Examples might be services interacting with sensors and
implants, natural language services, or virtual reality services.

Web Server –
A web server can mean two things - a computer on which a web site is hosted
and a program that runs on such a computer. So the term web server refers
to both hardware and software. HTML
Web server computer - the hardware
A web site is a collection of web pages which are digital files generally written HTML is a format that tells a computer how to display a web page. The documents
using Hypertext Markup Language (HTML). For a web site to be available to themselves are plain text files with special "tags" or codes that a web browser uses to
everyone in the world at all times, it need to be stored or "hosted" on a computer interpret and display information on your computer screen.
that is connected to the internet. Such a computer is known as a Web Server.  HTML stands for Hyper Text Markup Language
The web server program - the software
 An HTML file is a text file containing small markup tags & plain text

32 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
33

 The markup tags tell the Web browser how to display the page "HTML tags" and "HTML elements" are often used to describe the same thing.
 An HTML file must have an htm or html file extension<html> But strictly speaking, an HTML element is everything between the start tag and the
end tag, including the tags:
 HTML documents are also called web pages

All HTML document must contain the following elements: HTML Element:
o HTML
o HEAD <p>This is a paragraph.</p>
o BODY
HTML Versions
<html>
<head>
<title> My First Webpage </title>
Since the early days of the web, there have been many versions of HTML:
</head>
Version Year
<body>
This is my first homepage. <b>this text is bold</b> HTML 1991
</body>
</html> HTML+ 1993

HTML 2.0 1995


TO CREATE AN HTML PAGE BY USING THE PRECEDING CODE
1. Open notepad HTML 3.2 1997
2. Enter the preceding code in notepad and save the file as
myfirstpage.html HTML 4.01 1999
3. Open myfirstpage.html in your browser
XHTML 1.0 2000
HTML Tags
HTML markup tags are usually called HTML tags HTML5 2012
 HTML tags are keywords (tag names) surrounded by angle brackets like
<html> XHTML5 2013
 HTML tags normally come in pairs like <b> and </b>
 The first tag in a pair is the start tag, the second tag is the end tag
 The end tag is written like the start tag, with a forward slash before the tag The HTML <head> Element
name The <head> element is a container for all the head elements. Elements inside <head>
 Start and end tags are also called opening tags and closing tags can include scripts, instruct the browser where to find style sheets, provide meta
<tagname>content</tagname> information, and more.
The following tags can be added to the head section: <title>, <style>, <meta>, <link>,
<script>, <noscript>, and <base>.
HTML Elements Sections of an HTML Document

33 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
34

An html document is divided into two main sections – Visited link Sets the colour for links that have been VLINK
the head section and the body section. colour followed
The head section contains information about the document, which is covered in the
page attributes section below. This is usually placed at the top of the html document Active link Sets the colour for links that are active (when ALINK
colour they’re clicked)
(so it can load into the browser first) and won’t be displayed inside your browser
window. Background Specifies what graphic file will be used as the BACKGROUND
The body section contains the content of your document that will be displayed, such as Graphic background
text and images.
Page attributes
There are several different elements that maybe included within the <HEAD>section E.g.
of your document. The most important is the title of your document, which is specified <BODYBGCOLOR="white" TEXT="black" LINK="blue" VLINK="purple"
by the <TITLE> tag. The title tag can be used to identify your site and will also be ALINK="red" BACKGROUND="back.gif">
used to provide the text that will display in your browser’s title bar. </BODY>
e.g. Note: In HTML, US spelling must be used for words like COLOR, CENTER and
<TITLE>Steve’s Home Page</TITLE> the colour GRAY otherwise they won’t be recognised by the web browser.
Would show in the title bar as
It’s a good idea to make the title descriptive as the title bar is often used by search 1 Open your HTML editor or notepad
engines to describe a website. Your title should make it clear what the site is about. You should have a blank document to begin with
Other information is often contained in the header section of the document using Meta 2 Enter the following HTML.
tags. E.g. some search engines use Meta tags to provide a description of a site. If you
wanted to take advantage of this feature you might put a Meta tag such as the one <HTML>
below into your head section. <HEAD>
<METANAME="Description" CONTENT="Type a description of your site here."> <TITLE>my first website </TITLE>
The body section </HEAD>
The content of your page needs to be between the <BODY>and </BODY>tags. It is <BODY BGCOLOR="white" TEXT="black" LINK="blue" VLINK="purple"
important to make sure the content of your page is in the body section since anything ALINK="red" BACKGROUND="back.gif">
before the <BODY>tag and after the </BODY>tag often won’t appear in the web </BODY>
browser. The body tag is an example of a tag that can have attributes. Some of the </HTML>
attributes that can be set for the body tag are:
Attribute Description HTML 3 Save the file as index.html.
Background Sets the background colour for the document BGCOLOR
colour Make sure the file called back.gif has also been saved in that same location.
Text colour Sets the colour for text on the page TEXT 4 Preview your document in your web browser. To do this, you can open your web
browser, go to your file menu and then open the index file you just saved. Many
Hyperlink colour Sets the colour for hyperlink text LINK HTML editors also have a built in preview option.

34 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
35

<img src="url" alt="some_text">


HTML Headings
HTML headings are defined with the <h1> to <h6> tags. Example
Example <img src="e:\new folder\google.jpg" width="104" height="142">

<h1>This is a heading</h1> HTML Images - The Alt Attribute


<h2>This is a heading</h2> The required alt attribute specifies an alternate text for an image, if the image cannot
<h3>This is a heading</h3> be displayed.
Headings Are Important
The value of the alt attribute is an author-defined text:
Use HTML headings for headings only. Don't use headings to make text BIG or bold.
<img src="boat.gif" alt="Big Boat">
Search engines use your headings to index the structure and content of your web pages.
Since users may skim your pages by its headings, it is important to use headings to
show the document structure. The alt attribute provides alternative information for an image if a user for some reason
H1 headings should be used as main headings, followed by H2 headings, then the less cannot view it (because of slow connection, an error in the src attribute, or if the user
important H3 headings, and so on. uses a screen reader).

HTML Paragraphs
HTML Images - Set Height and Width of an Image
HTML paragraphs are defined with the <p> tag.
The height and width attributes are used to specify the height and width of an image.
Example
The attribute values are specified in pixels by default:
<p>This is a paragraph. </p>
<p>This is another paragraph. </p> <img src="pulpit.jpg" alt="Pulpit rock" width="304" height="228">

HTML Links HTML Elements


HTML links are defined with the <a> tag. An HTML element is everything from the start tag to the end tag:
Example
Start tag * Element content End tag *
<a href="http://www.google.com">This is a link</a>
<p> This is a paragraph </p>
HTML Images
<a href="default.htm"> This is a link </a>
HTML Images - The <img> Tag and the Src Attribute
 In HTML, images are defined with the <img> tag. <br>
 The <img> tag is empty, which means that it contains attributes only, and has
* The start tag is often called the opening tag. The end tag is often called the closing
no closing tag.
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 Attributes
Syntax for defining an image: Attributes provide additional information about HTML elements.
35 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
36

<i> Defines a part of text in an alternate voice or mood


 HTML elements can have attributes
 Attributes provide additional information about an element <small> Defines smaller text
 Attributes are always specified in the start tag
 Attributes come in name/value pairs like: name="value" <strong> Defines important text

Attribute Example <sub> Defines subscripted text


HTML links are defined with the <a> tag. The link address is specified in the href
attribute: <sup> Defines superscripted text

Example <ins> Defines inserted text


<a href="http://www.w3schools.com">This is a link</a> <del> Defines deleted text

Tag Description <mark> Defines marked/highlighted text

<html> Defines an HTML document


HTML Links
<body> Defines the document's body Links are found in nearly all Web pages. Links allow users to click their way from
page to page.
<h1> to <h6> Defines HTML headings HTML Hyperlinks (Links)
The HTML <a> tag defines a hyperlink.
<hr> Defines a horizontal line A hyperlink (or link) is a word, group of words, or image that you can click on to jump
to another document.
<!--> Defines a comment 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
HTML Formatting Tags the link’s destination.
By default, links will appear as follows in all browsers:
HTML uses tags like <b> and <i> for formatting output, like bold or italic text.  An unvisited link is underlined and blue
These HTML tags are called formatting tags  A visited link is underlined and purple
 An active link is underlined and red
HTML Text Formatting Tags
HTML Link Syntax
Tag Description The HTML code for a link is simple. It looks like this:
<a href="url">Link text</a>
<b> Defines bold text
The href attribute specifies the destination of a link.
<em> Defines emphasized text Example
<a href="http://www.google.com/">Visit W3Schools</a>

36 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
37

The "Link text" doesn't have to be text. It can be an image or any other HTML The HTML <link> Element
element. The <link> tag defines the relationship between a document and an external resource.
The <link> tag is most used to link to style sheets:
The HTML <head> Element <head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
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 </head>
information, and more.
The following tags can be added to the head section: <title>, <style>, <meta>, <link>, The HTML <style> Element
<script>, <noscript>, and <base>. The <style> tag is used to define style information for an HTML document.
Inside the <style> element you specify how HTML elements should render in a
The HTML <title> Element browser:
The <title> tag defines the title of the document. <head>
The <title> element is required in all HTML/XHTML documents. <style type="text/css">
The <title> element: body {background-color:yellow;}
 defines a title in the browser toolbar p {color:blue;}
 provides a title for the page when it is added to favorites </style>
 displays a title for the page in search-engine results
</head>
A simplified HTML document:
<! DOCTYPE html>
<html> The HTML <meta> Element
<head> Metadata is data (information) about data.
<title>Title of the document</title> The <meta> tag provides metadata about the HTML document. Metadata will not be
displayed on the page, but will be machine-parsable.
</head> Meta elements are typically used to specify page description, keywords, author of the
document, last modified and other metadata.
<body> The metadata can be used by browsers (how to display content or reload page), search
The content of the document...... engines (keywords), or other web services.
</body> <meta> tags always go inside the <head> element.
<meta> Tags - Examples of Use
</html> Define keywords for search engines:
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript">
Define a description of your web page:
The HTML <base> Element
<meta name="description" content="Free Web tutorials on HTML and CSS">
The <base> tag specifies the base URL/target for all relative URLs in a page:
Define the author of a page:
<head>
<meta name="author" content="Hege Refsnes">
<base href="http://www.w3schools.com/images/" target="_blank">
Refresh document every 30 seconds:
</head> <meta http-equiv="refresh" content="30">

37 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
38

The HTML <script> Element How the HTML code above looks in a browser:
The <script> tag is used to define a client-side script, such as a JavaScript. row 1, cell 1 row 1, cell 2
The <script> element will be explained in a later chapter.
row 2, cell 1 row 2, cell 2
HTML head Elements
HTML Tables and the Border Attribute
Tag Description
If you do not specify a border attribute, the table will be displayed without borders.
<head> Defines information about the document Sometimes this can be useful, but most of the time, we want the borders to show.
To display a table with borders, specify the border attribute:
<title> Defines the title of a document <table border="1">
<tr>
<base> Defines a default address or a default target for all links on a page <td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
<link> Defines the relationship between a document and an external resource
</tr>
<meta> Defines metadata about an HTML document </table>

<script> Defines a client-side script

<style> Defines style information for a document HTML Table Headers


Header information in a table are defined with the <th> tag.
All major browsers display the text in the <th> element as bold and centered.
HTML Tables <table border="1">
Tables are defined with the <table> tag. <tr>
A table is divided into rows (with the <tr> tag), and each row is divided into data cells <th>Header 1</th>
(with the <td> tag). td stands for "table data," and holds the content of a data cell. A <th>Header 2</th>
<td> tag can contain text, links, images, lists, forms, other tables, etc. </tr>
Table Example <tr>
<table border="1"> <td>row 1, cell 1</td>
<tr> <td>row 1, cell 2</td>
<td>row 1, cell 1</td> </tr>
<td>row 1, cell 2</td> <tr>
</tr> <td>row 2, cell 1</td>
<tr> <td>row 2, cell 2</td>
<td>row 2, cell 1</td> </tr>
<td>row 2, cell 2</td> </table>
</tr> How the HTML code above looks in your browser:
</table>

38 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
39

Header 1 Header 2 HTML Unordered Lists


An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
row 1, cell 1 row 1, cell 2 The list items are marked with bullets (typically small black circles).
row 2, cell 1 row 2, cell 2 <ul>
<li>Coffee</li>
<li>Milk</li>
HTML Table Tags </ul>
Tag Description How the HTML code above looks in a browser:
 Coffee
<table> Defines a table  Milk

<th> Defines a header cell in a table


HTML Ordered Lists
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
<tr> Defines a row in a table
The list items are marked with numbers.
<td> Defines a cell in a table <ol>
<li>Coffee</li>
<caption> Defines a table caption <li>Milk</li>
</ol>
<colgroup> Specifies a group of one or more columns in a table for formatting How the HTML code above looks in a browser:
1. Coffee
<col> Specifies column properties for each column within a <colgroup> element 2. Milk

<thead> Groups the header content in a table HTML Description Lists


A description list is a list of terms/names, with a description of each term/name.
<tbody> Groups the body content in a table The <dl> tag defines a description list.
The <dl> tag is used in conjunction with <dt> (defines terms/names) and <dd>
<tfoot> Groups the footer content in a table (describes each term/name):
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
HTML Lists <dt>Milk</dt>
The most common HTML lists are ordered and unordered lists: <dd>- white cold drink</dd>
</dl>
The most common HTML lists are ordered and unordered lists:
How the HTML code above looks in a browser:
HTML Lists
Coffee
An ordered list: An unordered list: - black hot drink
1. The first list item  List item Milk
2. The second list item  List item - white cold drink
3. The third list item  List item

39 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
40

HTML List Tags <span> Defines a section in a document (inline)


Tag Description

<ol> Defines an ordered list


HTML Forms
<ul> Defines an unordered list
HTML forms are used to pass data to a server.
An HTML form can contain input elements like text fields, checkboxes, radio-buttons,
<li> Defines a list item
submit buttons and more. A form can also contain select lists, textarea, fieldset, legend,
<dl> Defines a description list and label elements.
The <form> tag is used to create an HTML form:
<dt> Defines a term/name in a description list <form>
.
<dd> Defines a description of a term/name in a description list input elements
.
The HTML <div> Element </form>
The HTML <div> element is a block level element that can be used as a container for
grouping other HTML elements. HTML Forms - The Input Element
The <div> element has no special meaning. Except that, because it is a block level The most important form element is the <input> element.
element, the browser will display a line break before and after it. The <input> element is used to select user information.
When used together with CSS, the <div> element can be used to set style attributes to An <input> element can vary in many ways, depending on the type attribute. An
large blocks of content. <input> element can be of type text field, checkbox, password, radio button, submit
Another common use of the <div> element, is for document layout. It replaces the "old button, and more.
way" of defining layout using tables. Using <table> elements for layout is not the The most common input types are described below.
correct use of <table>. The purpose of the <table> element is to display tabular data.
Text Fields
The HTML <span> Element <input type="text"> defines a one-line input field that a user can enter text into:
The HTML <span> element is an inline element that can be used as a container for <form>
text. First name: <input type="text" name="firstname"><br>
The <span> element has no special meaning.
Last name: <input type="text" name="lastname">
When used together with CSS, the <span> element can be used to set style attributes to
parts of the text. </form>
How the HTML code above looks in a browser:
HTML Grouping Tags First name:
Tag Description Last name:
<div> Defines a section in a document (block-level) Note: The form itself is not visible. Also note that the default width of a text field is 20
characters.

40 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
41

Submit Button
Password Field <input type="submit"> defines a submit button.
<input type="password"> defines a password field: A submit button is used to send form data to a server. The data is sent to the page
<form> specified in the form's action attribute. The file defined in the action attribute usually
does something with the received input:
Password: <input type="password" name="pwd">
<form name="input" action="html_form_action.asp" method="get">
</form>
Username: <input type="text" name="user">
How the HTML code above looks in a browser:
<input type="submit" value="Submit">
***
Password: </form>
Note: The characters in a password field are masked (shown as asterisks or circles). How the HTML code above looks in a browser:
Submit
Radio Buttons Username:
<input type="radio"> defines a radio button. Radio buttons let a user select ONLY If you type some characters in the text field above, and click the "Submit" button, the
ONE of a limited number of choices: browser will send your input to a page called "html_form_action.asp". The page will
<form> show you the received input.
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
HTML Form Tags
New: New tags in HTML5.
</form>
How the HTML code above looks in a browser:
Tag Description
Male
<form> Defines an HTML form for user input
Female
<input> Defines an input control

Checkboxes <textarea> Defines a multiline input control (text area)


<input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or
MORE options of a limited number of choices. <label> Defines a label for an <input> element
<form>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br> <fieldset> Groups related elements in a form
<input type="checkbox" name="vehicle" value="Car">I have a car
<legend> Defines a caption for a <fieldset> element
</form>
How the HTML code above looks in a browser: <select> Defines a drop-down list

I have a bike <optgroup> Defines a group of related options in a drop-down list


I have a car
<option> Defines an option in a drop-down list

41 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
42

<button> Defines a clickable button checkbox Choose one or more options


name= Name of the field.
value= Initial value in the field.
<datalist>New Specifies a list of pre-defined options for input controls
radio Choose only one option
<keygen>New Defines a key-pair generator field (for forms) name= Name of the field.
value= Initial value in the field.
<output>New Defines the result of a calculation select Drop-down menu
name= Name of the field.
size= Number of items in list.
multiple= Allow multiple choice if yes.

option Individual items in the menu.


selected Make an item default.
value= Value to send if selected.
hidden Does not show on the form.
name= Name of the field.
value= Value to send.
reset Button to reset all fields
Form element
name= Name of the button. Reset
HTML EXPLANATION EXAMPLE value= Text shown on the button.
textarea Text area - several lines submit Button to submit the form
rows= Rows in the field. name= Name of the button. Submit
cols= Columns in the field. value= Text shown on the button.
name= Name of the field.

wrap= Control linebreaks.


off Turns off linebreaks. image Image behaving as button
virtual Shows linebreaks, but name= Name of the image.
sends text as entered.
physical Inserts linebreaks when
needed and even sends it.
text One line text field
size= Characters shown. FRAME-
maxlength= Max characters allowed.
name= Name of the field. A frame is a part of a web page or browser window which displays content
value= Initial value in the field. independent of its container, with the ability to load content independently. The HTML
password Password field. or media elements that go in a frame may or may not come from the same web site as
size= Characters shown. the other elements of content on display.
maxlength= Characters allowed to enter.
name= Name of the field. The <frameset> tag is used to store the definitions of the various frames in the file.
value= Initial value in the field. These definitions will typically:
– include the size and location of the frame
42 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
43

– include the Web pages the frames display ---------------------------------------


The <frameset> code does not include an opening and closing <body> tag. If the user agent can't display frames or is configured not to, it will render the
– the reason for this is that this HTML file displays the contents of contents of the NOFRAMES element.
Frame layout
other Web pages; technically, it is not a Web page
– use rows and cols attributes of <frameset>
<HTML>
<HEAD> – Frameset is defined by rows or columns, but not both.
<TITLE>A simple frameset document</TITLE> Must choose to layout frames in either rows or columns.
</HEAD> The Frame Syntax
<FRAMESET cols="20%, 80%"> The syntax for creating a row or column frame layout is:
<FRAMESET rows="100, 200">
– <frameset rows=“row height 1, row height 2, row height 3, . . .”>
<FRAME src="contents_of_frame1.html">
<FRAME src="contents_of_frame2.gif"> • row height is the height of each row
</FRAMESET> or
<FRAME src="contents_of_frame3.html"> – <frameset cols=“column width 1, column width 2, column width
<NOFRAMES> 3, . . .”>
<P>This frameset document contains:
• column width is the width of each column
<UL>
<LI><A href="contents_of_frame1.html">Some neat contents</A> Row and column sizes can be specified in three ways:
<LI><IMG src="contents_of_frame2.gif" alt="A neat image"> – in pixels
<LI><A href="contents_of_frame3.html">Some other neat contents</A> – as a percentage of the total size of the frameset
</UL> – by an asterisk (*)
</NOFRAMES>
</FRAMESET> Specifying a Frame Source
</HTML>
That might create a frame layout something like this: To specify a source for a frame, use the <frame> tag with the syntax: <frame
--------------------------------------- src=“URL”>
| | | – The URL is the filename and location of the page that you want to load.
| | | – You must insert the <frame> tag between the opening and closing
| Frame 1 | |
| | | <frameset> tags.
| | | – In HTML, the <frame> tag has no end tag. In XHTML, the <frame> tag
|---------| | must be properly closed.
| | Frame 3 |
| | | Optional Attributes
| | |
| | | Attribute Value Description
| Frame 2 | |
| | | frameborder 0 Specifies whether or not to display a border around a
| | | 1 frame
| | |
| | |

43 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
44

 External - using an external CSS file


longdesc URL Specifies a page that contains a long description of the
The preferred way to add CSS to HTML, is to put CSS syntax in separate CSS files.
content of a frame
Inline Styles
marginheight pixels Specifies the top and bottom margins of a frame An inline style can be used if a unique style is to be applied to one single occurrence of
an element.
marginwidth pixels Specifies the left and right margins of a frame To use inline styles, use the style attribute in the relevant tag. The style attribute can
contain any CSS property. The example below shows how to change the text color and
name Text Specifies the name of a frame the left margin of a paragraph:
<p style="color:blue;margin-left:20px;">This is a paragraph.</p>
noresize noresize Specifies that a frame is not resizable

scrolling yes Specifies whether or not to display scrollbars in a frame EXAMPLE


no <! DOCTYPE html>
auto <html>

src URL Specifies the URL of the document to show in a frame


<body>
<h1 style="text-align:center;">Center-aligned heading</h1>
Standard Attributes <p>This is a paragraph.</p>
The <frame> tag supports the following standard attributes in HTML 4.01: </body>
Attribute Value Description
</html>
Class classname Specifies a classname for an element Internal Style Sheet
Id Id Specifies a unique id for an element An internal style sheet can be used if one single document has a unique style. Internal
styles are defined in the <head> section of an HTML page, by using the <style> tag,
Style style_definition Specifies an inline style for an element like this:
<head>
title Text Specifies extra information about an element <style type="text/css">
body {background-color:yellow;}
p {color:blue;}
</style>
CSS (Cascading Style Sheets) </head>
CSS (Cascading Style Sheets) is used to style HTML elements.
Styling HTML with CSS
CSS was introduced together with HTML 4, to provide a better way to style HTML
elements. External Style Sheet
CSS can be added to HTML in the following ways: An external style sheet is ideal when the style is applied to many pages. With an
 Inline - using the style attribute in HTML elements external style sheet, you can change the look of an entire Web site by changing one
 Internal - using the <style> element in the <head> section
44 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
45

file. Each page must link to the style sheet using the <link> tag. The <link> tag goes  XML Simplifies Data Transport
inside the <head> section:  XML Simplifies Platform Changes
<head>
 XML Makes Your Data More Available
<link rel="stylesheet" type="text/css" href="mystyle.css">
 XML is Used to Create New Internet Languages
</head>
XML documents form a tree structure that starts at "the root" and branches to
HTML Style Tags "the leaves".
Tag Description
<?xml version="1.0" encoding="ISO-8859-1"?>
<style> Defines style information for a document <note>
<to>Tove</to>
<link> Defines the relationship between a document and an external resource <from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML (EXtensible Markup Language)
 XML stands for EXtensible Markup Language An Example XML Document
 XML is a markup language much like HTML
<?xml version="1.0" encoding="ISO-8859-1"?>
 XML was designed to carry data, not to display data
 XML tags are not predefined. You must define your own tags <note>
 XML is designed to be self-descriptive <to>Tove</to>
 XML was designed to transport and store data. <from>Jani</from>
<heading>Reminder</heading>
The Difference between XML and HTML <body>Don't forget me this weekend!</body>
XML is not a replacement for HTML. </note>
XML and HTML were designed with different goals:
 XML was designed to transport and store data, with focus on what data is The first line is the XML declaration. It defines the XML version (1.0) and the
 HTML was designed to display data, with focus on how data looks encoding used (ISO-8859-1 = Latin-1/West European character set).
HTML is about displaying information, while XML is about carrying information. The next line describes the root element of the document (like saying: "this document
XML and HTML were designed with different goals: is a note"):
 XML was designed to transport and store data, with focus on what data is <note>
 HTML was designed to display data, with focus on how data looks The next 4 lines describe 4 child elements of the root (to, from, heading, and body):
HTML is about displaying information, while XML is about carrying information. <to>Tove</to>
<from>Jani</from>
XML is used in many aspects of web development, often to simplify data <heading>Reminder</heading>
storage and sharing.
<body>Don't forget me this weekend!</body>
 XML Separates Data from HTML
And finally the last line defines the end of the root element:
 XML Simplifies Data Sharing </note>
45 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
46

You can assume, from this example, that the XML document contains a note to Tove <author>Giada De Laurentiis</author>
from Jani. <year>2005</year>
<price>30.00</price>
XML Documents Form a Tree Structure </book>
<book category="CHILDREN">
XML documents must contain a root element. This element is "the parent" of all other <title lang=" english ">Harry Potter</title>
elements. <author>J K. Rowling</author>
The elements in an XML document form a document tree. The tree starts at the root <year>2005</year>
and branches to the lowest level of the tree. <price>29.99</price>
All elements can have sub elements (child elements): </book>
<root> <book category="WEB">
<child> <title lang=" english ">Learning XML</title>
<subchild>.....</subchild> <author>Erik T. Ray</author>
<year>2003</year>
</child> <price>39.95</price>
</root> </book>
The terms parent, child, and sibling are used to describe the relationships between </bookstore>
elements. Parent elements have children. Children on the same level are called siblings The root element in the example is <bookstore>. All <book> elements in the document
(brothers or sisters). are contained within <bookstore>.
All elements can have text content and attributes (just like in HTML). The <book> element has 4 children: <title>,< author>, <year>, <price>.

Example: All XML Elements Must Have a Closing Tag

In HTML, some elements do not have to have a closing tag:


<p>This is a paragraph.

In XML, it is illegal to omit the closing tag. All elements must have a closing tag:
<p>This is a paragraph.</p>

XML Tags are Case Sensitive


XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.
Opening and closing tags must be written with the same case:

<Message>This is incorrect</message>
<message>This is correct</message>
The image above represents one book in the XML below:

<bookstore> Note: "Opening and closing tags" are often referred to as "Start and end tags". Use
<book category="COOKING"> whatever you prefer. It is exactly the same thing.
<title lang="english">Everyday Italian</title> XML Elements Must be Properly Nested

46 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
47

The error in the first document is that the date attribute in the note element is not
In HTML, you might see improperly nested elements: quoted.
<b><i>This text is bold and italic</b></i>
Entity References
In XML, all elements must be properly nested within each other: Some characters have a special meaning in XML.
<b><i>This text is bold and italic</i></b> If you place a character like "<" inside an XML element, it will generate an error
because the parser interprets it as the start of a new element.
In the example above, "Properly nested" simply means that since the <i> element is This will generate an XML error:
opened inside the <b> element, it must be closed inside the <b> element.
<message>if salary < 1000 then</message>

XML Documents Must Have a Root Element To avoid this error, replace the "<" character with an entity reference:
XML documents must contain one element that is the parent of all other elements. <message>if salary &lt; 1000 then</message>
This element is called the rootelement.
There are 5 predefined entity references in XML:
<root> &lt; < less than
<child>
<subchild>.....</subchild> &gt; > greater than
</child>
</root> &amp; & ampersand

&apos; ' apostrophe


XML Attribute Values Must be Quoted
XML elements can have attributes in name/value pairs just like in HTML. &quot; " quotation mark
In XML, the attribute values must always be quoted.
Note: Only the characters "<" and "&" are strictly illegal in XML. The greater than
character is legal, but it is a good habit to replace it.
Study the two XML documents below. The first one is incorrect, the second is correct:

<note date=12/11/2007> Comments in XML


<to>Tove</to> The syntax for writing comments in XML is similar to that of HTML.
<from>Jani</from> <!-- This is a comment -->
</note>
White-space is Preserved in XML
HTML truncates multiple white-space characters to one single white-space:
<note date="12/11/2007">
<to>Tove</to> HTML: Hello Tove
<from>Jani</from>
Output: Hello Tove
</note>
With XML, the white-space in a document is not truncated.

47 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
48

<img src="computer.gif">
What is an XML Element? <a href="demo.asp">
Attributes often provide information that is not a part of the data. In the example
An XML element is everything from (including) the element's start tag to (including) below, the file type is irrelevant to the data, but can be important to the software that
the element's end tag. wants to manipulate the element:
<file type="gif">computer.gif</file>
An element can contain:
 other elements
 text XML Attributes Must be Quoted
 attributes Attribute values must always be quoted. Either single or double quotes can be used.
 or a mix of all of the above... For a person's sex, the person element can be written like this:
 <person sex="female">
<bookstore> or like this:
<book category="CHILDREN"> <person sex='female'>
<title>Harry Potter</title> If the attribute value itself contains double quotes you can use single quotes, like in
<author>J K. Rowling</author> this example:
<year>2005</year> <gangster name='George "Shotgun" Ziegler'>
<price>29.99</price> or you can use character entities:
</book> <gangster name="George &quot;Shotgun&quot; Ziegler">
<book category="WEB">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year> XML Elements vs. Attributes
<price>39.95</price> Take a look at these examples:
</book> <person sex="female">
</bookstore> <firstname>Anna</firstname>
In the example above, <bookstore> and <book> have element contents, because they <lastname>Smith</lastname>
contain other elements. <book> also has an attribute (category="CHILDREN"). </person>
<title>, <author>, <year>, and <price> have text contentbecause they contain text.

XML Naming Rules <person>


XML elements must follow these naming rules: <sex>female</sex>
 Names can contain letters, numbers, and other characters <firstname>Anna</firstname>
 Names cannot start with a number or punctuation character <lastname>Smith</lastname>
 Names cannot start with the letters xml (or XML, or Xml, etc) </person>
 Names cannot contain spaces In the first example sex is an attribute. In the last, sex is an element. Both examples
provide the same information.
XML Attributes
In HTML, attributes provide additional information about elements:
48 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
49

XML with correct syntax is "Well Formed" XML. <!ELEMENT note (to,from,heading,body)>
XML validated against a DTD is "Valid" XML. <!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
Well Formed XML Documents <!ELEMENT heading (#PCDATA)>
A "Well Formed" XML document has correct XML syntax. <!ELEMENT body (#PCDATA)>
The syntax rules were described in the previous chapters: ]>
 XML documents must have a root element
 XML elements must have a closing tag A DTD can be declared inline inside an XML document, or as an
 XML tags are case sensitive
external reference.
 XML elements must be properly nested
 XML attribute values must be quoted

Valid XML Documents Internal DTD Declaration


A "Valid" XML document is a "Well Formed" XML document, which also conforms If the DTD is declared inside the XML file, it should be wrapped in a DOCTYPE
to the rules of a Document Type Definition (DTD): definition with the following syntax:
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE root-element [element-declarations]>
<!DOCTYPE note SYSTEM "Note.dtd"> Example XML document with an internal DTD:
<?xml version="1.0"?>
<note>
<!DOCTYPE note [
<to>Tove</to> <!ELEMENT note (to,from,heading,body)>
<from>Jani</from> <!ELEMENT to (#PCDATA)>
<heading>Reminder</heading> <!ELEMENT from (#PCDATA)>
<body>Don't forget me this weekend!</body> <!ELEMENT heading (#PCDATA)>
</note> <!ELEMENT body (#PCDATA)>
The DOCTYPE declaration, in the example above, is a reference to an external DTD ]>
file. The content of the file is shown in the paragraph below. <note>
<to>Tove</to>
XML DTD <from>Jani</from>
The purpose of a DTD is to define the structure of an XML document. It defines the <heading>Reminder</heading>
structure with a list of legal elements: <body>Don't forget me this weekend</body>
</note>
The purpose of a DTD (Document Type Definition) is to define the legal building
The DTD above is interpreted like this:
blocks of an XML document.  !DOCTYPE note defines that the root element of this document is note
A DTD defines the document structure with a list of legal elements and attributes.  !ELEMENT note defines that the note element contains four elements: "to,
from, heading, body"
<!DOCTYPE note  !ELEMENT to defines the to element to be of type "#PCDATA"
[  !ELEMENT from defines the from element to be of type "#PCDATA"

49 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
50

 !ELEMENT heading defines the heading element to be of type "#PCDATA"  Entities


 !ELEMENT body defines the body element to be of type "#PCDATA"  PCDATA
 CDATA
External DTD Declaration
Elements
If the DTD is declared in an external file, it should be wrapped in a DOCTYPE Elements are the main building blocks of both XML and HTML documents.
definition with the following syntax: Examples of HTML elements are "body" and "table". Examples of XML elements
<!DOCTYPE root-element SYSTEM "filename"> could be "note" and "message". Elements can contain text, other elements, or be
This is the same XML document as above, but with an external DTD (Open it, and empty. Examples of empty HTML elements are "hr", "br" and "img".
select view source): Examples:
<?xml version="1.0"?> <body>some text</body>
<!DOCTYPE note SYSTEM "note.dtd">
<note> <message>some text</message>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading> Attributes
<body>Don't forget me this weekend!</body> Attributes provide extra information about elements.
</note> Attributes are always placed inside the opening tag of an element. Attributes always
And this is the file "note.dtd" which contains the DTD: come in name/value pairs. The following "img" element has additional information
<!ELEMENT note (to,from,heading,body)> about a source file:
<!ELEMENT to (#PCDATA)> <img src="computer.gif" />
The name of the element is "img". The name of the attribute is "src". The value of the
<!ELEMENT from (#PCDATA)>
attribute is "computer.gif". Since the element itself is empty it is closed by a " /".
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)> Entities
Some characters have a special meaning in XML, like the less than sign (<) that
Why Use a DTD? defines the start of an XML tag.
Most of you know the HTML entity: "&nbsp;". This "no-breaking-space" entity is
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 used in HTML to insert an extra space in a document. Entities are expanded when a
document is parsed by an XML parser.
interchanging data.
The following entities are predefined in XML:
Your application can use a standard DTD to verify that the data you receive from the
outside world is valid. Entity References Character
You can also use a DTD to verify your own data.
&lt; <
The Building Blocks of XML Documents
&gt; >
Seen from a DTD point of view, all XML documents (and HTML documents) are
made up by the following building blocks: &amp; &
 Elements
 Attributes &quot; "

50 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
51

XML example:
&apos; '

<br />
PCDATA
PCDATA means parsed character data. Elements with Parsed Character Data
Think of character data as the text found between the start tag and the end tag of an Elements with only parsed character data are declared with #PCDATA inside
XML element. parentheses:
PCDATA is text that WILL be parsed by a parser. The text will be examined by <!ELEMENT element-name (#PCDATA)>
the parser for entities and markup.
Tags inside the text will be treated as markup and entities will be expanded. Example:
However, parsed character data should not contain any &, <, or > characters; these
need to be represented by the &amp; &lt; and &gt; entities, respectively. <!ELEMENT from (#PCDATA)>
CDATA
CDATA means character data. Elements with any Contents
CDATA is text that will NOT be parsed by a parser. Tags inside the text will NOT Elements declared with the category keyword ANY, can contain any combination of
be treated as markup and entities will not be expanded. parsable data:
<!ELEMENT element-name ANY>

In a DTD, elements are declared with an ELEMENT declaration. Example:

Declaring Elements <!ELEMENT note ANY>


In a DTD, attributes are declared with an ATTLIST declaration.
In a DTD, XML elements are declared with an element declaration with the following
syntax:
Declaring Attributes
<!ELEMENT element-name category>
An attribute declaration has the following syntax:
or
<!ATTLIST element-name attribute-name attribute-type attribute-value>
<!ELEMENT element-name (element-content)>
DTD example:
Empty Elements
Empty elements are declared with the category keyword EMPTY:
<!ATTLIST payment type CDATA "check">
<!ELEMENT element-name EMPTY>

XML example:
Example:

<payment type="check" />


<!ELEMENT br EMPTY>
The attribute-type can be one of the following:

51 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
52

Type Description
Valid XML:
CDATA The value is character data <square width="100" />
In the example above, the "square" element is defined to be an empty element with a
(en1|en2|..) The value must be one from an enumerated list
"width" attribute of type CDATA. If no width is specified, it has a default value of 0.
ID The value is a unique id
#REQUIRED
IDREF The value is the id of another element Syntax
<!ATTLIST element-name attribute-name attribute-type #REQUIRED>
IDREFS The value is a list of other ids
Example
NMTOKEN The value is a valid XML name DTD:
<!ATTLIST person number CDATA #REQUIRED>
NMTOKENS The value is a list of valid XML names
Valid XML:
ENTITY The value is an entity
<person number="5677" />
ENTITIES The value is a list of entities
Invalid XML:
NOTATION The value is a name of a notation <person />
Use the #REQUIRED keyword if you don't have an option for a default value, but still
xml: The value is a predefined xml value want to force the attribute to be present.
The attribute-value can be one of the following:
Value Explanation #IMPLIED
Syntax
Value The default value of the attribute
<!ATTLIST element-name attribute-name attribute-type #IMPLIED>
#REQUIRED The attribute is required Example
DTD:
#IMPLIED The attribute is not required <!ATTLIST contact fax CDATA #IMPLIED>

#FIXED value The attribute value is fixed


Valid XML:
<contact fax="555-667788" />

A Default Attribute Value Valid XML:


DTD: <contact />
<!ELEMENT square EMPTY> Use the #IMPLIED keyword if you don't want to force the author to include an
<!ATTLIST square width CDATA "0"> attribute, and you don't have an option for a default value.

52 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
53

In XML, element names are defined by the developer. This often results in a conflict
#FIXED when trying to mix XML documents from different XML applications.
This XML carries HTML table information:
Syntax <table>
<!ATTLIST element-name attribute-name attribute-type #FIXED "value"> <tr>
Example <td>Apples</td>
DTD: <td>Bananas</td>
<!ATTLIST sender company CDATA #FIXED "Microsoft"> </tr>
</table>
Valid XML: This XML carries information about a table (a piece of furniture):
<sender company="Microsoft" /> <table>
<name>African Coffee Table</name>
Invalid XML: <width>80</width>
<sender company="W3Schools" /> <length>120</length>
Use the #FIXED keyword when you want an attribute to have a fixed value without </table>
allowing the author to change it. If an author includes another value, the XML parser If these XML fragments were added together, there would be a name conflict. Both
will return an error. contain a <table> element, but the elements have different content and meaning.
An XML parser will not know how to handle these differences.
Enumerated Attribute Values
Syntax Solving the Name Conflict Using a Prefix
<!ATTLIST element-name attribute-name (en1|en2|..) default-value> Name conflicts in XML can easily be avoided using a name prefix.
Example This XML carries information about an HTML table, and a piece of furniture:
DTD: <h:table>
<!ATTLIST payment type (check|cash) "cash"> <h:tr>
<h:td>Apples</h:td>
XML example: <h:td>Bananas</h:td>
<payment type="check" /> </h:tr>
or </h:table>
<payment type="cash" />
Use enumerated attribute values when you want the attribute value to be one of a fixed <f:table>
set of legal values. <f:name>African Coffee Table</f:name>
<f:width>80</f:width>
XML Namespaces provide a method to avoid element name conflicts. <f:length>120</f:length>
</f:table>
Name Conflicts In the example above, there will be no conflict because the two <table> elements have
different names.

53 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
54

XML Namespaces - The xmlns Attribute <f:table>


When using prefixes in XML, a so-called namespace for the prefix must be defined. <f:name>African Coffee Table</f:name>
The namespace is defined by the xmlns attribute in the start tag of an element. <f:width>80</f:width>
The namespace declaration has the following syntax. xmlns:prefix="URI". <f:length>120</f:length>
<root> </f:table>

<h:table xmlns:h="http://www.w3.org/TR/html4/"> </root>


<h:tr> Note: The namespace URI is not used by the parser to look up information.
<h:td>Apples</h:td> The purpose is to give the namespace a unique name. However, often companies use
<h:td>Bananas</h:td> the namespace as a pointer to a web page containing namespace information.
</h:tr>
</h:table> Uniform Resource Identifier (URI)
A Uniform Resource Identifier (URI) is a string of characters which identifies an
<f:table xmlns:f="http://www.w3schools.com/furniture"> Internet Resource.
<f:name>African Coffee Table</f:name> The most common URI is the Uniform Resource Locator (URL) which identifies an
<f:width>80</f:width> Internet domain address. Another, not so common type of URI is the Universal
<f:length>120</f:length> Resource Name (URN).
In our examples we will only use URLs.
</f:table>
Default Namespaces
</root>
Defining a default namespace for an element saves us from using prefixes in all the
In the example above, the xmlns attribute in the <table> tag give the h: and f: prefixes
child elements. It has the following syntax:
a qualified namespace.
xmlns="namespaceURI"
When a namespace is defined for an element, all child elements with the same prefix
are associated with the same namespace. This XML carries HTML table information:
Namespaces can be declared in the elements where they are used or in the XML root <table xmlns="http://www.w3.org/TR/html4/">
element: <tr>
<root xmlns:h="http://www.w3.org/TR/html4/" <td>Apples</td>
xmlns:f="http://www.w3schools.com/furniture"> <td>Bananas</td>
</tr>
<h:table> </table>
<h:tr> This XML carries information about a piece of furniture:
<h:td>Apples</h:td> <table xmlns="http://www.w3schools.com/furniture">
<h:td>Bananas</h:td> <name>African Coffee Table</name>
</h:tr> <width>80</width>
</h:table>

54 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
55

<length>120</length>  It is easier to define data facets (restrictions on data)


</table>  It is easier to define data patterns (data formats)
 It is easier to convert data between different data types

XML Schema XML Schemas use XML Syntax


XML Schema is an XML-based alternative to DTD. Another great strength about XML Schemas is that they are written in XML.
An XML schema describes the structure of an XML document. Some benefits of that XML Schemas are written in XML:
 You don't have to learn a new language
The XML Schema language is also referred to as XML Schema Definition (XSD).
 You can use your XML editor to edit your Schema files
What is an XML Schema?
 You can use your XML parser to parse your Schema files
The purpose of an XML Schema is to define the legal building blocks of an XML
document, just like a DTD.  You can manipulate your Schema with the XML DOM
An XML Schema:  You can transform your Schema with XSLT
 defines elements that can appear in a document
 defines attributes that can appear in a document A Simple XML Document
 defines which elements are child elements Look at this simple XML document called "note.xml":
 defines the order of child elements
 defines the number of child elements <?xml version="1.0"?>
 defines whether an element is empty or can include text <note>
 defines data types for elements and attributes <to>Tove</to>
 defines default and fixed values for elements and attributes <from>Jani</from>
<heading>Reminder</heading>
XML Schemas are the Successors of DTDs <body>Don't forget me this weekend!</body>
We think that very soon XML Schemas will be used in most Web applications as a </note>
replacement for DTDs. Here are some reasons:

 XML Schemas are extensible to future additions An XML Schema


 XML Schemas are richer and more powerful than DTDs The following example is an XML Schema file called "note.xsd" that defines the
 XML Schemas are written in XML elements of the XML document above ("note.xml"):
 XML Schemas support data types
 XML Schemas support namespaces <?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
XML Schemas are much more powerful than DTDs.
xmlns="http://www.w3schools.com"
XML Schemas Support Data Types elementFormDefault="qualified">
One of the greatest strength of XML Schemas is the support for data types.
With support for data types: <xs:element name="note">
 It is easier to describe allowable document content <xs:complexType>
 It is easier to validate the correctness of data <xs:sequence>
 It is easier to work with data from a database <xs:element name="to" type="xs:string"/>

55 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
56

<xs:element name="from" type="xs:string"/> The syntax for defining a simple element is:
<xs:element name="heading" type="xs:string"/> <xs:element name="xxx" type="yyy"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence> What is an Attribute?
</xs:complexType> Simple elements cannot have attributes. If an element has attributes, it is considered to
</xs:element> be of a complex type. But the attribute itself is always declared as a simple type.

</xs:schema> How to Define an Attribute?


The syntax for defining an attribute is:
The note element is a complex type because it contains other elements. The other
<xs:attribute name="xxx" type="yyy"/>
elements (to, from, heading, body) are simple types because they do not contain other
elements.
What is a Complex Element?
The <schema> Element A complex element is an XML element that contains other elements and/or attributes.
There are four kinds of complex elements:
The <schema> element is the root element of every XML Schema:
<?xml version="1.0"?>  empty elements
 elements that contain only other elements
 elements that contain only text
<xs:schema>
 elements that contain both other elements and text
...
Note: Each of these elements may contain attributes as well!
...
</xs:schema>
Examples of Complex Elements
The <schema> element may contain some attributes. A schema declaration A complex XML element, "product", which is empty:
often looks something like this: <product pid="1345"/>
<?xml version="1.0"?>
A complex XML element, "employee", which contains only other elements:
<employee>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" <firstname>John</firstname>
targetNamespace="http://www.w3schools.com" <lastname>Smith</lastname>
xmlns="http://www.w3schools.com" </employee>
elementFormDefault="qualified">
... XSD Empty Elements
... Complex Empty Elements
</xs:schema>

An empty XML element:


What is a Simple Element? <product prodid="1345" />
A simple element is an XML element that can contain only text. It cannot contain any
other elements or attributes.
The <any> Element

Defining a Simple Element


56 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
57

The <any> element enables us to extend the XML document with elements not XPath is a language for navigating in XML documents.
specified by the schema.
What is XSLT?
<xs:any minOccurs="0"/>
 XSLT stands for XSL Transformations
The <anyAttribute> Element  XSLT is the most important part of XSL
 XSLT transforms an XML document into another XML document
The <anyAttribute> element enables us to extend the XML document with attributes
 XSLT uses XPath to navigate in XML documents
not specified by the schema.
<xs:anyAttribute/>  XSLT is a W3C Recommendation

XSLT = XSL Transformations


String Data Type XSLT is the most important part of XSL.
The string data type can contain characters, line feeds, carriage returns, and tab XSLT is used to transform an XML document into another XML document, or another
characters. type of document that is recognized by a browser, like HTML and XHTML. Normally
XSLT does this by transforming each XML element into an (X)HTML element.
The following is an example of a string declaration in a schema:
<xs:element name="customer" type="xs:string"/> XSLT Uses XPath
XSLT uses XPath to find information in an XML document. XPath is used to navigate
An element in your document might look like this:
through elements and attributes in XML documents.
<customer>John Smith</customer>
In the transformation process, XSLT uses XPath to define parts of the source
An element in your document might look like this: document that should match one or more predefined templates. When a match is
XSL Languages found, XSLT will transform the matching part of the source document into the result
document.
XSL stands for EXtensible Style sheet Language. It is used to refer to a family of
languages used to transform and render XML documents.
CSS = Style Sheets for HTML XLink and XPointer
HTML uses predefined tags, and the meaning of each tag is well understood. XLink defines a standard way of creating hyperlinks in XML documents.
XPointer allows the hyperlinks to point to more specific parts in the XML document.
XSL = Style Sheets for XML
XML does not use predefined tags (we can use any tag-names we like), and therefore What is XLink?
the meaning of each tag is not well understood.

XSL consists of three parts:


 XSLT - a language for transforming XML documents
 XPath - a language for navigating in XML documents
 XSL-FO - a language for formatting XML documents
XSLT is a language for transforming XML documents into XHTML documents or
to other XML documents.

57 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
58

 XLink is short for XML Linking Language The target XML document is called "dogbreeds.xml" and it lists a few different dog
 XLink is used to create hyperlinks in XML breeds:
documents The Linking XML Document
 Any element in an XML document can behave Instead of linking to the entire document (as with XLink), XPointer allows you to link
as a link to specific parts of the document.
 XLink supports simple links (like HTML) and To link to a specific part of a page, add a number sign (#) and an XPointer expression
extended links (for linking multiple resources after the URL in the xlink:href attributes.
together)
 With XLink, the links can be defined outside the The expression: #xpointer(id("Rottweiler")) refers to the element in the target
linked files document, with the id value of "Rottweiler".

So the xlink:href attribute would look like this:


The XML Example Document xlink:href=http://dog.com/dogbreeds.xml#xpointer(id('Rottweiler'))
Look at the following XML document, "bookstore.xml", that represents a few books:
However, XPointer allows a shorthand form when linking to an element with an id.
<?xml version="1.0" encoding="ISO-8859-1"?> You can use the value of the id directly, like this:
xlink:href=http://dog.com/dogbreeds.xml#Rottweiler
<bookstore>
The following XML document refers to information of the dog breed for each of my
dogs :-), all through XLink and XPointer references:
<book title="Harry Potter">
<?xml version="1.0" encoding="ISO-8859-1"?>
<description
xlink:type="simple"
<mydogs xmlns:xlink="http://www.w3.org/1999/xlink">
xlink:href="http://book.com/images/HPotter.gif"
xlink:show="new"> <mydog xlink:type="simple"
this is the description
xlink:href="http://dog.com/dogbreeds.xml#Rottweiler">
</description>
<description xlink:type="simple"
</book>
xlink:href="http://myweb.com/mydogs/anton.gif">
</bookstore>
Anton is my favorite dog. He has won a lot of.....
</description>
What is XPointer? </mydog>
 XPointer is short for XML Pointer Language
 XPointer allows the links to point to specific parts of an XML document <mydog xlink:type="simple"
 XPointer uses XPath expressions to navigate in the XML document xlink:href="http://dog.com/dogbreeds.xml#FCRetriever">
To link to a specific part of a page, add a number sign (#) and an XPointer <description xlink:type="simple"
expression after the URL in the xlink:href attributes. xlink:href="http://myweb.com/mydogs/pluto.gif">
The Target XML Document Pluto is the sweetest dog on earth......
</description>

58 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
59

</mydog> <?xml version="1.0" encoding="ISO-8859-1"?>

</mydogs> <bookstore>
<book>
XPATH <title lang="en">Harry Potter</title>
XPath is a language for finding information in an XML document. The XPath <author>J K. Rowling</author>
language is based on a tree representation of the XML document, and provides the <year>2005</year>
ability to navigate around the tree, selecting nodes by a variety of criteria. <price>29.99</price>
</book>
 XPath is a syntax for defining parts of an XML document </bookstore>
 XPath uses path expressions to navigate in XML documents
 XPath contains a library of standard functions Example of nodes in the XML document above:
 XPath is a major element in XSLT <bookstore> (root element node)

XPath Path Expressions <author>J K. Rowling</author> (element node)


XPath uses path expressions to select nodes or node-sets in an XML document. These
path expressions look very much like the expressions you see when you work with a
lang="en" (attribute node)
traditional computer file system.

XPath Standard Functions


XPath includes over 100 built-in functions. There are functions for string values,
numeric values, date and time comparison, node and QName manipulation, sequence
manipulation, Boolean values, and more.

XPath is Used in XSLT


XPath is a major element in the XSLT standard. Without XPath knowledge you will
not be able to create XSLT documents.
XQuery and XPointer are both built on XPath expressions. XQuery 1.0 and XPath 2.0
share the same data model and support the same functions and operators

Nodes
In XPath, there are seven kinds of nodes: element, attribute, text, namespace,
processing-instruction, comment, and document nodes.
XML documents are treated as trees of nodes. The topmost element of the tree is called
the root element.
Look at the following XML document:

59 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
operator Path Expression Result 60
Nodename bookstore Selects all nodes with the name "bookstore"

Atomic values / /bookstore Selects the root element bookstore


Atomic values are nodes with no children or parent.
Example of atomic values: Note: If the path starts with a slash ( / ) it always
J K. Rowling represents an absolute path to an element!

/ bookstore/book Selects all book elements that are children of bookstore


"en"
Items // //book Selects all book elements no matter where they are in
Items are atomic values or nodes. the document

Relationship of Nodes bookstore//book Selects all book elements that are descendant of the
bookstore element, no matter where they are under the
<book> bookstore element
<title>Harry Potter</title>
<author>J K. Rowling</author> @ //@lang Selects all attributes that are named lang
<year>2005</year>
<price>29.99</price> . Selects the current node
</book>
.. Selects the parent of the current node
Parent
In the above example; descendants of the bookstore element are the book, title, author,
Each element and attribute has one parent.
year, and price elements.
In the above example; the book element is the parent of the title, author, year, and
price.
XPath uses path expressions to select nodes or node-sets in an XML document. The
Children
node is selected by following a path or steps.
Element nodes may have zero, one or more children.
In the above example; the title, author, year, and price elements are all children of the
book element.
XML Parser
 It is a software library (or a package) that provides methods (or interfaces) for client
Siblings
applications to work with XML documents
Nodes that have the same parent.  It checks the well-formed-ness
In the above example; the title, author, year, and price elements are all siblings.  It may validate the documents
Ancestors  It does a lot of other detailed things so that a client is shielded from that complexity.
A node's parent, parent's parent, etc.
In the above example; the ancestors of the title element are the book element and the
bookstore element.
Descendants
A node's children, children's children, etc.

60 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
61

<catalog>
<bike>
<24-inch></24-inch>
<bike>
<26-inch></26-inch>
</bike>
</bike>
This is not well-formed XML. It lacks a declaration statement and proper nesting. The
An XML Parser is a parser that is designed to read XML and create a way for declaration statement is how the browser knows that you are creating code in the XML
programs to use XML. There are different types, and each has its advantages. language. This sample does have a root element and closing tags, however, the closing
The main types of parsers are known by some funny names: SAX, DOM and pull. For tags for <bike> are improperly nested. One element does not close before beginning
each type, there are some excellent implementations freely available for a variety of the next one. The root element is missing a closing tag.
languages, including Java, C++, C#, VB# (in fact, any .Net language), PHP, Perl, <?xml version= "1.0"?>
Python, Ruby and so on.
<catalog>
An XML parser is a tool to validate your code to ensure it is well-formed. Even
<bike>
through XML is simplistic; it does need to have proper syntax and form. A parser
<24-inch></24-inch>
looks at your code and highlights lines that may cause problems. XML parsers are
</bike>
available in two flavours, non-validating and validating. It is important to know the
<bike>
difference between these two styles before selecting a parser.
<26-inch></26-inch>
Non-Validating Parser </bike>
A non-validating parser only checks for structure problems with the XML code. This </catalog>
tool will suffice when there is no document type definition (DTD) or schema. The non- If you ran the first sample through a parser, you would be alerted to the syntax
validating parser does not compare validation rules you create to the XML code. It problems with the code.
does not care about data types or any unique processing instructions. Non-validating
parsers only look at the established syntax rules for XML.
Application of XML
Validating Parser
Validating XML parsers looks for validation rules you establish in a DTD or schema. XML has a variety of uses for Web, e-business, and portable applications.
A validating parser does everything a non-validating tool does, but also looks for
internal or external instructions to verify that the code matches unique validation rules The following are some of the many applications for which XML is useful:
you design.  Web publishing: XML allows you to create interactive pages, allows the
customer to customize those pages, and makes creating e-commerce applications
What is Well-formed? more intuitive. With XML, you store the data once and then render that content
Well-formed means you dotted all your i’s and crossed all your t’s when writing the for different viewers or devices based on style sheet processing using an
XML document. Valid XML requires a declaration statement, root element and closing Extensible Style Language (XSL)/XSL Transformation (XSLT) processor.
tags. The elements must be nested correctly.
Poorly Formed XML

61 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
62

 Web searching and automating Web tasks: XML defines the type of
Steps to JavaScript writing:
information contained in a document, making it easier to return useful results
It can be written implicitly or explicitly:
when searching the Web:

 General applications: XML provides a standard method to access information, Implicitly


making it easier for applications and devices of all kinds to use, store, transmit, Means that it can be written in one of two places in the web page:
and display data.
o In Head Section: which will be loaded before the rest of the document and if it's
 e-business applications: XML implementations make electronic data
written in a function it will be loaded upon request.
interchange (EDI) more accessible for information interchange, business-to- o In Body section: which will be loaded in it's turn on the page.
business transactions, and business-to-consumer transactions.

 Metadata applications: XML makes it easier to express metadata in a portable, You can write any number of scripts inside the page, code is written between <script>
reusable format. tags as follow:

 Pervasive computing: XML provides portable and structured information types Listing 1: Where write Javascript code
for display on pervasive (wireless) computing devices such as personal digital 1<script type=”text/javascript”>
assistants (PDAs), cellular phones, and others. For example, WML (Wireless 2 // code goes here
Markup Language) and VoiceXML. 3 </script>
UNIT-4
Explicitly
JAVASCRIPT: JavaScript is an easy-to-use programming language that can be Means, that code will be written in separate file and linked to the desired page.
embedded in the header of your web pages. It can enhance the dynamics and Code is written in separate file with .js extension and is included in the head of the
interactive features of your page by allowing you to perform calculations, check forms, web page as follow:
write interactive games, add special effects, customize graphics selections, and create
security passwords and more. Listing 2: Linking an separate javascript file
JavaScript is a scripting language which aims to make web pages more interactive and 1 <script src=”myfile.js”/>
dynamic.
It allows creating applications that run over the web and it's free “no need to buy a JavaScript variables
license, so it's open standards”, also it can act as Object-Oriented Language. As other languages, data needs to be stored in some holder for different manipulation
operations, so variables are needed to maintain that.
The following is some reasons why JavaScript is used: Variable declaration:
o Can dynamically generate HTML elements in runtime
Variable can be declared in one of two ways:
o Can read and change contents of HTML elements o By direct value assignment. Ex: sum=10 ; val=”Hello Javascript”;
o Can Handle Events o Using the keyword var. Ex: var sum=10.
o Is used for Client side validation
If you didn't assigned a value to a variable and tried to use it, it will produce a value
o Can detect visitor browser and settings
undefined which is considered to be an error in case of variables declared without
o Can create cookies
keyword var which will be runtime error and undefined value or NaN in other case.
o Can directly access files on the web server
o Can directly access files on the user's system

62 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
63

Using semicolons also makes it possible to write many statements on one line.
Variables Scope:
Like in other programming languages, variables have scopes “local and global”. JavaScript Code
Global scope is declared out of any {} in <script> tag and can be seen anywhere inside JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
the tag, in other hand local scope, it's just seen inside its local. Each statement is executed by the browser in the sequence they are written.
Listing 3: Working with variables JavaScript Code Blocks
<script>
 JavaScript statements can be grouped together in blocks.
var sum=10 //Global Variable
 Blocks start with a left curly bracket, and end with a right curly bracket.
function getSum()
{
The purpose of a block is to make the sequence of statements execute together.
var x=sum //Local variable
}
A good example of statements grouped together in blocks, are JavaScript functions.
sum=x //Wrong assignment cause x is local Variable
This example will run a function that will manipulate two HTML elements:
</script>
Example
Variable Types: function myFunction()
Three main types: {
o Primitive data types: document.getElementById("demo").innerHTML="Hello Dolly";
o Numbers : integers or float (Ex: var x=1 , var z=2.3) document.getElementById("myDIV").innerHTML="How are you?";
o Booleans : true or false(Ex: var flag=true) }
o Strings : (Ex: var val=”hello world”)
o Reference data types: JavaScript is Case Sensitive
o Objects : myObj=new Object();
o Arrays : var myArray=new Array(2); JavaScript is case sensitive.
o Special data types: Watch your capitalization closely when you write JavaScript statements:
o null : no value A function getElementById is not the same as getElementbyID.
o undefined : known before A variable named myVariable is not the same as MyVariable.

White Space
JavaScript Statements JavaScript ignores extra spaces. You can add white space to your script to make it
JavaScript is a sequence of statements to be executed by the browser. more readable. The following lines are equivalent:
JavaScript statements are "commands" to the browser. var person="Hege";
The purpose of the statements is to tell the browser what to do. var person = "Hege";
This JavaScript statement tells the browser to write "Hello Dolly" inside an HTML
element with id="demo":
document.getElementById ("demo").innerHTML="Hello Dolly"; Break up a Code Line
You can break up a code line within a text string with a backslash. The example
Semicolon ;
below will be displayed properly:
Semicolon separates JavaScript statements.
Normally you add a semicolon at the end of each executable statement.

63 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
64

document.write ("Hello \ An operator may have one or two operands. An operand is one of the inputs
World!"); (arguments) of an operator. Those operators that work with only one operand are
called unary operators. Those who work with two operands are called binary
However, you cannot break up a code line like this: operators.
document.write \ JavaScript has the following types of operators. This section describes the operators
and contains information about operator precedence.
("Hello World!");
 Assignment operators
Expressions  Comparison operators
 Arithmetic operators
An expression is any valid unit of code that resolves to a value.  Bitwise operators
Conceptually, there are two types of expressions: those that assign a value to a variable  Logical operators
 String operators
and those that simply have a value.
 Special operators
The expression x = 7 is an example of the first type. JavaScript has both binary and unary operators, and one special ternary operator, the
conditional operator. A binary operator requires two operands, one before the operator
This expression uses the = operator to assign the value seven to the variable x. The
and one after the operator:
expression itself evaluates to seven.
operand1 operator operand2
The code 3 + 4 is an example of the second expression type. This expression uses the +
operator to add three and four together without assigning the result, seven, to a For example, 3+4 or x*y.
variable. A unary operator requires a single operand, either before or after the operator:

JavaScript has the following expression categories: operator operand


 Arithmetic: evaluates to a number, for example 3.14159. (Generally
or
uses arithmetic operators.)
operand operator
 String: evaluates to a character string, for example, "Fred" or "234". (Generally
uses string operators.)
For example, x++ or ++x.
 Logical: evaluates to true or false. (Often involves logical operators.)
Assignment operators
 Object: evaluates to an object. An assignment operator assigns a value to its left operand based on the value of its
right operand. The basic assignment operator is equal (=), which assigns the value of
OPERATOR its right operand to its left operand. That is, x = y assigns the value of y to x.
An operator is a special symbol which indicates a certain process is carried out. Assign values to variables and add them together:
y=5;
Operators in programming languages are taken from mathematics. Programmers work
z=2;
with data. The operators are used to process data.
x=y+z;
The result of x will be: 7
64 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
65

< less than x<8 true


JavaScript Assignment Operators
Assignment operators are used to assign values to JavaScript variables. >= greater than or equal to x>=8 false
Given that x=10 and y=5, the table below explains the assignment operators:
Operator Example Same As Result <= less than or equal to x<=8 true

= x=y x=5 Arithmetic Operators


+= x+=y x=x+y x=15 Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
-= x-=y x=x-y x=5 Operator Description Example Result of x Result of y

*= x*=y x=x*y x=50 + Addition x=y+2 7 5

/= x/=y x=x/y x=2 - Subtraction x=y-2 3 5

%= x%=y x=x%y x=0 * Multiplication x=y*2 10 5

Comparison Operators / Division x=y/2 2.5 5


Comparison operators are used in logical statements to determine equality or
difference between variables or values. % Modulus (division remainder) x=y%2 1 5
Given that x=5, the table below explains the comparison operators:
++ Increment x=++y 6 6
Operator Description Comparing Returns
x=y++ 5 6
== equal to x==8 false
-- Decrement x=--y 4 4
x==5 true
x=y-- 5 4
=== exactly equal to (equal value and equal type) x==="5" false
Logical Operators
x===5 true
Logical operators are used to determine the logic between variables or values.
!= not equal x!=8 true Given that x=6 and y=3, the table below explains the logical operators:
Operator Description Example
!== not equal (different value or different type) x!=="5" true
&& And (x < 10 && y > 1) is true
x!==5 false
|| Or (x==5 || y==5) is false
> greater than x>8 false
! Not !(x==y) is true

65 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
66

The shorthand assignment operator += can also be used to concatenate strings. For
example, if the variable mystring has the value "alpha", then the expressionmystring
Bitwise operators += "bet" evaluates to "alphabet" and assigns this value to mystring.
Bitwise operators treat their operands as a set of 32 bits (zeros and ones), rather than as
decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a
Special operators
binary representation of 1001. Bitwise operators perform their operations on such
JavaScript provides the following special operators:
binary representations, but they return standard JavaScript numerical values.
 Conditional operator
The following table summarizes JavaScript's bitwise operators.
 Comma operator

Operator Usage Description  New operator

Bitwise AND a&b Returns a one in each bit position for which the
corresponding bits of both operands are ones. Conditional operator
The conditional operator is the only JavaScript operator that takes three operands. The
Bitwise OR a|b Returns a one in each bit position for which the operator can have one of two values based on a condition. The syntax is:
corresponding bits of either or both operands are ones.

Bitwise XOR a^b Returns a one in each bit position for which the condition ? val1 : val2
corresponding bits of either but not both operands are ones.
If condition is true, the operator has the value of val1. Otherwise it has the value
Bitwise NOT ~a Inverts the bits of its operand. of val2. You can use the conditional operator anywhere you would use a standard
operator.
Left shift a << b Shifts a in binary representation b bits to the left, shifting For example,
in zeros from the right.

Sign-propagating a >> b Shifts a in binary representation b bits to the right, var status = (age >= 18) ? "adult" : "minor";
right shift discarding bits shifted off.
This statement assigns the value "adult" to the variable status if age is eighteen or
Zero-fill right a >>> Shifts a in binary representation b bits to the right, more. Otherwise, it assigns the value "minor" to status.
shift b discarding bits shifted off, and shifting in zeros from the Comma operator
left. The comma operator (,) simply evaluates both of its operands and returns the value of
the second operand. This operator is primarily used inside a for loop, to allow multiple
String operators variables to be updated each time through the loop.
In addition to the comparison operators, which can be used on string values, the For example, if 2-dimensional array with 10 elements on a side, the following code
concatenation operator (+) concatenates two string values together, returning another uses the comma operator to increment two variables at once. The code prints the values
string that is the union of the two operand strings. For example, "my " + of the diagonal elements in the array:
"string" returns the string "my string".

66 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
67

</html>
for (var i = 0, j = 9; i <= 9; i++, j--)

document.writeln("a[" + i + "][" + j + "]= " + a[i][j]);

New
You can use the new operator to create an instance of a user-defined object type or of
one of the predefined object types Array, Boolean, Date, Function, Image, Number,
Object, Option, and String. On the server, you can also use it with DB Pool, Lock, File, Confirm Box
or Send Mail. Use new as follows: 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.
var objectName = new objectType([param1, param2, ..., paramN]); If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns
false.
Syntax
JavaScript Popup Boxes window.confirm("sometext");

JavaScript has three kinds of popup boxes: Alert box, Confirm box, and Prompt box. The window.confirm() method can be written without the window prefix.
Alert Box Example
An alert box is often used if you want to make sure information comes through to the
user. <html>
When an alert box pops up, the user will have to click "OK" to proceed. <body>
Syntax <script type="text/javascript">
var x;
window.alert("sometext");
var r=confirm("are you sure you want to delete the internet?");
The window.alert method can be written without the window prefix.
if (r==true)
{
Example x="You pressed OK!";
<html> }
<body> else
<h1 alertbox example</h1> {
<script type="text/javascript"> x="You pressed Cancel!";
alert("Hey, remember to tell your friends about quackit.com!"); }
document.write(x);
</script>
</script>
</body> </body>

67 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
68

</html> document.write(x);
</script>
</body>
</html>

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. Conditional Statements
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the Conditional statements are used to perform different actions based on different
box returns null. conditions.
Syntax Very often when you write code, you want to perform different actions for different
decisions. You can use conditional statements in your code to do this.
window.prompt("sometext","defaultvalue"); In JavaScript we have the following conditional statements:
 if statement - use this statement to execute some code only if a specified
The window.prompt() method can be written without the window prefix. condition is true
 if...else statement - use this statement to execute some code if the condition is
Example true and another code if the condition is false
 if...else if....else statement - use this statement to select one of many blocks of
<html> code to be executed
<body>  switch statement - use this statement to select one of many blocks of code to
<script type="text/javascript"> be executed
var x; If Statement
var person=prompt("Please enter your favourite website”, “quackit.com"); Use the if statement to execute some code only if a specified condition is true.
if (person!=null) Syntax
{ if (condition)
x="Hello” + person + "! How are you today?"; {
} code to be executed if condition is true
Else }
{ Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a
x="you press the cancel button"; JavaScript error!
} Example

68 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
69

Make a "Good day" greeting if the time is less than 20:00: code to be executed if condition1 is true
if (time<20) }
{ else if (condition2)
x="Good day"; {
} code to be executed if condition2 is true
The result of x will be: }
Good day else
If...else Statement {
Use the if....else statement to execute some code if a condition is true and another code code to be executed if neither condition1 nor condition2 is true
if the condition is not true. }
Syntax
if (condition)
{
JavaScript Switch Statement
code to be executed if condition is true The switch statement is used to perform different action based on different conditions.
Use the switch statement to select one of many blocks of code to be executed.
}
else Syntax
{ switch(n)
code to be executed if condition is not true {
} case 1:
Example execute code block 1
If the time is less than 20:00, you will get a "Good day" greeting, otherwise you will break;
get a "Good evening" greeting case 2:
if (time<20) execute code block 2
{ break;
x="Good day"; default:
} code to be executed if n is different from case 1 and 2
else }
{ This is how it works: First we have a single expression n (most often a variable), that is
x="Good evening"; evaluated once. The value of the expression is then compared with the values for each
} case in the structure. If there is a match, the block of code associated with that case is
The result of x will be: executed. Use break to prevent the code from running into the next case automatically.
Good day Example
Display today's weekday-name. Note that Sunday=0, Monday=1, Tuesday=2, etc:
If...else if...else Statement var day=new Date().getDay();
Use the if....else if...else statement to select one of several blocks of code to be switch (day)
executed. {
case 0:
Syntax
x="Today it's Sunday";
if (condition1)
break;
{
case 1:
69 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
70

x="Today it's Monday"; the code block to be executed


break; }
case 2: Statement 1 is executed before the loop (the code block) starts.
x="Today it's Tuesday"; Statement 2 defines the condition for running the loop (the code block).
break; Statement 3 is executed each time after the loop (the code block) has been executed.
case 3: Example
x="Today it's Wednesday";
for (var i=0; i<5; i++)
break;
case 4: {
x="Today it's Thursday"; x=x + "The number is " + i + "<br>";
break; }
case 5: The While Loop
x="Today it's Friday";
break; The while loop loops through a block of code as long as a specified condition is true.
case 6: Syntax
x="Today it's Saturday"; while (condition)
break; {
default: code block to be executed
x="Looking forward to the Weekend"; }
}
Example
The result of x will be:
Today it's Monday The loop in this example will continue to run as long as the variable i is less than 5:
Example
The default Keyword
while (i<5)
Use the default keyword to specify what to do if there is no match
{
x=x + "The number is " + i + "<br>";
Different Kinds of Loops i++;
JavaScript supports different kinds of loops: }
 for - loops through a block of code a number of times
 for/in - loops through the properties of an object The Do/While Loop
 while - loops through a block of code while a specified condition is true The do/while loop is a variant of the while loop. This loop will execute the code block
 do/while - also loops through a block of code while a specified condition is once, before checking if the condition is true, then it will repeat the loop as long as the
true condition is true.
The For Loop Syntax
The for loop is often the tool you will use when you want to create a loop. do
The for loop has the following syntax: {
for (statement 1; statement 2; statement 3) code block to be executed
{ }
while (condition);
70 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
71

Example It can be errors due to wrong input, from a user, or from an Internet server.
The example below uses a do/while loop. The loop will always be executed at least
once, even if the condition is false, because the code block is executed before the The JavaScript statements try and catch come in pairs.
condition is tested: Syntax
Example try
{
do
//Run some code here
{ }
x=x + "The number is " + i + "<br>"; catch(err)
i++; {
} //Handle errors here
while (i<5); }

Examples
<html>
JavaScript try... catch & throw <body>
Try statement: <script type="text/javascript">
The try statement tests a block of code for errors. The try statement allows define a var x=prompt("Enter a number between 0 and 10:","")
block of code to be tested for errors while it is being executed. try
{
if(x>10)
Catch statement throw "Err1"
The catch statement lets you handle the error. The catch statement allows you to else if(x<0)
define a block of code to be executed, if an error occurs in the try block throw "Err2"
}
Throw Statement catch(er)
The throw statements create custom errors. {
The correct technical term is to create or throw an exception. if(er=="Err1")
If you use the throw statement together with try and catch, you can control program alert("Error! The value is too high")
flow and generate custom error messages. if(er == "Err2")
Syntax alert("Error! The value is too low")
}
throw exception
</script>
The exception can be a JavaScript String, a Number, a Boolean or an Object. </body>
</html>
Errors Will Happen!
When the JavaScript engine is executing JavaScript code, different errors can occur: JavaScript Objects
It can be syntax errors, typically coding errors made by the programmer.
An object is just a special kind of data, with properties and methods.
It can be missing features in the language (maybe due to browser differences).

71 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
72

In JavaScript almost everything is an object. Even primitive datatypes (except null and  2. Use a function to define an object, then create new object instances.
undefined) can be treated as objects.
 Booleans can be objects Creating a Direct Instance
 Numbers can be objects The following example creates a new instance of an object, and adds four properties to
 Strings are also objects it:
 Dates are always objects Example
 Maths and Regular Expressions are always objects person=new Object();
 Arrays are always objects person.firstname="John";
 Even functions are always objects person.lastname="Doe";
person.age=50;
Accessing Object Properties person.eyecolor="blue";
Properties are the values associated with an object. JavaScript Date Object
The syntax for accessing the property of an object is: The Date object is used to work with dates and times.
Date objects are created with new Date().
objectName.propertyName There are four ways of instantiating a date:
var d = new Date();
This example uses the length property of the String object to find the length of a string: var d = new Date(milliseconds);
var d = new Date(dateString);
var message="Hello World!"; var d = new Date(year, month, day, hours, minutes, seconds, milliseconds;
var x=message.length;
The value of x, after execution of the code above will be: <html>
12 <head>
Accessing Objects Methods <title>Current date and time</title>
Methods are the actions that can be performed on objects. </head>
You can call a method with the following syntax: <script type="text/javascript">
objectName.methodName () var todayDate=new Date();
This example uses the toUpperCase() method of the String object, to convert a text to
uppercase:
var message="Hello world!"; document.writeln(todayDate);
var x=message.toUpperCase();
The value of x, after execution of the code above will be: </script>
HELLO WORLD! </html>
JavaScript Array Object
Creating JavaScript Objects The Array object is used to store multiple values in a single variable.
With JavaScript you can define and create your own objects.
There are 2 different ways to create a new object: Create an array, and assign values to it:
var mycars = new Array();
 1. Define and create a direct instance of an object.
mycars[0] = "Saab";
72 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
73

mycars[1] = "Volvo"; 1: Regular:


mycars[2] = "BMW"; var myCars=new Array();
myCars[0]="Saab";
Example myCars[1]="Volvo";
<html> myCars[2]="BMW";
<head> 2: Condensed:
<title>array object</title> var myCars=new Array("Saab","Volvo","BMW");
</head> 3: Literal:
var myCars=["Saab","Volvo","BMW"];
<script type="text/javascript">
var my_array = new Array();
for (i = 0; i < 10; i++)
{ Access an Array
my_array[i] = i; You refer to an element in an array by referring to the index number.
} This statement access the value of the first element in myCars:
x = my_array[4]; var name=myCars[0];
document.writeln(x); This statement modifies the first element in myCars:
myCars[0]="Opel";
</script>
</html> [0] is the first element in an array. [1] is the second . . . . . (indexes start with 0)
What is an Array? Boolean Object
An array is a special variable, which can hold more than one value at a time. The Boolean object is used to convert a non-Boolean value to a Boolean value (true or
If you have a list of items (a list of car names, for example), storing the cars in single false).
variables could look like this: Example
var car1="Saab"; Make a new method for the Boolean object:
var car2="Volvo"; Boolean.prototype.myColor=function()
var car3="BMW"; {
if (this.valueOf()==true)
However, what if you want to loop through the cars and find a specific one? And what {
if you had not 3 cars, but 300? this.color="green";
The solution is an array! }
An array can hold many values under a single name, and you can access the values by else
referring to an index number. {
this.color="red";
}
}
Create an Array
An array can be created in three ways.
Make a Boolean object, then calls the myColor method:
The following code creates an Array object called myCars:

73 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
74

var x = Math.PI; // Returns PI


Property Description var y = Math.sqrt(16); // Returns the square root of 16
<html>
E Returns Euler's number (approx. 2.718)
<body>
LOG2E Returns the base-2 logarithm of E (approx. 1.442) <script>

LOG10E Returns the base-10 logarithm of E (approx. 0.434) Property Description


PI Returns PI (approx. 3.14) constructor Returns the function that created the Boolean object's prototype

SQRT1_2 Returns the square root of 1/2 (approx. 0.707) prototype Allows you to add properties and methods to a Boolean object

SQRT2 Returns the square root of 2 (approx. 1.414) document.write(Math.pow(4,3));


</script>
var a=new Boolean(1);
</body>
a.myColor();
var b=a.color; </html>
The value of b is now: Math Object Properties
Green
Boolean Object Properties Method Description

toString() Converts a Boolean value to a string, and returns the result


Boolean Object Methods
valueOf() Returns the primitive value of a Boolean object
<html>
<body>
<script>
var myvar=new Boolean(1); Math Object Methods
document.write(myvar);
</script> Method Description
</body>
</html> cos(x) Returns the cosine of x (x is in radians)

log(x) Returns the natural logarithm (base E) of x

Math Object max(x,y,z,...,n) Returns the number with the highest value
The Math object allows you to perform mathematical tasks.
Math is not a constructor. All properties/methods of Math can be called by using Math min(x,y,z,...,n) Returns the number with the lowest value
as an object, without creating it.
pow(x,y) Returns the value of x to the power of y
Syntax

74 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
75

round(x) Rounds x to the nearest integer JavaScript is case sensitive. The function keyword must be written in lowercase
letters, and the function must be called with the same capitals as used in the function
sin(x) Returns the sine of x (x is in radians) name.
sqrt(x) Returns the square root of x

tan(x) Returns the tangent of an angle

JavaScript Functions Calling a Function with Arguments


Example When you call a function, you can pass along some values to it, these values are
called arguments or parameters.
<html> These arguments can be used inside the function.
<head> You can send as many arguments as you like, separated by commas (,)
<script> myFunction(argument1,argument2)
function myFunction()
{ Declare the argument, as variables, when you declare the function:
alert("Hello World!"); function myFunction(var1,var2)
} {
</script> some code
</head> }
<body> The variables and the arguments must be in the expected order. The first variable is
<button it</button> given the value of the first passed argument etc.
</body> Example
</html> <button Potter','Wizard')">Try it</button>

JavaScript Function Syntax <script>


A function is written as a code block (inside curly { } braces), preceded by function myFunction(name,job)
the function keyword: {
alert("Welcome " + name + ", the " + job);
function functionname() }
{ </script>
some code to be executed
}
Functions with a Return Value
Sometimes you want your function to return a value back to where the call was made.
The code inside the function will be executed when "someone" calls the function.
This is possible by using the return statement.
The function can be called directly when an event occurs (like when a user clicks a
When using the return statement, the function will stop executing, and return the
button), and it can be called from "anywhere" by JavaScript code.
specified value.
75 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
76

Syntax The function above will exit the function if a>b, and will not calculate the sum of a and
function myFunction() b.
{
var x=5;
return x; Cascading style sheet
} Cascading style sheets(CSS) is a simple mechanism for adding style (e.g., fonts,
The function above will return the value 5. colors, spacing) to web documents(eg., HTML).
Note: It is not the entire JavaScript that will stop executing, only the function.
JavaScript will continue executing code, where the function-call was made from.  CSS stands for cascading style sheets.
The function-call will be replaced with the return value:
 It is also called as style sheets or styles.
var myVar=myFunction();
 Css is used to add more effects for our html page to make it moreattractive
The variable myVar holds the value 5, which is what the function "myFunction()"
returns.  Styles define how to display HTML elements
You can also use the return value without storing it as a variable:  External Style Sheets can save a lot of work
document.getElementById("demo").innerHTML=myFunction();  External Style Sheets are stored in CSS files
The innerHTML of the "demo" element will be 5, which is what the function
"myFunction()" returns. CSS Syntax
You can make a return value based on arguments passed into the function:
A CSS rule has two main parts: a selector, and one or more declarations:
Example
Calculate the product of two numbers, and return the result:
function myFunction(a,b)
{
return a*b;
}
The selector is normally the HTML element you want to style.
document.getElementById("demo").innerHTML=myFunction(4,3); Each declaration consists of a property and a value.
The innerHTML of the "demo" element will be: The property is the style attribute you want to change. Each property has a value.
12
The return statement is also used when you simply want to exit a function. The
return value is optional: CSS Example
function myFunction(a,b) A CSS declaration always ends with a semicolon, and declaration groups are
{ surrounded by curly brackets:
if (a>b) p {color:red;text-align:center;}
{ To make the CSS more readable, you can put one declaration on each line, like this:
return; Example
}
p
x=a+b
} {
color:red;

76 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
77

text-align:center;
}

CSS Comments
Comments are used to explain your code, and may help you when you edit the source
code at a later date. Comments are ignored by browsers.
A CSS comment begins with "/*", and ends with "*/", like this:
/*This is a comment*/
p
{
text-align:center;
/*This is another comment*/
color:black;
font-family:arial;
}
Three Ways to Insert CSS
There are three ways of inserting a style sheet:
 External style sheet
 Internal style sheet Do not add a space between the property value and the unit (such as margin-
 Inline style left:20 px). The correct way is: margin-left:20px

External Style Sheet


Internal Style Sheet
An external style sheet is ideal when the style is applied to many pages. With an
external style sheet, you can change the look of an entire Web site by changing one An internal style sheet should be used when a single document has a unique style. You
file. Each page must link to the style sheet using the <link> tag. The <link> tag goes define internal styles in the head section of an HTML page, by using the <style> tag,
inside the head section: like this:
<head> <head>
<link rel="stylesheet" type="text/css" href="mystyle.css"> <style>
</head> hr {color:sienna;}
An external style sheet can be written in any text editor. The file should not contain p {margin-left:20px;}
any html tags. Your style sheet should be saved with a .css extension. An example of a body {background-image:url("images/back40.gif");}
style sheet file is shown below: </style>
hr {color:sienna;} </head>
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}

77 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
78

<p style="color:red;margin-left:20px;">This is a paragraph.</p>

Multiple Style Sheets


If some properties have been set for the same selector in different style sheets, the
values will be inherited from the more specific style sheet.
For example, an external style sheet has these properties for the h3 selector:
h3
{
color:red;
text-align:left;
font-size:8pt;
}
And an internal style sheet has these properties for the h3 selector:
h3
{
text-align:right;
font-size:20pt;
}
If the page with the internal style sheet also links to the external style sheet the
properties for h3 will be:
color:red;
text-align:right;
font-size:20pt;
The color is inherited from the external style sheet and the text-alignment and the font-
size is replaced by the internal style sheet.

Multiple Styles Will Cascade into One


Styles can be specified:
 inside an HTML element
 inside the head section of an HTML page
 in an external CSS file
Inline Styles Tip: Even multiple external style sheets can be referenced inside a single HTML
An inline style loses many of the advantages of style sheets by mixing content with document.
presentation. Use this method sparingly!
To use inline styles you use the style attribute in the relevant tag. The style attribute Cascading order
can contain any CSS property. The example shows how to change the color and the
left margin of a paragraph:
78 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
79

What style will be used when there is more than one style specified for an HTML The background image for a page can be set like this:
element? Example
Generally speaking we can say that all the styles will "cascade" into a new "virtual" body {background-image:url('paper.gif');}
style sheet by the following rules, where number four has the highest priority:
1. Browser default
2. External style sheet Background Image - Repeat Horizontally or Vertically
3. Internal style sheet (in the head section) By default, the background-image property repeats an image both horizontally and
4. Inline style (inside an HTML element) vertically.
So, an inline style (inside an HTML element) has the highest priority, which means Some images should be repeated only horizontally or vertically, or they will look
that it will override a style defined inside the <head> tag, or in an external style sheet, strange, like this:
or in a browser (a default value). Example
body
Note: If the link to the external style sheet is placed after the internal style sheet in {
HTML <head>, the external style sheet will override the internal style sheet!
background-image:url('gradient2.png');
}
CSS background properties are used to define the
background effects of an element. Property Description
CSS properties used for background effects:
 background-color background Sets all the background properties in one declaration
 background-image
 background-repeat background- Sets whether a background image is fixed or scrolls with the
 background-attachment attachment rest of the page
 background-position
background-color Sets the background color of an element
Background Color
The background-color property specifies the background color of an element. background-image Sets the background image for an element
The background color of a page is defined in the body selector:
Example background-position Sets the starting position of a background image
body {background-color:#b0c4de;}
background-repeat Sets how a background image will be repeated
With CSS, a color is most often specified by:
 a HEX value - like "#ff0000"
 an RGB value - like "rgb(255,0,0)"
 a color name - like "red" All CSS Text Properties
Text Color
Background Image The color property is used to set the color of the text.
The background-image property specifies an image to use as the background of an With CSS, a color is most often specified by:
element.  a HEX value - like "#ff0000"
By default, the image is repeated so it covers the entire element.  an RGB value - like "rgb(255,0,0)"

79 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
80

 a color name - like "red"


text-transform Controls the capitalization of text
Look at CSS Color Values for a complete list of possible color values.
The default color for a page is defined in the body selector.
vertical-align Sets the vertical alignment of an element
Example
body {color:blue;} white-space Specifies how white-space inside an element is handled
h1 {color:#00ff00;}
h2 {color:rgb(255,0,0);} word-spacing Increases or decreases the space between words in a text

Text Alignment
The text-align property is used to set the horizontal alignment of a text.
Text can be centered, or aligned to the left or right, or justified. Font Style
When text-align is set to "justify", each line is stretched so that every line has equal The font-style property is mostly used to specify italic text.
width, and the left and right margins are straight (like in magazines and newspapers). This property has three values:
Example  normal - The text is shown normally
h1 {text-align:center;}  italic - The text is shown in italics
p.date {text-align:right;}  oblique - The text is "leaning" (oblique is very similar to italic, but less
p.main {text-align:justify;} supported)
Example
p.normal {font-style:normal;}
p.italic {font-style:italic;}
p.oblique {font-style:oblique;}
Property Description

color Sets the color of text


All CSS Font Properties
direction Specifies the text direction/writing direction
Property Description
letter-spacing Increases or decreases the space between characters in a text
font Sets all the font properties in one declaration
line-height Sets the line height
font-family Specifies the font family for text
text-align Specifies the horizontal alignment of text
font-size Specifies the font size of text
text-decoration Specifies the decoration added to text
font-style Specifies the font style for text
text-indent Specifies the indentation of the first line in a text-block
font-variant Specifies whether or not a text should be displayed in a small-caps font
text-shadow Specifies the shadow effect added to text
font-weight Specifies the weight of a font

80 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
81

}
</style>
Styling Links </head>
Links can be styled with any CSS property (e.g. color, font-family, background, etc.).
In addition, links can be styled differently depending on what state they are in. <body>
The four links states are: <p id="para1">Hello World!</p>
 a:link - a normal, unvisited link <p>This paragraph is not affected by the style.</p>
 a:visited - a link the user has visited </body>
 a:hover - a link when the user mouses over it </html>
 a:active - a link the moment it is clicked
Example The class Selector
a:link {color:#FF0000;} /* unvisited link */ The class selector is used to specify a style for a group of elements. Unlike the id
a:visited {color:#00FF00;} /* visited link */ selector, the class selector is most often used on several elements.
a:hover {color:#FF00FF;} /* mouse over link */ This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
a:active {color:#0000FF;} /* selected link */
In the example below, all HTML elements with class="center" will be center-aligned:
When setting the style for several link states, there are some order rules: Example
 a:hover MUST come after a:link and a:visited
.center {text-align:center;}
 a:active MUST come after a:hover
You can also specify that only specific HTML elements should be affected by a class.
In the example below, all p elements with class="center" will be center-aligned:
CSS Selectors Example
In CSS, selectors are patterns used to select the element(s) you want to style. p.center {text-align:center;}
example
TYPES OF SELECTORS <html>
ID Selector <head>
CLASS Selector <style>
p.center
The id Selector {
The id selector is used to specify a style for a single, unique element. text-align:center;
The id selector uses the id attribute of the HTML element, and is defined with a "#". }
The style rule below will be applied to the element with id="para1": </style>
Example </head>
<html>
<head> <body>
<style> <h1 class="center">This heading will not be affected</h1>
#para1 <p class="center">This paragraph will be center-aligned.</p>
{ </body>
text-align:center; </html>
color:red;

81 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
82

Div color: #0066FF;


Div (short for division) divides the content into individual sections. Each section can font-family:arial;
then have its own formatting, as specified by the CSS. Div is a block-level container, font-size: 6px;
meaning that there is a line feed after the </div> tag. }
For example, if we have the following CSS declaration:
The HTML code
.large {
color: #00FF00; Span is not at the <span class="largefont">block level</span>.
font-family:arial;
font-size: 4pt; gets displayed as
}
Span is not at the block level.
The HTML code
The HTML <span> Element
<div class="large"> The HTML <span> element is an inline element that can be used as a container for
This is a DIV sample. text.
</div> The <span> element has no special meaning.
When used together with CSS, the <span> element can be used to set style attributes to
gets displayed as parts of the text.
This is a DIV sample.
HTML Grouping Tags
The HTML <div> Element
<html>
The HTML <div> element is a block level element that can be used as a container <body>
for grouping other HTML elements. <div style="color:#0000FF">
The <div> element has no special meaning. Except that, because it is a block level <h3>This is a heading in a div element</h3>
element, the browser will display a line break before and after it. <p>This is some text in a div element.</p>
When used together with CSS, the <div> element can be used to set style attributes </div>
to large blocks of content.
Another common use of the <div> element, is for document layout. It replaces the <p>This is some text.</p>
"old way" of defining layout using tables. Using <table> elements for layout is not <p>My mother has <span style="color:blue;font-weight:bold"> blue</span>
the correct use of <table>. The purpose of the <table> element is to display tabular data. eyes and my father has <span style="color:darkolivegreen;font-
weight:bold">dark green</span> eyes.</p>
Span </body>
Span is similar to div in that they both divide the content into individual sections. The </html>
difference is that span goes into a finer level, so we can span to format a single
character if needed. There is no line feed after the </span> tag.
For example, if we have the following CSS declaration: INTRODUCTION TO AJAX
AJAX is about updating parts of a web page, without reloading the whole page.
.largefont { AJAX = Asynchronous JavaScript and XML.

82 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
83

AJAX is a technique for creating fast and dynamic web pages.  XML (often used as the format for transferring data)
Tag Description AJAX applications are browser and platform independent!

<div> Defines a section in a document (block-level) UNIT 5


<span> Defines a section in a document (inline) Document Object Model
AJAX allows web pages to be updated asynchronously by exchanging small amounts The Document Object Model is a programming API for documents. The object model
of data with the server behind the scenes. This means that it is possible to update parts itself closely resembles the structure of the documents it models.
of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content
An application programming interface (API) specifies how some software
should change. components should interact with each other.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook
tabs.
 The Document Object Model (DOM) is a programming API for HTML and
XML documents
 It defines the logical structure of documents and the way a document is
How AJAX Works accessed and manipulated.
 The DOM defines a standard for accessing HTML and XML documents.

“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."

For instance, consider this table, taken from an HTML document:

<TABLE>
<ROWS>
<TR>
<TD>Shady Grove</TD>
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
AJAX is based on Internet Standards </TR>
</ROWS>
AJAX is based on internet standards, and uses a combination of:
</TABLE>
 XMLHttpRequest object (to exchange data asynchronously with a server)
 JavaScript/DOM (to display/interact with the information)
 CSS (to style the data) The Document Object Model represents this table like this:
83 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
84

DOM Nodes
According to the HTML DOM standard, everything in an HTML document is a node:
 The entire document is a document node
 Every HTML element is an element node
 The text inside HTML elements are text nodes
 Every HTML attribute is an attribute node
 Comments are comment nodes
The HTML DOM Node Tree
The HTML DOM views HTML documents as tree structures. The structure is called
a Node Tree:
HTML DOM Tree Example

DOM representation of the example table


In the Document Object Model, documents have a logical structure which is very
much like a tree;

DOM standard is separated into 3 different parts:


 Core DOM - standard model for any structured document
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents

HTML DOM
The HTML DOM defines a standard for accessing and manipulating HTML
documents. With the HTML DOM, all nodes in the tree can be accessed by JavaScript. All HTML
The HTML DOM defines the objects and properties of all HTML elements, and elements (nodes) can be modified, and nodes can be created or deleted.
the methods to access them. Node Parents, Children, and Siblings
In other words: The nodes in the node tree have a hierarchical relationship to each other.
The HTML DOM is a standard for how to get, change, add, or delete HTML The terms parent, child, and sibling are used to describe the relationships. Parent nodes
elements. have children. Children on the same level are called siblings (brothers or sisters).
The HTML DOM is:  In a node tree, the top node is called the root
 A standard object model for HTML  Every node has exactly one parent, except the root (which has no parent)
 A standard programming interface for HTML  A node can have any number of children
In the HTML DOM, everything is a node. The DOM is HTML viewed as a node tree.  Siblings are nodes with the same parent

84 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
85

 The <h1> and <p> nodes are siblings and child nodes of <body>
and:
The following image illustrates a part of the node tree and the relationship between  The <head> element is the first child of the <html> element
the nodes:  The <body> element is the last child of the <html> element
 The <h1> element is the first child of the <body> element
 The <p> element is the last child of the <body> element

NOTE:
A common error in DOM processing is to expect an element node to contain text.
In this example: <title>DOM Tutorial</title>, the element node <title>, holds a text
node with the value "DOM Tutorial".
The value of the text node can be accessed by the node's innerHTML property.

HTML DOM Methods


Methods are actions you can perform on nodes (HTML Elements)
Programming Interface
The HTML DOM can be accessed with JavaScript (and other programming
languages).
All HTML elements are defined as objects, and the programming interface is the
Look at the following HTML fragment: object methods and object properties.
<html> A method is an action you can do (like add or modify an element).
<head> A property is a value that you can get or set (like the name or content of a node).
<title>DOM Tutorial</title>
</head> The getElementById() Method
<body> The getElementById() method returns the element with the specified ID:
<h1>DOM Lesson one</h1>
Example
<p>Hello world!</p>
var element=document.getElementById("intro");
</body> HTML DOM Objects - Methods and Properties
</html> Some commonly used HTML DOM methods:
From the HTML above:  getElementById(id) - get the node (element) with a specified id
 The <html> node has no parent node; it is the root node  appendChild(node) - insert a new child node (element)
 The parent node of the <head> and <body> nodes is the <html> node  removeChild(node) - remove a child node (element)
 The parent node of the "Hello world!" text node is the <p> node Some commonly used HTML DOM properties:
and:  innerHTML - the text value of a node (element)
 The <html> node has two child nodes: <head> and <body>  parentNode - the parent node of a node (element)
 The <head> node has one child node: the <title> node  childNodes - the child nodes of a node (element)
 The <title> node also has one child node: the text node "DOM Tutorial"  attributes - the attributes nodes of a node (element)
85 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
86

"dynamically" the properties of the objects found in web pages. DHTML is being
obsolete due that all the things you can do can be done easier with flash.
innerHTML
The innerHTML property can be used to modify your document's HTML on the fly. DHTML (Dynamic HTML) is not a programming or markup language like HTML. It
When you use innerHTML, you can change the page's content without refreshing the is a term that is used to describe the creation of dynamic and interactive pages. One of
page. This can make your website feel quicker and more responsive to user input. the advantages of DHTML for web design and clients is that it can combine the use of
The innerHTML property is used along with getElementById within your JavaScript HTML, JavaScript, XML and CSS (Cascading Style Sheets). Dynamic web
code to refer to an HTML element and change its contents. pages/websites separate the content (text) from the logic (interactive functions, look
The innerHTML property is not actually part of the official DOM specification.
and feel etc.). Dynamic content is stored in a database that is connected to the website.
Despite this, it is supported in all major browsers, and has had widespread use across
the web for many years. DOM, which stands for Document Object Model, is the
hierarchy that you can use to access and manipulate HTML objects from within your Components of DHTML
JavaScript.
The innerHTML Syntax  HTML
 CSS
 JAVA SCRIPT
document.getElementById('{ID of element}').innerHTML = '{content}';
 DOM
In this syntax example, {ID of element} is the ID of an HTML element
and {content} is the new content to go into the element. The Role of each component in DHTML
<script type="text/javascript">
function Msg1() With CSS,
{ - we can change the style of any HTML elements.
document.getElementById('myText').innerHTML = 'Thanks!'; With DOM,
} - we can have a map on every elements in the HTML page.
function Msg2() With JavaScript,
{ -we can access and have operations on the elements in the DOM tree.
document.getElementById('myText').innerHTML = 'new thanks'; With event handler,
} -we can execute the predefined scripts at any time.
</script>
<input type="button" value="Show Message 1" /> Makes a web site dynamic?
<input type="button" value="Show Message 2" />
<p id="myText"></p> Interactivity – adapt and react to the visitor’s actions as quick as possible.
Synchronicity – bring together relevant information from a variety of sources.
Flexibility – give the visitor different ways to find information in the site.
Adaptability – adjusts to cater to individual visitor’s needs.
DHTML (Dynamic HTML) Activity – uses motion and sound to draw user’s attention to changes on the site

HTML is the basic language to make web pages. DOM = Document Object Model
Defines a hierarchical model of the document structure
DHTML uses language resources such as style sheets (css) and javascript to modify through which all document elements may be accessed
86 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
87

Nodes
The W3C DOM defines element of a document is a node method Sets or returns the value of the method attribute in a form
of a particular type
Node Types name Sets or returns the value of the name attribute in a form
Common types are: document node, element node, text
node, attribute node, comment node, document-type node target Sets or returns the value of the target attribute in a form
Advantages of DHTML Form Object Methods
Supported by most browsers
Small file sizes (faster than Flash) Method Description
No plug-ins required reset() Resets a form
Easy to learn (learn HTML, JavaScript)
Faster web experience (change the page content without load new pages) submit() Submits a form
Browser and OS incompatibilities
The implementation of CSS, DOM varies from browser to browser Form Object Events
Event The event occurs when...
Disadvantages of DHTML
onreset The reset button is clicked
 Incomplete support : Both Netscape and Explorer support CSS-P and the
DOM, but apply it to HTML document elements using different tags. Many
DHTML effects require a browser detection script and two completely onsubmit The submit button is clicked
different sets of code to make same effect display across browsers.
 Learning Curve: Because DHTML is a combination of technologies, Example
developers need to be proficient in HTML, CSS, and JavaScript. The learning
curve can be heavy.. Create a button that submits the form:
 Expensive Tools:. Dreamweaver and Fusion are two of the most popular; <html>
Form Object <head>
<script>
The Form object represents an HTML form.
For each <form> tag in an HTML document, a Form object is created. function formSubmit()
Forms are used to collect user input, and contain input elements like text fields, {
checkboxes, radio-buttons, submit buttons and more. A form can also contain select document.getElementById("frm1").submit();
menus, textarea, fieldset, legend, and label elements. }
Forms are used to pass data to a server. </script>
Form Object Properties </head>
Property Description <body>

action Sets or returns the value of the action attribute in a form <form id="frm1" action="form_action.asp">
First name: <input type="text" name="fname"><br>
length Returns the number of elements in a form
Last name: <input type="text" name="lname"><br>
<input type="button" value="Submit form">
87 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
88

</form> <price>29.99</price>
</book>
</body> </bookstore>
</html> The root node in the XML above is named <bookstore>. All other nodes in the
document are contained within <bookstore>.
The root node <bookstore> holds two <book> nodes.
XML DOM The first <book> node holds four nodes: <title>, <author>, <year>, and <price>, which
The XML DOM defines a standard for accessing and manipulating XML. contains one text node each, "Everyday Italian", "Giada De Laurentiis", "2005", and
The XML DOM is: "30.00".
 A standard object model for XML Text is Always Stored in Text Nodes
 A standard programming interface for XML A common error in DOM processing is to expect an element node to contain text.
 Platform- and language-independent However, the text of an element node is stored in a text node.
The XML DOM defines the objects and properties of all XML elements, and In this example: <year>2005</year>, the element node <year>, holds a text node with
the methods (interface) to access them. the value "2005".
The XML DOM is a standard for how to get, change, add, or delete XML "2005" is not the value of the <year> element!
elements. The XML DOM views an XML document as a node-tree.
All the nodes in the tree have a relationship to each other.
DOM Nodes
According to the DOM, everything in an XML document is a node.
The XML DOM Node Tree
The DOM says:
 The entire document is a document node The XML DOM views an XML document as a tree-structure. The tree structure is
 Every XML element is an element node called a node-tree.
 The text in the XML elements are text nodes All nodes can be accessed through the tree. Their contents can be modified or deleted,
 Every attribute is an attribute node and new elements can be created.
 Comments are comment nodes
The node tree shows the set of nodes, and the connections between them. The tree
starts at the root node and branches out to the text nodes at the lowest level of the tree:
<?xml version="1.0" encoding="ISO-8859-1"?>
<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="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>

88 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
89

Common Gateway Interface (CGI)


The Common Gateway Interface (CGI) is a set of rules for
running scripts and programs on a Web server. It specifies what information is
communicated between the Web server and clients' Web browsers and how the
information is transmitted.
Common Gateway Interface (CGI) is a standard method used to
generate dynamic content on web pages and web applications. CGI, when
implemented on a web server provides an interface between the web server and
programs that generate the web content. These programs are known as CGI
scripts or simply CGIs; they are usually written in a scripting language.

89 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
90

3. The gateway program processes the information and returns HTML text to the Web
CGI provides the communication interface between a gateway and a Web server. server. The server, in turn, adds a MIME header and returns the HTML text to the Web
A script is a program written a C, C++, TCL, PERL (Practical Extraction and Report
Language). browser.
Web server is the middleware to receive request from the Web client and pass it to 4. The Web browser displays the document received from the Web server.
CGI script, and send information back to the Web Client.
CGI programs are most commonly used with HTML FORM's, and provide the
server interface that receives the form variables and processes them.
CGI simply specifies an interface convention, and the programs that work with
CGI can be written in virtually any language.

Testing &debugging Perl CGI script,


Several basic steps exist in the debugging process. The following list is a suggested
method of finding the problem by process of elimination; as you develop and debug a
few programs of your own; you'll grow to recognize certain kinds of problems and will
be able to skip many of these steps:
 Test the program and keep track of any problems you encounter.
 If your project includes multiple Perl programs, determine which program is
causing the error.
 Determine whether the program is executing at all.
 Check for syntax errors.
The sequence of events for creating a dynamic HTML document on the fly through  Determine whether the program is producing valid HTML output.
 Check whether the correct data is being sent to the program from the form.
CGI scripting is as follows:
 Pinpoint the location of the problem and fix it.
1. A client makes an HTTP request by means of a URL. This URL could be typed into Perl/CGI is a server-side scripting language, used to run
arbitrary programs within the web server. The web server is
the 'Location' window of a browser, be a hyperlink or be specified in the 'Action'
configured to understand the Perl scripts and to execute
attribute of an HTML <form> tag. them. The web server on CCC is configured to connect to both
mySQL as well Oracle database servers through their
respective Perl “modules”.
2. From the URL, the Web server determines that it should activate the gateway
program listed in the URL and send any parameters passed via the URL to that Let us start with a simple Hello World Perl script, which I
will call as helloWorld.pl
program.
#!/usr/local/bin/perl
use CGI::Carp qw(fatalsToBrowser warningsToBrowser);
print "Content-type: text/html\n\n"; print
("<html><head><title>Hello World Script</title></head>\n");

90 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
91

print ("<body>\n"); print ("<h1>Hello World !!!!</h1>\n");  When you see a period (.) between two variables it is merely "concantenating"
print ("</body></html>\n"); the two variables (putting them together)
 A word starting with a @ indicates that this is a single-dimension array.
The first line is a directive as to where the perl compiler (Single-dimension arrays are referred to as "lists" in Perl)
exists. There are different modules within Perl, and we will  A word starting with a % indicates a two-dimensional array officially called
use CGI::Carp module, which allows us to print statements to an "associative array" but more commonly referred to as a "hash" (you'll have
the browser window (i.e., the HTTP client). It also helps in to read up on that one)
debugging, which is difficult when we are using HTTP. We need  When you see a file open statement with a < sign, or no symbol at all, the file
is being opened for a read operation
the first print statement with the two new line characters
 When you see a file open statement with a > sign the file is being opened for
(or more than two new line characters) according to the HTTP
a write operation
protocol. The rest of these are print statements, which get  When you see a file open statement with two >> signs the file is being
printed to the HTTP client (browser). opened for an append operation

Testing from the command line


perl - scalar variables
Before we try to run the script via the Web server, let's try running
it from the command line Scalar variables are simple variables containing only one element--a string, a
number, or a reference. Strings may contain any symbol, letter, or number.
Numbers may contain exponents, integers, or decimal values. The bottom line
Testing from the Web server
here with scalar variables is that they contain only one single piece of data. What
you see is what you get with scalar variables.
Assuming your script did print out from the command line, let's go
to the final step: testing the script via the Web server The most basic kind of variable in Perl is the scalar variable.
Scalar variables hold both strings and numbers, and are remarkable
in that strings and numbers are completely interchangeable. For
Perl Basics
example, the statement
If you know just a few simple Perl things you'll be able to look at most Perl scripts and
figure out what they do. $priority = 9;
Sets the scalar variable $priority to 9, but you can also assign a
string to exactly the same variable:
 A line staring with a # denotes a comment (which doesn't get executed). $priority = 'high';
 A word starting with a $ indicates that this is a "variable" (i.e. a temporary Perl also accepts numbers as strings, like this:
holding area for a value) $priority = '9';
 A word starting with a & is a call to a sub-routine (where the '&' denotes the $default = '0009';
call and the word is the name of the sub-routine located elsewhere in the
script)
and can still cope with arithmetic and other operations quite
happily.
91 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
92

In general variable names consists of numbers, letters and  Arithmetic Operators


underscores, but they should not start with a number and the  Equality Operators
variable $_ is special, as we'll see later. Also, Perl is case sensitive,
so $a and $A are different.  Logical Operators

 Assignment Operators
A scalar variable stores a single (scalar) value. Perl scalar names
are prefixed with a dollar sign ($), so for example, $x, $y, $z,  Bitwise Operators
$username, and $url are all examples of scalar variable names.
 Logical Operators
Here's how variables are used:
 Quote-like Operators
$foo = 1;
$name = "Fred";
 Miscellaneous Operators
$pi = 3.141592;
You do not need to declare a variable before using it; just drop it Lets have a look on all operators one by one.
into your code. A scalar can hold data of any type, be it a string, a
number, or whatnot. You can also drop scalars into double-quoted Perl Arithmetic Operators:
strings:
$fnord = 23; Assume variable $a holds 10 and variable $b holds 20 then:
$blee = "The magic number is $fnord.";
Now if you print $blee, you will get "The magic number is 23." Operator Description Example

Let's edit first.pl again and add some scalars to it: +


Addition - Adds values on either side of
$a + $b will give 30
the operator
#!/usr/bin/perl
$classname = "CGI Programming 101"; Subtraction - Subtracts right hand
print "Hello there. What is your name?\n"; - $a - $b will give -10
operand from left hand operand
$you = <STDIN>;
chomp($you);
print "Hello, $you. Welcome to $classname.\n"; Multiplication - Multiplies values on
* $a * $b will give 200
either side of the operator
operator
using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called Division - Divides left hand operand by
operator. / $b / $a will give 2
right hand operand
Perl language supports many operator types but following is a list of important and most
frequently used operators:

92 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
93

Modulus - Divides left hand operand by ($a >=


Checks if the value of left operand is greater than or equal to the
% right hand operand and returns $b % $a will give 0 >= $b) is not
value of right operand, if yes then condition becomes true.
remainder true.

Exponent - Performs exponential $a**$b will give 10 to the power ($a <=
** Checks if the value of left operand is less than or equal to the value
(power) calculation on operators 20 <= $b) is
of right operand, if yes then condition becomes true.
true.

Perl Equality Operators:


These are also called relational operators. Assume variable $a holds 10 and variable $b
Perl Assignment Operators:
holds 20 then, lets check following numeric equality operators: Assume variable $a holds 10 and variable $b holds 20 then:

[ Show Example ] [ Show Example ]


Operator Description Example Operator Description Example

($a == Simple assignment operator, Assigns values from $c = $a + $b will assigne


Checks if the value of two operands are equal or not, if yes then =
== $b) is not right side operands to left side operand value of $a + $b into $c
condition becomes true.
true.

Add AND assignment operator, It adds right


($a != $c += $a is equivalent to $c
Checks if the value of two operands are equal or not, if values are += operand to the left operand and assign the result to
!= $b) is = $c + $a
not equal then condition becomes true. left operand
true.

Subtract AND assignment operator, It subtracts


($a <=> $c -= $a is equivalent to $c
Checks if the value of two operands are equal or not, and returns -1, -= right operand from the left operand and assign the
$b) = $c - $a
<=> 0, or 1 depending on whether the left argument is numerically less result to left operand
returns -
than, equal to, or greater than the right argument.
1.
Multiply AND assignment operator, It multiplies right
$c *= $a is equivalent to $c
*= operand with the left operand and assign the result
($a > $b) = $c * $a
Checks if the value of left operand is greater than the value of right to left operand
> is not
operand, if yes then condition becomes true.
true.
Divide AND assignment operator, It divides left
$c /= $a is equivalent to $c
/= operand with the right operand and assign the
= $c / $a
Checks if the value of left operand is less than the value of right ($a < $b) result to left operand
<
operand, if yes then condition becomes true. is true.

93 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
94

%=
Modulus AND assignment operator, It takes
modulus using two operands and assign the result
$c %= $a is equivalent to Perl Bitwise Operators:
$c = $c % a
to left operand Bitwise operator works on bits and perform bit by bit operation. Assume if $a = 60; and $b =
13; Now in binary format they will be as follows:
Exponent AND assignment operator, Performs
$c **= $a is equivalent to $a = 0011 1100
**= exponential (power) calculation on operators and
$c = $c ** $a
assign value to the left operand $b = 0000 1101

-----------------
Perl Logical Operators:
$a&$b = 0000 1100
There are following logical operators supported by Perl language. Assume variable $a holds
true and variable $b holds false then: $a|$b = 0011 1101

[ Show Example ] $a^$b = 0011 0001


Operator Description Example
~$a = 1100 0011

Called Logical AND operator. If both the There are following Bitwise operators supported by Perl language
and operands are true then then condition becomes ($a and $b) is false.
true. [ Show Example ]
Operator Description Example

C-style Logical AND operator copies a bit to the


&& ($a && $b) is false.
result if it exists in both operands. Binary AND Operator copies a bit to the result if ($a & $b) will give 12
&
it exists in both operands. which is 0000 1100

Called Logical OR Operator. If any of the two


or operands are non zero then then condition ($a or $b) is true. Binary OR Operator copies a bit if it exists in ($a | $b) will give 61
|
becomes true. eather operand. which is 0011 1101

C-style Logical OR operator copies a bit if it Binary XOR Operator copies the bit if it is set in ($a ^ $b) will give 49
|| ($a || $b) is true. ^
exists in eather operand. one operand but not both. which is 0011 0001

Called Logical NOT Operator. Use to reverses (~$a ) will give -61 which
not the logical state of its operand. If a condition is not($a and $b) is true. Binary Ones Complement Operator is unary and is 1100 0011 in 2's
~
true then Logical NOT operator will make false. has the efect of 'flipping' bits. complement form due to a
signed binary number.

94 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
95

<<
Binary Left Shift Operator. The left operands
value is moved left by the number of bits
$a << 2 will give 240 Java applet
which is 1111 0000 A Java applet is a small application written in Java and delivered to users in
specified by the right operand.
the form of bytecode. The user launches the Java applet from a web page and
Binary Right Shift Operator. The left operands it is then executed within a Java Virtual Machine (JVM) in a process separate
$a >> 2 will give 15 which
>> value is moved right by the number of bits
is 0000 1111 from the web browser itself. A Java applet can appear in a frame of the web
specified by the right operand.
page, a new application window, Sun's Applet Viewer or a stand-alone tool
for testing applets. Java applets were introduced in the first version of the
Quote-like Operators: Java language in 1995.

There are following Quote-like operators supported by Perl language. In the following table, SOURCE CODE(COMPILE)BYTE CODE(INTERPRET)MACHINE CODE
a {} represents any pair of delimiters you choose.

[ Show Example ] Java bytecode is the form of instructions that the Java virtual machine executes.
Operator Description Example Each bytecode opcode is one byte in length,

q{ } Encloses a string with-in single quotes q{abcd} gives 'abcd'


An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java
qq{ } Encloses a string with-in double quotes qq{abcd} gives "abcd" application, including the following:
 An applet is a Java class that extends the java.applet.Applet class.
qx{ } Encloses a string with-in invert quotes qx{abcd} gives `abcd`  A main() method is not invoked on an applet, and an applet class will not define
main().
 Applets are designed to be embedded within an HTML page.

Miscellaneous Operators: When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
There are following miscellaneous operators supportet="Perl Operators Precedence  A JVM is required to view an applet. The JVM can be either a plug-in of the Web
Example">Show Example ] browser or a separate runtime environment.
 The JVM on the user's machine creates an instance of the applet class and invokes
left terms and list operators (leftward) various methods during the applet's lifetime.
left ->  Applets have strict security rules that are enforced by the Web browser. The security of
nonassoc ++ -- an applet is often referred to as sandbox security, comparing the applet to a child
right ** playing in a sandbox with various rules that must be followed.
right ! ~ \ and unary + and -  Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.

Life Cycle of an Applet:

95 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
96

Four methods in the Applet class give you the framework on which you build any
serious applet: The Applet CLASS:
Every applet is an extension of the java.applet.Applet class. The base Applet class provides
 init: This method is intended for whatever initialization is needed for your applet. It is methods that a derived Applet class may call to obtain information and services from the
browser context.
called after the param tags inside the applet tag have been processed.
 start: This method is automatically called after the browser calls the init method. It is These include methods that do the following:
also called whenever the user returns to the page containing the applet after having
gone off to other pages.  Get applet parameters
 stop: This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.  Get the network location of the HTML file that contains the applet
 destroy: This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources  Get the network location of the applet class directory
behind after a user leaves the page that contains the applet.
 paint: Invoked immediately after the start() method, and also any time the applet  Print a status message in the browser
needs to repaint itself in the browser. The paint() method is actually inherited from the
java.awt.  Fetch an image

A "Hello, World" Applet:  Fetch an audio clip

The following is a simple applet named HelloWorldApplet.java:  Play an audio clip

import java.applet.*;  Resize the applet


import java.awt.*;
Additionally, the Applet class provides an interface by which the viewer or browser obtains
public class HelloWorldApplet extends Applet information about the applet and controls the applet's execution. The viewer may:
{
public void paint (Graphics g)
{  request information about the author, version and copyright of the applet
g.drawString ("Hello World", 25, 50);
}  request a description of the parameters the applet recognizes
}
 initialize the applet
These import statements bring the classes into the scope of our applet class:
 destroy the applet
 java.applet.Applet.
 start the applet's execution
 java.awt.Graphics.
 stop the applet's execution
Without those import statements, the Java compiler would not recognize the classes Applet
and Graphics, which the applet class refers to. The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.

96 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR
97

The "Hello, World" applet is complete as it stands. The only method overridden is the paint If an applet resides in a package other than the default, the holding package must be
method. specified in the code attribute using the period character (.) to separate package/class
components. For example:

Invoking an Applet: <applet code="mypackage.subpackage.TestApplet.class"


width="320" height="120">
An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.

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

<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Based on the above examples, here is the live applet example: Applet Example.
Note: You can refer to HTML Applet Tag to understand more about calling applet from
HTML.

The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width
and height are also required to specify the initial size of the panel in which an applet runs.
The applet directive must be closed with a </applet> tag.

If an applet takes parameters, values may be passed for the parameters by adding <param>
tags between <applet> and </applet>. The browser ignores text and other tags between the
applet tags.

Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything


that appears between the tags, not related to the applet, is visible in non-Java-enabled
browsers.

The viewer or browser looks for the compiled Java code at the location of the document. To
specify otherwise, use the codebase attribute of the <applet> tag as shown:

<applet codebase="http://amrood.com/applets"
code="HelloWorldApplet.class" width="320" height="120">

97 CSE 3rd sem COMPUTER CONCEPT AND WEB TECHNLOGY | By ATUL SINGH-JKIE BILASPUR

You might also like