0% found this document useful (0 votes)
45 views150 pages

1 To 5 Unit

Uploaded by

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

1 To 5 Unit

Uploaded by

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

191CAC602J - Web Technology

UNIT I : WEB ESSENTIALS AND HTML 9

Web Essentials: Creating a Website - Working principle of a Website - Browser


fundamentals-Client - Server Communication. The Basic Internet Protocols - The
World Wide Web - Markup Languages: An Introduction to HTML History – Versions
- Basic XHTML Syntax and Semantics-Some Fundamental HTML Elements -Lists -
tables - Frames - Forms - HTML 5.0

Web Essentials: Creating a Website


1. Define Purpose and Goals
○ Identify the objective of the website (e.g., personal portfolio, e-commerce,
blog).
○ Define the target audience and key features needed.
2. Plan and Structure
○ Create a sitemap outlining the structure (e.g., Home, About, Services,
Contact).
○ Develop wireframes or mockups for design layout.
3. Choose Technology Stack
○ Frontend: HTML, CSS, JavaScript.
○ Backend: PHP, Node.js, Python, Ruby, or others.
○ Database: MySQL, MongoDB, PostgreSQL.
○ Frameworks/Libraries: React, Angular, Vue.js (frontend); Express,
Django (backend).
4. Design and Development
○ Use responsive design principles for cross-device compatibility.
○ Implement functionality using client-side (JavaScript) and server-side logic.
○ Test usability and accessibility.
5. Host and Deploy
○ Register a domain name (e.g., example.com).
○ Choose a hosting provider (shared, VPS, cloud).
○ Deploy using tools like Git, FTP, or CI/CD pipelines.
6. Maintenance
○ Monitor website performance and uptime.
1
○ Regularly update content and software for security and relevance.

Working Principle of a Website


1. User Request
○ A user enters a URL in the browser or clicks a link.
○ The browser sends a request to a DNS server to resolve the domain name
to an IP address.
2. Server Communication
○ The request is sent to the web server hosting the website.
○ The server processes the request, retrieves required data (if any), and
sends back a response.
3. Response Rendering
○ The server response contains HTML, CSS, and JavaScript files.
○ The browser renders these files to display the website content.
4. Client-Server Interaction
○ Websites often use additional technologies like AJAX, REST APIs, or
WebSockets to dynamically update content without reloading the page.
5. Security
○ HTTPS ensures encrypted communication between the client and server.
○ Authentication and authorization manage access control.

Browser Fundamentals
1. What is a Browser?
○ A web browser is software that retrieves, displays, and navigates web
content. Examples include Chrome, Firefox, Safari, and Edge.
2. Main Components of a Browser
○ User Interface (UI): Address bar, navigation buttons, bookmarks, etc.
○ Rendering Engine: Parses HTML, CSS, and JavaScript to render web pages
(e.g., Blink for Chrome, WebKit for Safari).
○ Networking: Handles communication with servers using HTTP/HTTPS.
○ JavaScript Engine: Executes JavaScript code (e.g., V8 in Chrome).
○ Storage: Manages cookies, local storage, and cache for faster access.
3. Browser Rendering Process
○ Parse HTML to create a Document Object Model (DOM).
○ Parse CSS to create a CSS Object Model (CSSOM).
○ Combine DOM and CSSOM into a render tree.
2
○ Layout the render tree and paint it on the screen.
4. Browser Caching
○ Browsers store copies of frequently accessed resources (e.g., images,
scripts) to reduce loading time and server load.
5. Developer Tools
○ Inspect and debug HTML, CSS, and JavaScript.
○ Analyze performance and optimize website speed.

Client-Server Communication
Client-server communication is a model where a client (typically a browser or an
application) sends a request to a server, and the server processes it to send a
response. This interaction forms the foundation of most web and networked
applications.

Client:

● A device or application (e.g., web browser, mobile app) that requests


resources or services.
● Examples: Chrome (web client), Outlook (email client).

Server:

● A device or program that provides services or resources in response to


client requests.
● Examples: Web server (Apache, Nginx), Database server (MySQL).

Client-Side Components

○ User Interface (UI): Frontend design and functionality (e.g., HTML, CSS,
JavaScript).
○ Communication Module: Handles data exchange with the server (e.g.,
AJAX, Fetch API).
○ Storage: Local storage, cookies, or session storage for caching data.
● Server-Side Components
○ Web Server: Receives and processes client requests (e.g., Apache, Nginx).

3
○ Application Server: Handles business logic and connects with databases
(e.g., Node.js, Flask, Spring).
○ Database: Stores and retrieves data (e.g., MySQL, MongoDB).
● Protocols
○ HTTP/HTTPS: Hypertext Transfer Protocol for communication.
○ WebSocket: For real-time, full-duplex communication.
○ REST or GraphQL: API paradigms for structured data exchange.
● Security
○ Authentication: Ensures the user is who they claim to be (e.g., OAuth,
JWT).
○ Encryption: Protects data using HTTPS and SSL/TLS.
○ Authorization: Determines access rights to resources.

Client-Server Architecture

1. Two-Tier Architecture:

● Client Tier: Directly communicates with the server.


● Server Tier: Processes requests and interacts with the database.
● Use Case: Simple applications like local databases or small-scale web apps.

Two-tier architecture, also known as two-layer architecture or client-server


architecture, is a software architecture model that divides an application into two
distinct parts or tiers: the client tier and the server tier. Each tier has specific
responsibilities and functions within the overall application, and they communicate
with each other to provide the desired functionality.

4
2. Three-Tier Architecture:

Three-tier architecture is a software design pattern that organizes applications


into three separate, logical layers:

● Client Tier (Presentation Layer): Frontend user interface.


● Application Tier (Logic Layer): Backend processes and business logic.
● Database Tier (Data Layer): Manages data storage and retrieval.
● Use Case: Most modern web and mobile applications.

1. Presentation Tier (User Interface)

● Role: This is the front-end layer where users interact with the application.
It is responsible for presenting data to the user and interpreting user inputs.
● Components:

5
○ Web browsers, desktop applications, or mobile apps that communicate with
the other tiers.
● Technologies:
○ HTML, CSS, JavaScript for web applications.
○ Frameworks like Angular, React, Vue.js for dynamic web interfaces.

2. Logic Tier (Business Logic)

● Role: This middle layer handles the core functionality of the application,
such as processing business logic, making decisions, and managing data between
the other two tiers.
● Components:
○ Application server, middleware, APIs.
○ Handles business rules, calculations, and data processing.
● Technologies:
○ Server-side programming languages: Java, Python, Ruby, PHP, C#, Node.js.
○ Frameworks: Spring, Django, Flask, ASP.NET.

3. Data Tier (Database)

● Role: The data tier stores, retrieves, and manages application data. It is
responsible for database operations like storing records, querying, updating, and
deleting data.
● Components:
○ Database servers like MySQL, PostgreSQL, Oracle, SQL Server, MongoDB.
● Technologies:
○ Relational databases (RDBMS) or NoSQL databases.

3. Multi-Tier Architecture (N-Tier):

● Extends the three-tier model by adding layers such as caching servers, load
balancers, or microservices.
● Use Case: Large-scale distributed systems.

6
Multi-tier architecture and N-tier architecture are software design patterns
that help organize and structure the different components of an application. Both
are used to separate concerns, improve scalability, maintainability, and facilitate
better management of large systems. While the two terms are often used
interchangeably, there are slight differences based on the number of layers or
tiers involved.

Multi-Tier Architecture

Multi-tier architecture is a software design pattern where the system is divided


into several layers, each responsible for different functionality. These layers or
tiers are often categorized as:

● Presentation Tier: The user interface layer. It’s responsible for displaying
the data to the user and collecting user inputs. This could be a web interface or a
client-side application.
● Business Logic Tier (Application Tier): The business layer or logic layer,
which handles data processing and decision-making. It processes requests from
the presentation tier and sends them to the data tier.
● Data Tier: The data storage layer, typically a database, where the
application stores and retrieves data.

Key Features:

7
● Separation of concerns: Different layers are responsible for different parts of
the system, which improves maintainability.
● Scalability: Each layer can be scaled independently.
● Improved security: Sensitive data can be isolated in the data tier.

2. N-Tier Architecture

N-tier architecture is a more general form of multi-tier architecture, where "N"


represents the number of layers or tiers in the system, and it can vary based on
system complexity. It can be used to describe systems with more than three tiers
(multi-tier being the most basic form with three layers: presentation, business,
and data).

● N-Tier means there could be additional tiers, such as:


○ Web tier: For handling web-related services.
○ Integration tier: For external system communication, such as APIs or
third-party services.
○ Caching tier: For caching frequently accessed data.
○ Security tier: For authentication, authorization, and other security-related
concerns.

In N-tier systems, the number of tiers can be extended as needed to address


more specific needs of the application.

Key Features:

● More flexibility: Systems can have as many tiers as needed, depending on


the requirements.
● Decoupling: Each layer or tier is decoupled from the others, allowing for
more flexible and independent development.
● Complex applications: N-tier architectures are ideal for large and complex
applications that need to handle multiple concerns, such as security, load
balancing, and caching.

Comparison:

Aspect Multi-Tier N-Tier Architecture


Architecture

Number of Typically 3 layers Can have multiple layers (e.g.,


Layers (Presentation, Business Presentation, Business, Data,

8
Logic, Data) Caching, Security, etc.)

Flexibility Less flexible (3 main More flexible (can be extended


layers) with more layers)

Complexity Suitable for simpler Suitable for complex, large-scale


applications applications

Separation Basic separation of Higher degree of separation, with


of Concerns concerns specialized layers for different
concerns

Scalability Scalable but may be Highly scalable, as layers can be


limited to 3 layers added to handle specific needs

Basic internet protocols

The basic internet protocols are essential rules and standards that govern the
communication and functioning of the internet. These protocols allow devices to

9
communicate with each other, transfer data, and enable web services. Here's a
breakdown of some of the core internet protocols:

1. Transmission Control Protocol (TCP)

● Purpose: TCP is a connection-oriented protocol that ensures reliable


communication between devices on a network.
● Key Features:
○ Reliable data transfer by establishing a connection between the sender and
receiver before data is transmitted.
○ Ensures data is delivered in order and without errors by performing error-
checking and retransmission of lost packets.
● Use: It is used for applications where data integrity and order are important,
such as web browsing (HTTP/HTTPS), file transfers (FTP), and email.

2. Internet Protocol (IP)

● Purpose: IP is a connectionless protocol that is responsible for addressing


and routing data packets between devices across different networks.
● Key Features:
○ IP assigns unique addresses to each device on a network (IP addresses).
○ It handles routing and forwarding of packets from the source to the
destination based on IP addresses.
● Use: IP is used in virtually all internet communication, including routing
data from one device to another, regardless of the network.

Variants:

● IPv4: The most widely used version, which uses 32-bit addresses.
● IPv6: The newer version with 128-bit addresses, designed to address the
limitations of IPv4, including address exhaustion.

3. Hypertext Transfer Protocol (HTTP)

● Purpose: HTTP is used for transmitting hypertext (web pages) over the
internet.
● Key Features:
○ A stateless protocol, meaning each request from a client to a server is
treated as independent.
○ It operates at the application layer, enabling browsers to fetch web pages
and other resources.
● Use: It is the foundational protocol for web browsing, allowing users to
access websites using URLs (Uniform Resource Locators).

10
Secure version:

● HTTPS: HTTP over SSL/TLS (Secure Sockets Layer/Transport Layer


Security), providing encryption and secure communication.

4. File Transfer Protocol (FTP)

● Purpose: FTP is used for transferring files between a client and a server
over the internet or a local network.
● Key Features:
○ Allows users to upload, download, and manage files on remote servers.
○ Supports both anonymous and authenticated access.
● Use: Commonly used for website management, software distribution, and
file sharing.

Variants:

● SFTP (Secure FTP): FTP over a secure connection using SSH (Secure Shell).
● FTPS: FTP with SSL/TLS encryption.

5. Simple Mail Transfer Protocol (SMTP)

● Purpose: SMTP is used for sending emails between servers.


● Key Features:
○ It defines how email is transferred between mail servers.
○ Typically works with other protocols like IMAP or POP3 to retrieve and
manage emails.
● Use: It is used by email servers to send and relay messages.

6. Post Office Protocol (POP3)

● Purpose: POP3 is used by email clients to retrieve email messages from a


mail server.
● Key Features:
○ Downloads email messages from the server to the client and removes them
from the server (in most cases).
○ Simpler and more straightforward than IMAP.
● Use: POP3 is used when users need offline access to their email or when
they want to manage their email on a single device.

7. Internet Message Access Protocol (IMAP)

● Purpose: IMAP is another email retrieval protocol that allows email clients
to access and manage messages stored on a mail server.

11
● Key Features:
○ Keeps email messages on the server, allowing synchronization across
multiple devices.
○ Supports folders and more advanced email management features.
● Use: IMAP is used for users who need to access their email from multiple
devices or locations.

8. Dynamic Host Configuration Protocol (DHCP)

● Purpose: DHCP is used to automatically assign IP addresses to devices on


a network.
● Key Features:
○ Simplifies network configuration by automatically providing devices with IP
addresses, gateway information, and DNS server details.
○ Reduces manual configuration and errors.
● Use: DHCP is commonly used in home and enterprise networks to assign IP
addresses to devices such as computers, smartphones, and printers.

9. Domain Name System (DNS)

● Purpose: DNS is responsible for translating human-readable domain names


(e.g., www.example.com) into IP addresses (e.g., 192.168.1.1).
● Key Features:
○ Acts like a phonebook for the internet, translating domain names to IP
addresses so that computers can locate each other.
○ Supports caching to improve efficiency and reduce lookup times.
● Use: Every time a user accesses a website, DNS is used to resolve the
domain name to the correct IP address for the server hosting the site.

10. Secure Sockets Layer / Transport Layer Security (SSL/TLS)

● Purpose: SSL/TLS are cryptographic protocols designed to provide secure


communication over a network.
● Key Features:
○ SSL was the predecessor of TLS, but both provide encryption and ensure
data integrity and authentication.
○ TLS is commonly used to secure HTTP traffic, turning it into HTTPS.
● Use: SSL/TLS is widely used to secure sensitive data in transit, such as
credit card details, login credentials, and personal information.

Summary of Key Internet Protocols

12
Protoc Purpose Primary Use
ol

TCP Reliable data Ensures reliable, ordered delivery


transmission of data

IP Addressing and routing Assigns addresses and routes


packets packets

HTTP Web page transfer Browsing the web, loading


websites

FTP File transfer Uploading/downloading files

SMTP Sending email Email transmission between


servers

POP3 Email retrieval Downloading email from a server

IMAP Email retrieval Accessing email stored on a


server

DHCP Dynamic IP address Automatic assignment of IP


allocation addresses

DNS Domain name resolution Translating domain names to IP


addresses

SSL/TL Secure communication Encrypting data for secure

13
S transfer

These protocols are foundational to the functioning of the internet, enabling a


wide range of applications and services to operate effectively and securely.

World Wide Web (WWW)


The World Wide Web (WWW), often simply referred to as the Web, is a vast,
interconnected system of information accessible via the internet. It enables users
to access a wide variety of resources such as websites, documents, multimedia,
and services, through web browsers and other technologies. The Web is based on
a client-server model, where users interact with web content hosted on remote
servers.

Key Components of the World Wide Web

1. Web Browsers:
○ A web browser is a software application used to access and navigate the
World Wide Web. Examples include Google Chrome, Mozilla Firefox, Microsoft
Edge, and Safari.
○ Web browsers render HTML content (web pages), display images, run
scripts, and handle other web technologies to provide an interactive experience.
2. Web Servers:
○ A web server is a computer system that hosts web content and serves it to
users upon request.
○ Web servers respond to HTTP requests from browsers, sending back the
requested web pages (HTML documents, images, videos, etc.).
3. Web Pages:
○ A web page is a document that can be viewed in a browser. It is typically
written in HTML (Hypertext Markup Language) and may include other
technologies like CSS (Cascading Style Sheets) for design and JavaScript for
interactivity.
○ Web pages are linked together by hyperlinks, which are clickable
references to other pages or resources.
4. URLs (Uniform Resource Locators):
○ A URL is the address used to access resources on the web. It specifies the
protocol (HTTP/HTTPS), the domain name (e.g., www.example.com), and the
path to the specific resource (e.g., /about-us).
○ A typical URL looks like: https://www.example.com/page1.html.
5. Hyperlinks:
14
○ Hyperlinks are clickable elements in web pages that allow users to
navigate from one page to another. They are usually text or images that, when
clicked, take the user to a different web address (URL).
6. HTML (Hypertext Markup Language):
○ HTML is the foundational language for creating web pages. It structures
content with elements like headings, paragraphs, links, and images.
○ It forms the basic skeleton of a web page.
7. CSS (Cascading Style Sheets):
○ CSS is used to control the layout, design, and presentation of web pages. It
defines how HTML elements should be displayed (e.g., font style, colors, spacing,
etc.).
8. JavaScript:
○ JavaScript is a programming language that adds interactivity and dynamic
behavior to web pages. It is commonly used for features like form validation,
animations, and real-time updates.

How the World Wide Web Works

1. Request-Response Model:
○ When a user enters a URL into their browser or clicks a link, a request is
sent over the internet to the corresponding web server.
○ The web server processes the request and sends back the requested data,
typically an HTML page along with other resources (images, videos, CSS files,
etc.).
○ The browser then processes the received data and displays the page to the
user.
2. Client-Server Interaction:
○ The client (user's browser) sends a request for a specific web page to the
server, which hosts the web content.
○ The server processes the request, retrieves the requested data (such as
HTML documents, images, etc.), and sends it back to the client.
3. Protocols:
○ The Web relies on HTTP (Hypertext Transfer Protocol) or its secure version,
HTTPS (HTTP Secure), to facilitate communication between browsers (clients)
and web servers.
○ When a user navigates to a URL starting with "https://", the connection is
encrypted using SSL/TLS for security.
4. Rendering:
○ Once the browser receives the HTML document and associated resources, it
uses its rendering engine to display the page. It interprets the HTML, applies
styles from CSS, and executes JavaScript to create the interactive experience.

Evolution of the World Wide Web


15
1. Web 1.0 (The Static Web):
○ Web 1.0 refers to the early stage of the internet, where websites were
static and mainly consisted of simple, read-only content. Users could view
information but could not interact or contribute easily.
○ Websites were built using basic HTML and lacked interactivity.
2. Web 2.0 (The Social Web):
○ Web 2.0 represents the shift towards more dynamic, interactive websites.
This era saw the rise of social media platforms, blogs, wikis, and user-generated
content.
○ Websites became more collaborative, allowing users to interact, share
content, and communicate in real time.
3. Web 3.0 (The Semantic Web):
○ Web 3.0 is an evolving concept that envisions a smarter, more intuitive
web that better understands users’ needs through artificial intelligence (AI),
machine learning, and data processing.
○ It includes technologies like semantic web, blockchain, and
virtual/augmented reality (VR/AR), offering more personalized experiences.

Key Technologies Behind the World Wide Web

● HTTP/HTTPS: Protocols used for transferring data between clients and


servers.
● HTML/CSS: Markup and styling languages for creating and designing web
content.
● JavaScript: Scripting language that adds interactivity to web pages.
● APIs (Application Programming Interfaces): Allow applications to
communicate and share data with each other. Many web services provide APIs to
allow third-party developers to interact with their platforms.
● Web Servers (Apache, Nginx): Servers that host web content and deliver
it to users.
● Databases (MySQL, MongoDB): Used to store and retrieve data for
dynamic websites and web applications.

HTML

What is HTML?

● HTML stands for Hyper Text Markup Language


● HTML is the standard markup language for creating Web pages
● HTML describes the structure of a Web page
● HTML consists of a series of elements
● HTML elements tell the browser how to display the content

16
● HTML elements label pieces of content such as "this is a heading", "this is a
paragraph", "this is a link", etc.

A Simple HTML Document

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>

Example Explained

● The <!DOCTYPE html> declaration defines that this document is an HTML5


document
● The <html> element is the root element of an HTML page
● The <head> element contains meta information about the HTML page
● The <title> element specifies a title for the HTML page (which is shown in
the browser's title bar or in the page's tab)
● The <body> element defines the document's body, and is a container for all
the visible contents, such as headings, paragraphs, images, hyperlinks, tables,
lists, etc.
● The <h1> element defines a large heading
● The <p> element defines a paragraph

What is an HTML Element?

An HTML element is defined by a start tag, some content, and an end tag:

<tagname> Content goes here... </tagname>

The HTML element is everything from the start tag to the end tag:

<h1>My First Heading</h1>

<p>My first paragraph.</p>

17
Start tag Element content End tag

<h1> My First Heading </h1>

<p> My first paragraph. </p>

<br> none none

The <!DOCTYPE> Declaration


The <!DOCTYPE> declaration represents the document type, and helps browsers
to display web pages correctly.

It must only appear once, at the top of the page (before any HTML tags).

The <!DOCTYPE> declaration is not case sensitive.

The <!DOCTYPE> declaration for HTML5 is:

<!DOCTYPE html>

HTML Headings
HTML headings are defined with the <h1> to <h6> tags.

<h1> defines the most important heading. <h6> defines the least important
heading:

Example

18
<h1>This is heading 1</h1>

<h2>This is heading 2</h2>

<h3>This is heading 3</h3>

HTML Paragraphs
HTML paragraphs are defined with the <p> tag:

Example

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

HTML Links
HTML links are defined with the <a> tag:

Example

<a href="https://www.w3schools.com">This is a link</a>

The link's destination is specified in the href attribute.

Attributes are used to provide additional information about HTML elements.

HTML Images
19
HTML images are defined with the <img> tag.

The source file (src), alternative text (alt), width, and height are provided as
attributes:

Example

<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">

HTML Elements
The HTML element is everything from the start tag to the end tag:

<tagname>Content goes here...</tagname>

Examples of some HTML elements:

<h1>My First Heading</h1>

<p>My first paragraph.</p>

Start tag Element content End tag

<h1> My First Heading </h1>

<p> My first paragraph. </p>

<br> none none

Note: Some HTML elements have no content (like the <br> element). These elements
are called empty elements. Empty elements do not have an end tag!

20
Nested HTML Elements
HTML elements can be nested (this means that elements can contain other
elements).

All HTML documents consist of nested HTML elements.

The following example contains four HTML elements (<html>, <body>, <h1> and
<p>):

Example

<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>

Never Skip the End Tag


Some HTML elements will display correctly, even if you forget the end tag:

Example

<html>
<body>

<p>This is a paragraph
<p>This is a paragraph

</body>
</html>

Empty HTML Elements


21
HTML elements with no content are called empty elements.

The <br> tag defines a line break, and is an empty element without a closing tag:

Example : <p>This is a <br> paragraph with a line break.</p>

HTML Attributes
● All HTML elements can have attributes
● Attributes provide additional information about elements
● Attributes are always specified in the start tag
● Attributes usually come in name/value pairs like: name="value"

The href Attribute


The <a> tag defines a hyperlink. The href attribute specifies the URL of the page
the link goes to:

Example

<a href="https://www.w3schools.com">Visit W3Schools</a>

The src Attribute


The <img> tag is used to embed an image in an HTML page. The src attribute
specifies the path to the image to be displayed:

Example : <img src="img_girl.jpg">

There are two ways to specify the URL in the src attribute:

1. Absolute URL - Links to an external image that is hosted on another website.


Example: src="https://www.w3schools.com/images/img_girl.jpg".
22
Notes: External images might be under copyright. If you do not get permission to
use it, you may be in violation of copyright laws. In addition, you cannot control
external images; it can suddenly be removed or changed.

2. Relative URL - Links to an image that is hosted within the website. Here, the
URL does not include the domain name. If the URL begins without a slash, it will
be relative to the current page. Example: src="img_girl.jpg". If the URL begins
with a slash, it will be relative to the domain. Example:
src="/images/img_girl.jpg".

Tip: It is almost always best to use relative URLs. They will not break if you
change domain.

The width and height Attributes


The <img> tag should also contain the width and height attributes, which specify
the width and height of the image (in pixels):

Example : <img src="img_girl.jpg" width="500" height="600">

The alt Attribute


The required alt attribute for the <img> tag specifies an alternate text for an
image, if the image for some reason cannot be displayed. This can be due to a
slow connection, or an error in the src attribute, or if the user uses a screen
reader.

Example : <img src="img_girl.jpg" alt="Girl with a jacket">

See what happens if we try to display an image that does not exist: <img
src="img_typo.jpg" alt="Girl with a jacket">

The style Attribute

23
The style attribute is used to add styles to an element, such as color, font, size,
and more.

Example : <p style="color:red;">This is a red paragraph.</p>

HTML Horizontal Rules


The <hr> tag defines a thematic break in an HTML page, and is most often
displayed as a horizontal rule.

The <hr> element is used to separate content (or define a change) in an HTML
page:

Example

<h1>This is heading 1</h1>


<p>This is some text.</p>
<hr>
<h2>This is heading 2</h2>
<p>This is some other text.</p>
<hr>
HTML Line Breaks
The HTML <br> element defines a line break.
Use <br> if you want a line break (a new line) without starting a new paragraph:
Example :
<p>This is<br>a paragraph<br>with line breaks.</p>
The <br> tag is an empty tag, which means that it has no end tag.

The Poem Problem


This poem will display on a single line:
Example
<p>
My Bonnie lies over the ocean.

24
My Bonnie lies over the sea.

My Bonnie lies over the ocean.

Oh, bring back my Bonnie to me.


</p>

Solution - The HTML <pre> Element


The HTML <pre> element defines preformatted text.
The text inside a <pre> element is displayed in a fixed-width font (usually
Courier), and it preserves both spaces and line breaks:
Example
<pre>
My Bonnie lies over the ocean.

My Bonnie lies over the sea.

My Bonnie lies over the ocean.

Oh, bring back my Bonnie to me.


</pre>

HTML Formatting Elements


Formatting elements were designed to display special types of text:

● <b> - Bold text


● <strong> - Important text
● <i> - Italic text
● <em> - Emphasized text
● <mark> - Marked text
● <small> - Smaller text
● <del> - Deleted text
● <ins> - Inserted text
● <sub> - Subscript text
25
● <sup> - Superscript text

HTML <b> and <strong> Elements


The HTML <b> element defines bold text, without any extra importance.

Example : <b>This text is bold</b>

The HTML <strong> element defines text with strong importance. The content
inside is typically displayed in bold.

Example : <strong>This text is important!</strong>

HTML <i> and <em> Elements


The HTML <i> element defines a part of text in an alternate voice or mood. The
content inside is typically displayed in italic.

Tip: The <i> tag is often used to indicate a technical term, a phrase from another
language, a thought, a ship name, etc.

Example : <i>This text is italic</i>

The HTML <em> element defines emphasized text. The content inside is typically
displayed in italic.

Tip: A screen reader will pronounce the words in <em> with an emphasis, using
verbal stress.

Example : <em>This text is emphasized</em>

HTML <small> Element


The HTML <small> element defines smaller text:
26
Example : <small>This is some smaller text.</small>

HTML <mark> Element


The HTML <mark> element defines text that should be marked or highlighted:

Example: <p>Do not forget to buy <mark>milk</mark> today.</p>

HTML <del> Element


The HTML <del> element defines text that has been deleted from a document.
Browsers will usually strike a line through deleted text:

Example : <p>My favorite color is <del>blue</del> red.</p>

HTML <ins> Element


The HTML <ins> element defines a text that has been inserted into a document.
Browsers will usually underline inserted text:

Example : <p>My favorite color is <del>blue</del> <ins>red</ins>.</p>

HTML <sub> Element


The HTML <sub> element defines subscript text. Subscript text appears half a
character below the normal line, and is sometimes rendered in a smaller font.
Subscript text can be used for chemical formulas, like H2O:

Example : <p>This is <sub>subscripted</sub> text.</p>

HTML <sup> Element


27
The HTML <sup> element defines superscript text. Superscript text appears half a
character above the normal line, and is sometimes rendered in a smaller font.
Superscript text can be used for footnotes, like WWW[1]:

Example : <p>This is <sup>superscripted</sup> text.</p>

HTML Text Formatting Elements

Tag Description

<b> Defines bold text

<em> Defines emphasized text

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

<small> Defines smaller text

<strong> Defines important text

<sub> Defines subscripted text

<sup> Defines superscripted text

<ins> Defines inserted text

28
<del> Defines deleted text

<mark> Defines marked/highlighted text

HTML Comment Tag

You can add comments to your HTML source by using the following syntax:
<!-- Write your comments here -->
Notice that there is an exclamation point (!) in the start tag, but not in the end
tag.
Note: Comments are not displayed by the browser, but they can help document your
HTML source code.

Add Comments
With comments you can place notifications and reminders in your HTML code:

Example

<!-- This is a comment -->


<p>This is a paragraph.</p>

<!-- Remember to add more information here -->

Hide Content
Comments can be used to hide content.
This can be helpful if you hide content temporarily:
Example
<p>This is a paragraph.</p>

29
<!-- <p>This is another paragraph </p> -->

<p>This is a paragraph too.</p>


You can also hide more than one line. Everything between the <!-- and the --> will
be hidden from the display.
Example
Hide a section of HTML code:
<p>This is a paragraph.</p>
<!--
<p>Look at this cool image:</p>
<img border="0" src="pic_trulli.jpg" alt="Trulli">
-->
<p>This is a paragraph too.</p>

Hide Inline Content


Comments can be used to hide parts in the middle of the HTML code.

Example : Hide a part of a paragraph: <p>This <!-- great text --> is a


paragraph.</p>

HTML Links - Hyperlinks


HTML links are hyperlinks.

You can click on a link and jump to another document.

When you move the mouse over a link, the mouse arrow will turn into a little hand.

Note: A link does not have to be text. A link can be an image or any other HTML
element!

HTML Links - Syntax


30
The HTML <a> tag defines a hyperlink. It has the following syntax:
<a href="url">link text</a>
The most important attribute of the <a> element is the href attribute, which
indicates the link's destination.
The link text is the part that will be visible to the reader.
Clicking on the link text, will send the reader to the specified URL address.
Example
This example shows how to create a link to W3Schools.com:
<a href="https://www.w3schools.com/">Visit W3Schools.com!</a>

By default, links will appear as follows in all browsers:

● An unvisited link is underlined and blue


● A visited link is underlined and purple
● An active link is underlined and red

HTML Links - The target Attribute


By default, the linked page will be displayed in the current browser window. To
change this, you must specify another target for the link.

The target attribute specifies where to open the linked document.

The target attribute can have one of the following values:

● _self - Default. Opens the document in the same window/tab as it was


clicked
● _blank - Opens the document in a new window or tab
● _parent - Opens the document in the parent frame
● _top - Opens the document in the full body of the window

Example : Use target="_blank" to open the linked document in a new


browser window or tab:

<a href="https://www.w3schools.com/" target="_blank">Visit W3Schools!</a>

Absolute URLs vs. Relative URLs


31
Both examples above are using an absolute URL (a full web address) in the href
attribute.

A local link (a link to a page within the same website) is specified with a relative
URL (without the "https://www" part):

Example
<h2>Absolute URLs</h2>
<p><a href="https://www.w3.org/">W3C</a></p>
<p><a href="https://www.google.com/">Google</a></p>
<h2>Relative URLs</h2>
<p><a href="html_images.asp">HTML Images</a></p>
<p><a href="/css/default.asp">CSS Tutorial</a></p>

HTML Links - Use an Image as a Link


To use an image as a link, just put the <img> tag inside the <a> tag:

Example
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;">
</a>

Link to an Email Address


Use mailto: inside the href attribute to create a link that opens the user's email
program (to let them send a new email):
Example
<a href="mailto:[email protected]">Send email</a>

Button as a Link
To use an HTML button as a link, you have to add some JavaScript code.
JavaScript allows you to specify what happens at certain events, such as a click of
a button:
Example
<button onclick="document.location='default.asp'">HTML Tutorial</button>
32
HTML Tables
A table in HTML consists of table cells inside rows and columns.
Example
A simple HTML table:
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>

Table Cells
Each table cell is defined by a <td> and a </td> tag.
td stands for table data.

33
Everything between <td> and </td> are the content of the table cell.

Example
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>

Table Rows
Each table row starts with a <tr> and ends with a </tr> tag.
tr stands for table row.

Example
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>

Table Headers
Sometimes you want your cells to be table header cells. In those cases use the <th>
tag instead of the <td> tag:
th stands for table header.
34
Example
Let the first row be table header cells:
<table>
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>

HTML Table Tags


Tag Description

<table> Defines a table

<th> Defines a header cell in a table

<tr> Defines a row in a table

<td> Defines a cell in a table

35
<caption> Defines a table caption

<colgroup Specifies a group of one or more columns in a table for


> formatting

<col> Specifies column properties for each column within a


<colgroup> element

<thead> Groups the header content in a table

<tbody> Groups the body content in a table

<tfoot> Groups the footer content in a table

How To Add a Border


To add a border, use the CSS border property on table, th, and td elements:

Example
table, th, td {
border: 1px solid black;
}
The following values are allowed:
● dotted
● dashed
● solid

36
● double
● groove
● ridge
● inset
● outset
● none
● hidden

HTML Table Padding & Spacing


HTML tables can adjust the padding inside the cells, and also the space between
the cells.

h h h
e e e
l l l
l l l
o o o

h h h
e e e
l l l
l l l
o o o

h h h
e e e
l l l
l l l
o o o

hello hello hello

37
hello hello hello

hello hello hello

HTML Table - Cell Padding


Cell padding is the space between the cell edges and the cell content.
By default the padding is set to 0.
To add padding on table cells, use the CSS padding property:

Example
th, td {
padding: 15px;
}
To add padding only above the content, use the padding-top property.
And the others sides with the padding-bottom, padding-left, and padding-right
properties:

Example
th, td {
padding-top: 10px;
padding-bottom: 20px;
padding-left: 30px;
padding-right: 40px;
}

HTML Table - Cell Spacing


Cell spacing is the space between each cell.
By default the space is set to 2 pixels.
To change the space between table cells, use the CSS border-spacing property on
the table element:

Example
38
table {
border-spacing: 30px;
}

HTML Table Colspan &


Rowspan
HTML tables can have cells that span over multiple rows and/or columns.

NAME

APRIL

2022

39
FIESTA

HTML Table - Colspan


To make a cell span over multiple columns, use the colspan attribute:

Example
<table>
<tr>
<th colspan="2">Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>43</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>57</td>
</tr>
</table>

HTML Table - Rowspan


To make a cell span over multiple rows, use the rowspan attribute:

Example
<table>

40
<tr>
<th>Name</th>
<td>Jill</td>
</tr>
<tr>
<th rowspan="2">Phone</th>
<td>555-1234</td>
</tr>
<tr>
<td>555-8745</td>
</tr>
</table>

HTML Table Colgroup


If you want to style the two first columns of a table, use the <colgroup> and <col>
elements.

MON TUE WED THU FRI SAT SUN

1 2 3 4 5 6 7

8 9 10 11 12 13 14

15 16 17 18 19 20 21

22 23 24 25 26 27 28

The <colgroup> element should be used as a container for the column specifications.
Each group is specified with a <col> element.
The span attribute specifies how many columns that get the style.
The style attribute specifies the style to give the columns.

Example
41
<table>
<colgroup>
<col span="2" style="background-color: #D6EEEE">
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
...

HTML Lists
HTML lists allow web developers to group a set of related items in lists.

Example
An unordered HTML list:
● Item
● Item
● Item
● Item
An ordered HTML list:
1. First item
2. Second item
3. Third item
4. Fourth item

Unordered HTML List


An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
The list items will be marked with bullets (small black circles) by default:

42
Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

Ordered HTML List


An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items will be marked with numbers by default:

Example
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

HTML Description Lists


HTML also supports description lists.
A description list is a list of terms, with a description of each term.
The <dl> tag defines the description list, the <dt> tag defines the term (name), and
the <dd> tag describes each term:

Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>

43
Unordered HTML List - Choose List Item
Marker
The CSS list-style-type property is used to define the style of the list item marker. It
can have one of the following values:

Value Description

disc Sets the list item marker to a bullet (default)

circle Sets the list item marker to a circle

square Sets the list item marker to a square

none The list items will not be marked

Disc
Example - Disc
<ul style="list-style-type:disc;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

Nested HTML Lists


Lists can be nested (list inside list):

Example
<ul>
<li>Coffee</li>
<li>Tea

44
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>

Horizontal List with CSS


HTML lists can be styled in many different ways with CSS.
One popular way is to style a list horizontally, to create a navigation menu:

Example
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333333;
}

li {
float: left;
}

li a {
display: block;
color: white;
text-align: center;
45
padding: 16px;
text-decoration: none;
}

li a:hover {
background-color: #111111;
}
</style>
</head>
<body>

<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>

</body>
</html>

Ordered HTML List - The Type Attribute


The type attribute of the <ol> tag, defines the type of the list item marker:

Type Description

type="1" The list items will be numbered with numbers (default)

type="A" The list items will be numbered with uppercase letters

type="a" The list items will be numbered with lowercase letters

type="I" The list items will be numbered with uppercase roman numbers

46
type="i" The list items will be numbered with lowercase roman numbers

Numbers
Numbers:
<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

HTML Iframes
An HTML iframe is used to display a web page within a web page.

HTML Iframe Syntax


The HTML <iframe> tag specifies an inline frame.
An inline frame is used to embed another document within the current HTML
document.

Syntax
<iframe src="url" title="description"></iframe>
Tip: It is a good practice to always include a title attribute for the <iframe>. This is
used by screen readers to read out what the content of the iframe is.

Iframe - Set Height and Width


Use the height and width attributes to specify the size of the iframe.
The height and width are specified in pixels by default:

Example

47
<iframe src="demo_iframe.htm" height="200" width="300" title="Iframe
Example"></iframe>
Or you can add the style attribute and use the CSS height and width properties:

Example
<iframe src="demo_iframe.htm" style="height:200px;width:300px;" title="Iframe
Example"></iframe>

Iframe - Remove the Border


By default, an iframe has a border around it.
To remove the border, add the style attribute and use the CSS border property:

Example
<iframe src="demo_iframe.htm" style="border:none;" title="Iframe
Example"></iframe>

Iframe - Target for a Link


An iframe can be used as the target frame for a link.
The target attribute of the link must refer to the name attribute of the iframe:

Example
<iframe src="demo_iframe.htm" name="iframe_a" title="Iframe Example"></iframe>

<p><a href="https://www.w3schools.com"
target="iframe_a">W3Schools.com</a></p>

HTML Forms
An HTML form is used to collect user input. The user input is most often sent to a
server for processing.

Example
First name:

48
Last name:

The <form> Element


The HTML <form> element is used to create an HTML form for user input:
<form>
.
form elements
.
</form>
The <form> element is a container for different types of input elements, such as:
text fields, checkboxes, radio buttons, submit buttons, etc.

The <input> Element


The HTML <input> element is the most used form element.
An <input> element can be displayed in many ways, depending on the type attribute.
Here are some examples:

Type Description

<input type="text"> Displays a single-line text input field

<input type="radio"> Displays a radio button (for selecting one of many


choices)

<input Displays a checkbox (for selecting zero or more of


type="checkbox"> many choices)

<input type="submit"> Displays a submit button (for submitting the form)

<input type="button"> Displays a clickable button

Text Fields
49
The <input type="text"> defines a single-line input field for text input.

Example
A form with input fields for text:
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>

Radio Buttons
The <input type="radio"> defines a radio button.
Radio buttons let a user select ONE of a limited number of choices.

Example
A form with radio buttons:
<p>Choose your favorite Web language:</p>

<form>
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
</form>

Checkboxes
The <input type="checkbox"> defines a checkbox.
Checkboxes let a user select ZERO or MORE options of a limited number of choices.

Example
A form with checkboxes:

50
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>

51
191CAC602J - Web Technology

UNIT II : CASCADING STYLE SHEETS AND DOM

Style Sheets: CSS-Introduction to Cascading Style Sheets-FeaturesCore Syntax-


Style Sheets and HTML- Style Rule Cascading and Inheritance-Selectors-CSS
Properties Host Objects: Browsers and the DOM-Introduction to the Document
Object Model DOM History and Levels-Intrinsic Event Handling-Modifying
Element Style- DOM Event Handling.

Style Sheets: CSS-Introduction to Cascading Style


Sheets

CSS Introduction

CSS (Cascading Style Sheets) is a language designed to simplify the process of


making web pages presentable.

 It allows you to apply styles to HTML documents by prescribing colors,


fonts, spacing, and positioning.

 The main advantages are separation of content (in HTML) and styling (in
CSS) and the same CSS rules can be used across all pages and not have
to be rewritten.

 HTML uses tags and CSS uses rule sets.

 CSS styles are applied to the HTML element using selectors.

Why CSS?

 Saves Time: Write CSS once and reuse it across multiple HTML pages.

 Easy Maintenance: Change the style globally with a single modification.

 Search Engine Friendly: Clean coding technique that improves


readability for search engines.

 Superior Styles: Offers a wider array of attributes compared to HTML.


 Offline Browsing: CSS can store web applications locally using offline
cache, allowing offline viewing.

CSS Syntax

CSS consists of style rules that are interpreted by the browser and applied to the
corresponding elements. A style rule set includes a selector and a declaration
block.

 Selector: Targets specific HTML elements to apply styles.

 Declaration: Combination of a property and its corresponding value.

 The selector points to the HTML element that you want to style.

 The declaration block contains one or more declarations separated by


semicolons.

 Each declaration includes a CSS property name and a value, separated by


a colon.

CSS Syntax Breakdown

1. Selectors: Selectors are used to “select” the HTML element you want to
style. It can be an element type (e.g., h1), a class (e.g., .class-name), an
ID (e.g., #id-name), or a combination of these.

1. Type Selector: Targets all elements of a specific type, like h1, p,


div, etc.

2. Class Selector: Targets elements with a specific class.


Example: .my-class { }

3. ID Selector: Targets an element with a specific ID. Example: #my-


id { }

4. Universal Selector: Targets all elements (*).

2. Properties: Properties are the aspects of the selected elements you want
to style (like color, width, height, etc.).

1. color: Defines the text color.

2. background-color: Defines the background color of an element.

3. font-size: Sets the size of the font.

4. margin: Specifies the space around an element.

5. padding: Defines the space between the element’s content and its
border.
3. Values: Values define the specifics of the property you want to apply,
such as a color name, a number (e.g., 16px), or percentages (e.g., 50%).

Cascading Order:

The Cascading Order in CSS is a set of rules that determine which style will be
applied to an element when multiple styles are conflicting. These rules can be
used to achieve a desired layout or design, but understanding how they work is
crucial to effectively use CSS. In this article, we will explore the different
cascading methods that can be used inside the cascading order. First, let’s
understand the basic concept of cascading. The term “cascading” refers to the
way that styles are inherited and applied to elements in a web page. The
cascading order is the order in which styles are applied, with more specific styles
taking precedence over more general styles.

Three main cascading methods are:

 Specificity

 Inheritance

 Order of declaration

Specificity:

This method determines which style should be applied based on the specificity of
the CSS selectors used. More specific selectors (such as using an ID instead of a
class) will take precedence over less specific selectors. This method compares
the specificity of selectors to determine which rule should take precedence. The
more specific a selector is, the higher its specificity value and the more likely it is
to override other styles. The higher the specificity, the higher the priority of the
style. For example, an ID selector (#id) has a higher specificity than a class
selector (.class) or an element selector (element).

Syntax: The specificity of a selector can be calculated by counting the number


of ID selectors (#), class selectors (.), attribute selectors ([attribute]),
and pseudo-elements (::).

Inheritance:

This method determines which style should be applied based on the parent-child
relationship between elements. Styles applied to a parent element will be
inherited by its child elements unless overridden by a more specific style. This
method uses the !important keyword to indicate that a rule should take
precedence over all others. However, it is generally considered best practice to
avoid using !important unless absolutely necessary. Inheritance is the
mechanism by which styles are passed from a parent element to its children’s
elements. The child element inherits the styles of its parent element unless the
styles are explicitly overridden.
Syntax:

/* Parent selector */

body {

/* Styles */

/* Child selector */

p{

/* Styles */

Order of declaration:

This method determines which style should be applied based on the order in
which styles are declared. Styles declared later in the stylesheet will take
precedence over styles declared earlier unless they are overridden by a more
specific style. This method uses the order in which styles are declared to
determine precedence. Styles declared later in the document will override those
declared earlier.

Syntax:

/* Last declared selector */

.class {

/* Styles */

/* Previously declared selector */

.class {

/* Styles */

Using CSS
CSS can be added to HTML documents in 3 ways:

 Inline - by using the style attribute inside HTML elements

 Internal - by using a <style> element in the <head> section


 External - by using a <link> element to link to an external CSS file

The most common way to add CSS, is to keep the styles in external CSS files.
However, in this tutorial we will use inline and internal styles, because this is
easier to demonstrate, and easier for you to try it yourself.

Inline CSS

An inline CSS is used to apply a unique style to a single HTML element.

An inline CSS uses the style attribute of an HTML element.

Internal CSS

An internal CSS is used to define a style for a single HTML page.

An internal CSS is defined in the <head> section of an HTML page, within


a <style> element.

External CSS

An external style sheet is used to define the style for many HTML pages.

To use an external style sheet, add a link to it in the <head> section of each
HTML page.

Inheritance
In CSS, inheritance controls what happens when no value is specified for a
property on an element.

CSS properties can be categorized in two types:

 Inherited properties, which by default are set to the computed value of


the parent element

 Non-inherited properties, which by default are set to initial value of the


property

Refer to any CSS property definition to see whether a specific property inherits
by default ("Inherited: yes") or not ("Inherited: no").

Inherited properties

When no value for an inherited property has been specified on an element, the
element gets the computed value of that property on its parent element. Only
the root element of the document gets the initial value given in the property's
summary.
Non-inherited properties

When no value for a non-inherited property has been specified on an element,


the element gets the initial value of that property (as specified in the property's
summary).

Note: The “inherit” keyword allows authors to explicitly specify inheritance. It


works on both inherited and non-inherited properties.

You can control inheritance for all properties at once using the all shorthand
property, which applies its value to all properties.

CSS Selectors
CSS selectors target the HTML elements on your pages, allowing you to add
styles based on their ID, class, type, attribute, and more. This guide will help
you to understand the intricacies of CSS selectors and their important role in
enhancing the user experience of your web pages. Understanding these
selectors—such as the universal selector, attribute selector, pseudo-class selector,
and combinator selectors—enables more efficient and dynamic web design.

Types of CSS Selectors

CSS Selectors Description

It is used to select the HTML elements


Simple Selectors based on their element name, id,
attributes, etc

Universal Selector Selects all elements on the page.

Targets elements based on their


Attribute Selector
attribute values.
CSS Selectors Description

Selects elements based on their state


Pseudo-Class Selector or position, such as :hover for hover
effects.

Combine selectors to specify


Combinator Selectors relationships between elements, such
as descendants ( ) or child (>).

Selects specific parts of an element,


Pseudo-Element Selector
such as ::before or ::after.

CSS Properties

CSS (Cascading Style Sheets) is a language used to describe a document's


presentation and formatting in HTML or XML. It allows web developers to control
the appearance of elements on a web page. Here are some commonly used CSS
properties. A CSS property styles an aspect of an HTML element. Here are a few
examples:

1. <div style="border: 1px solid black;

2. font-size: 18px; "> Style This </div>

In this example, two CSS properties are applied to the div element: The border
and the font-size properties.

A CSS property declaration consists of a property name and a property value.


The property name comes first, then a colon, and then the value. Here is the
general pattern a CSS property declaration follows:

1. property-name: property-value

If you specify more than one CSS property, each name-value pair is separated
by a semicolon like this:

1. property1 : property-value1;

2. property2 : property-value2;

The last property declaration does not have to end with a semicolon, but it
makes it easier to add more CSS properties without forgetting to put in that
extra semicolon.
Benefits of CSS Properties

CSS properties have several benefits for web development, such as:

o Control over presentation

o Separation of concerns

o Responsive design

o Efficiency and consistency

o Ease of maintenance

o Accessibility

o Animation and interactivity

o Performance optimization

o Modularity and reusability

o Browser compatibility

o Print-friendly styling

o Ease of updating and scalability

o Accessibility enhancements

o Integration with JavaScript

o Simplifies multi-device development

o Faster page rendering

o Maintains semantic structure

Browser

What is Browser Specific CSS?

Browser-specific CSS refers to CSS styles that are written or applied to target
specific web browsers or browser versions, due to the fact that different
browsers may interpret and render CSS rules differently.

As web development has progressed, browser-specific CSS was primarily used to


address inconsistencies in how browsers handled the rendering of web pages,
ensuring cross-browser compatibility.

However, with modern browsers and CSS standards evolving, much of the need
for browser-specific CSS has diminished, but it still exists in certain cases.
Browser-specific CSS rules are usually implemented using vendor prefixes or
specific CSS hacks, allowing developers to apply styles that are only recognized
by particular browsers.

Why apply Browser Specific CSS Code?

Here are the key reasons to apply browser-specific CSS in 1-liner pointers:

 Cross Browser Compatibility: Ensures consistent rendering across


different browsers.

 Legacy Browser Support: Addresses issues with older browsers (e.g.,


Internet Explorer).

 Experimental Features: Handles new, non-standard CSS features


requiring vendor prefixes.

 Bug Workarounds: Fixes browser-specific quirks or rendering bugs.

 Optimized Mobile Rendering: Tailors styles for specific mobile browsers


or devices.

 Fallback for Unsupported Properties: Provides alternative styles for


browsers lacking support for advanced CSS features.

 Performance Optimization: Improves rendering performance on certain


browsers.

DOM-Introduction to the Document Object Model


The Document Object Model, usually referred to as the DOM, is an essential
part of making websites interactive. It is an interface that allows a programming
language to manipulate the content, structure, and style of a website. JavaScript
is the client-side scripting language that connects to the DOM in an internet
browser.

Almost any time a website performs an action, such as rotating between a


slideshow of images, displaying an error when a user attempts to submit an
incomplete form, or toggling a navigation menu, it is the result of JavaScript
accessing and manipulating the DOM. In this article, we will learn what the DOM
is, how to work with the document object, and the difference between HTML
source code and the DOM.

Why is DOM Required?

The DOM is essential because


 Dynamic Content Updates: Without reloading the page, the DOM allows
content updates (e.g., form validation, AJAX responses).

 User Interaction: It makes your webpage interactive (e.g., responding


to button clicks, form submissions).

 Flexibility: Developers can add, modify, or remove elements and styles in


real-time.

 Cross-Platform Compatibility: It provides a standard way for scripts to


interact with web documents, ensuring browser compatibility.

How the DOM Works?

The DOM connects your webpage to JavaScript, allowing you to:

 Access elements (like finding an <h1> tag).

 Modify content (like changing the text of a <p> tag).

 React to events (like a button click).

 Create or remove elements dynamically.

Properties of the DOM

 Node-Based: Everything in the DOM is represented as a node (e.g.,


element nodes, text nodes, attribute nodes).

 Hierarchical: The DOM has a parent-child relationship, forming a tree


structure.

 Live: Changes made to the DOM using JavaScript are immediately


reflected on the web page.

 Platform-Independent: It works across different platforms, browsers,


and programming languages.

What DOM Is Not

 The DOM is not a binary description, as it does not define any binary
source code in its interfaces.

 It does not describe objects in XML or HTML directly; instead, it


represents XML and HTML documents as objects.

 The DOM is not a collection of data structures but an interface that


specifies how objects are represented and manipulated.
 It does not provide contextual significance of objects, meaning it lacks
information about which objects are contextually appropriate or critical
within a document.

Levels of DOM
DOM consisted of multiple levels, each representing different aspect of the
document.

 Level 0: Provides a low-level set of interfaces.

 Level 1: DOM level 1 can be described in two parts: CORE and HTML.

o CORE provides low-level interfaces that can be used to represent


any structured document.

o HTML provides high-level interfaces that can be used to represent


HTML documents.

 Level2: consists of six


specifications: CORE2, VIEWS, EVENTS, STYLE, TRAVERSAL,and RANGE.

o CORE2: extends the functionality of CORE specified by DOM level 1.

o VIEWS: views allows programs to dynamically access and


manipulate the content of the document.

o EVENTS: Events are scripts that are either executed by the


browser when the user reacts to the web page.

o STYLE: allows programs to dynamically access and manipulate the


content of style sheets.

o TRAVERSAL: This allows programs to dynamically traverse the


document.

o RANGE: This allows programs to dynamically identify a range of


content in the document.

 Level 3: consists of five different specifications: CORE3, LOAD and


SAVE, VALIDATION, EVENTS,and XPATH.

o CORE3: extends the functionality of CORE specified by DOM level 2.

o LOAD and SAVE: This allows the program to dynamically load the
content of the XML document into the DOM document and save the
DOM Document into an XML document by serialization.

o VALIDATION: This allows the program to dynamically update the


content and structure of the document while ensuring the document
remains valid.
o EVENTS: extends the functionality of Events specified by DOM
Level 2.

o XPATH: XPATH is a path language that can be used to access the


DOM tree.

Using DOM and Events: Suppose we want to make changes in the document
or stylesheet on a certain event. The event can be the loading of a web page,
selection of any specific element or a form is submitted, etc.

Some common event attributes are as follows.

 Window Event Attributes: These events are triggered for the window
object.

o onload: It fires after the page is finished loading.

o onresize: It fires when the browser window is resized.

 Mouse Events: These are the most common events with basic interaction
of user through the mouse.

o onclick: It fires when a mouse click is triggered on an element.

o onmouseover: It fires when a mouse pointer moves over an


element.

o ondblclick: It fires on a mouse double click on the element

 KeyBoard Events:

o onkeydown: It fires when the user is pressing a specific key

o onkeyup: It fires when a user releases a specific key

Intrinsic Events

An intrinsic event determines when an associated script will run. However, not
every intrinsic event works with every (X)HTML element. This table illustrates
which events and tags work together.

EVENT WORKS WITH WHEN


ONBLUR a, area, button, input, label, select, textarea the visitor
leaves an
element
that was
previousl
y in focus
(see

onfocus

below)

ONCHANGE input, select, text area the visitor


modifies
the value
or
contents
of the
element

ONCLICK All the visitor


elements except applet, base, basefont, br, font, clicks on
frame, frameset, head, html, iframe, meta, para the
m, script, style, title specified
area.

Modifying Element Style

The element.style Attribute:

Each DOM element has a element.style attribute, which is a JavaScript object.


The element.style object has attributes that can be used to read or set style
properties for the DOM element. Any time we have selected a DOM element we
can read or set the values of all CSS properties by referencing
the property name. Here is an example:

html

<button class="btn save">Save</button>

css

.save {

background: blue;

color: white;

font-size: 1.2rem;
font-family: sans-serif;

.btn {

padding: 0.2rem;

border: 1px solid yellow;

background: black;

color: white;

js

let saveButton = document.querySelector('button.save');

console.log(saveButton.style.background); // Prints: "blue"

console.log(saveButton.style.fontSize); // Prints: "1.2rem"

console.log(saveButton.style.fontFamily); // Prints: "sans-serif"

console.log(saveButton.style.border); // Prints: "1px solid yellow"

console.log(saveButton.style.padding); // Prints: "0.2rem"

Looking at the HTML, CSS, and JS above, we can see that the <button> element
has two classes applied to it: .btn and .save. These two classes define several
properties for the visual presentation of the button. In the JavaScript part of the
example, we select the saveButton using a
standard document.querySelector() call. Once we have selected the button
element we can access the element.style attribute to read and print the CSS
properties applied to this element.

We could also change the values dynamically using JavaScript:

saveButton.style.background = "red";

saveButton.style.color = "yellow";

These two lines of JavaScript would alter the background and text color of the
button. We could set these style properties to any valid CSS value and they
would override the existing style in the browser.

DOM Event Handling


DOM event handling is a mechanism that allows developers to detect and
respond to user interactions or changes in the Document Object Model (DOM).
Events represent user actions or system occurrences, such as clicking a button,
typing in a field, or loading a webpage.

Key Concepts in DOM Event Handling

1. EventTypes
Common events include:

o Mouse Events: click, dblclick, mouseover, mouseout, mousedown,


mouseup.

o Keyboard Events: keydown, keyup, keypress.

o Form Events: submit, change, focus, blur.

o Window Events: load, resize, scroll.

2. Event Listeners

o Definition: Functions that wait for specific events to occur on DOM


elements.

o Usage: Use the addEventListener method to attach listeners to


elements.

const button = document.getElementById("myButton");

button.addEventListener("click", () => {

alert("Button clicked!");

});

3. Event Propagation

o Bubbling: Events start from the target element and bubble up to


the root of the DOM.

o Capturing: Events are captured from the root down to the target
element.

o Stopping Propagation: Use event.stopPropagation() to prevent


further propagation.

4. Event Object

o Provides information about the event, such as the target element,


event type, and other metadata.

Example:

document.addEventListener("click", (event) => {

console.log(event.target); // Logs the clicked element


});

5. Default Actions and Prevention

o Some events have default actions, like following a link when clicked.

o Use event.preventDefault() to block these actions.

document.querySelector("a").addEventListener("click", (event) =>


{

event.preventDefault();

console.log("Default action prevented!");

});

Best Practices for DOM Event Handling

 Use addEventListener instead of inline event handlers for better


separation of concerns.

 Remove unnecessary event listeners using removeEventListener to avoid


memory leaks.

 Use event delegation to efficiently handle events for multiple child


elements.

document.getElementById("parent").addEventListener("click", (event) =>

if (event.target.tagName === "BUTTON") {

console.log("Button clicked:", event.target.textContent);

});

Avoid excessive nesting of event handlers to maintain code readability.


191CAC602J - Web Technology

UNIT III : SCRIPTING LANGUAGES


Introduction to JavaScript-JavaScript Statements-Operators-Data Types-
Functions ,Angular JS Basics-Expressions-Filters-Directives-Controllers- JS
Modules-JS Forms. React-Introduction to JSX-Virtual DOM-Setting up your
React JS Development Environment-Creating a simple React Application-
React UI and Forms-Component Life Cycle.

Introduction to JavaScript

JavaScript is a flexible and dynamic programming language primarily used


for creating interactive web applications. Its versatility allows it to run on
both client-side (in the browser) and server-side (via environments like
Node.js). It integrates seamlessly with HTML and CSS, enabling
developers to build robust and engaging applications.

Core Characteristics of JavaScript


1. Single-Threaded:
o JavaScript operates on a single thread, meaning it can
execute only one task at a time. This is manageable for most
tasks but can lead to challenges in handling multiple
operations simultaneously. Features like asynchronous
programming help mitigate this limitation.
2. Interpreted Language:
o Instead of compiling code into machine-readable format
beforehand, JavaScript executes code line by line at runtime,
making it an interpreted language.
3. Dynamically Typed:
o The data type of a variable in JavaScript is determined during
execution (runtime), not at the time of coding. This makes
JavaScript more flexible but can also lead to unexpected
errors.

Key Features of JavaScript

 Client-Side Scripting:
JavaScript runs in the browser, enabling faster responses to user
actions like clicks or form inputs without server communication.
 Versatility:
JavaScript supports a wide range of applications, from simple tasks
like form validation to complex tasks like server management.
 Event-Driven Programming:
JavaScript can react to user actions in real-time, such as updating
the page when a button is clicked.
 Asynchronous Capabilities:
JavaScript can perform tasks (e.g., fetching data) in the background
without interrupting the user experience, thanks to techniques like
Promise and async/await.
 Rich Ecosystem:
Libraries and frameworks like React, Angular, and Vue.js enhance
development efficiency and speed by offering pre-built tools and
components.

Client-Side and Server-Side Nature of JavaScript


1. Client-Side:
o JavaScript interacts with the DOM to manipulate webpage
elements, handle user inputs, and create dynamic experiences.
o Frameworks like AngularJS and ReactJS simplify development.
2. Server-Side:
o JavaScript can be used on servers with tools like Node.js.
o It performs tasks like database operations, file handling, and
response generation.

Programming Paradigms in JavaScript

 Imperative Programming:
o Focuses on controlling how tasks are performed, including
procedural and object-oriented approaches.
o For example, using for loops to iterate through data or
async/await to manage asynchronous operations.
 Declarative Programming:
o Focuses on what should be done without detailing how.
o For example, using arrow functions or higher-order functions
like .map() and .filter().

Applications of JavaScript

 Web Development:
o JavaScript brings interactivity and dynamic behavior to static
webpages. Frameworks like AngularJS enhance this process.
 Web Applications:
o JavaScript powers modern web applications with dynamic
features, often using APIs and libraries like React.
 Server Applications:
o Using Node.js, JavaScript enables server-side scripting and
full-stack development.
 Game Development:
o With HTML5 and libraries like EaseJS, JavaScript allows the
creation of browser-based games.
 Smartwatches:
o PebbleJS enables JavaScript applications on smartwatches,
particularly those requiring internet access.

Limitations of JavaScript
1. Security Risks:
o Vulnerable to attacks like Cross-Site Scripting (XSS), where
malicious scripts exploit website elements like <img> or
<script> tags to steal data.
2. Performance:
o JavaScript is slower than traditional compiled languages for
complex operations. However, for simple tasks in the browser,
performance is usually sufficient.
3. Complexity:
o Writing advanced JavaScript requires understanding
programming concepts and both client-side and server-side
scripting, which can be challenging.
4. Weak Error Handling and Type Checking:
o JavaScript is loosely typed, meaning variables don’t have fixed
types. This flexibility can lead to errors that are harder to
debug due to weak enforcement of type checking.

JavaScript Statements
In JavaScript, a statement is like a complete instruction that tells the
computer to do something. These statements are made up of different
parts: Values, Operators, Keywords, Expressions, and Comments.
Each statement is executed by the browser in the order it appears, line by
line.
Examples:
Semicolons
 Semicolons are used to separate JavaScript statements. They mark
the end of a statement.
 You can put multiple statements on one line if you separate them
with semicolons.
let a, b, c;
a = 2;
b = 3;
c = a + b;
console.log("The value of c is " + c + ".");

Code Blocks
A code block is a group of statements that are enclosed within curly
brackets {}. This allows multiple statements to be executed together.

function myFunction() {
console.log("Hello");
console.log("How are you?");
}

myFunction()

White Space
JavaScript ignores extra spaces in your code. This means you can use
spaces to make your code more readable without affecting how it works.

console.log(10*2);
console.log(10 * 2);

Line Length and Line Breaks


It’s good practice to keep your code lines to around 80 characters. If a
line of code is too long, you can break it up, usually after an operator (like
+, =, etc.).
document.getElementById("geek1").innerHTML = "Hello Geek!";

Keywords
Keywords are reserved words and cannot be used as a variable name. A
JavaScript keyword tells about what kind of operation it will perform.

Keyword Description

var Used to declare a variable

let Used to declare a block variable

const Used to declare a block constant

Used to decide if certain block will


if get executed or not

Executes a block of codes


switch depending on different cases

Executes a block of statements till


for the condition is true

function Used to declare a function

return Used to exit a function

Used to handle errors in a block of


try statements
break Used to terminate a loop

continue Used to continue a loop

JavaScript Operators
Operators in JavaScript are symbols or keywords used to perform
operations on values, variables, or expressions. They form the backbone
of calculations, comparisons, and logical operations in JavaScript.

Types of JavaScript Operators

1. Arithmetic Operators
These operators are used to perform basic mathematical calculations.

Operator Description Example Result

+ Addition 5+3 8

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division 5/3 1.6667

% Modulus (Remainder) 5 % 3 2

** Exponentiation 5 ** 3 125

2. Assignment Operators
These operators assign values to variables.

Operator Description Example Result

= Assignment x=5 x=5

+= Add and assign x += 3 x=x+3


Operator Description Example Result

-= Subtract and assign x -= 3 x=x-3

*= Multiply and assign x *= 3 x=x*3

/= Divide and assign x /= 3 x=x/3

%= Modulus and assign x %= 3 x=x%3

3. Comparison Operators
Used to compare two values and return a Boolean (true or false).

Operator Description Example Result

== Equal to 5 == '5' true

=== Strictly equal (type + value) 5 === '5' false

!= Not equal 5 != '5' false

!== Strictly not equal 5 !== '5' true

> Greater than 5>3 true

< Less than 5<3 false

>= Greater than or equal to 5 >= 5 true

<= Less than or equal to 5 <= 3 false

4. Logical Operators
Used to perform logical operations and combine conditions.

Operator Description Example Result

&& Logical AND true && false false

` ` Logical OR

! Logical NOT !true false


5. Bitwise Operators
Perform operations at the bit level.

Operator Description Example Result

& AND 5&1 1

` ` OR `5

^ XOR 5^1 4

~ NOT ~5 -6

<< Left shift 5 << 1 10

>> Right shift 5 >> 1 2

6. Ternary Operator
The ternary operator is a shorthand for if-else conditions.
 Syntax: condition ? value_if_true : value_if_false
 Example:
 let age = 18;
 let status = age >= 18 ? "Adult" : "Minor";
 console.log(status); // "Adult"

7. String Operators
Used for concatenating strings.

Operator Description Example Result

+ Concatenation 'Hello' + 'World' 'HelloWorld'


8. Type Operators
Used to check or convert types.

Operator Description Example Result

typeof Returns data type typeof 5 'number'

Checks if an object is an instance of arr instanceof


instanceof true
a class Array

9. Unary Operators
Operate on a single operand.

Operator Description Example Result

+ Converts to a number +'5' 5

- Negates the value -5 -5

++ Increment x++ x=x+1

-- Decrement x-- x=x-1

10. Special Operators


 Comma Operator (,):
Evaluates multiple expressions and returns the last.
 let x = (1, 2, 3);
 console.log(x); // 3
 Delete Operator:
Deletes a property from an object.
 let obj = { name: "Alice" };
 delete obj.name;
 console.log(obj); // {}
 Void Operator:
Executes an expression without returning a value.
 console.log(void 0); // undefined

JavaScript Data Types


JavaScript is a dynamically typed language, meaning variables do not
require explicit type declarations and can hold any data type. Data types
in JavaScript can be broadly categorized into Primitive Types and
Object Types.

1. Primitive Data Types


Primitive types are immutable and stored directly in memory. They
represent simple, single values.

Data Type Description Example

Represents both integer and floating-


Number 42, 3.14, -7, NaN
point numbers.

For representing integers larger than 123n,


BigInt
2^53 - 1 or smaller than -(2^53 - 1). BigInt(987654321)

Represents text enclosed in single,


String "Hello", 'World'
double, or backticks (', ", `).

Represents logical values, either true or


Boolean true, false
false.

Denotes a variable that has been


Undefined let x; console.log(x);
declared but not assigned a value.

Represents the intentional absence of


Null let y = null;
any object value.

Represents unique, immutable let sym =


Symbol
identifiers. Symbol('id');

2. Object Types
Object types are collections of key-value pairs and can hold complex data.
Objects:
Objects are containers for storing related data and functions.
let person = { name: "Alice", age: 25, greet: function()
{ console.log("Hi!"); } };
Arrays:
Special objects that store ordered, index-based collections of values.
let colors = ["red", "green", "blue"];
Functions:
JavaScript treats functions as first-class objects.
function greet() { console.log("Hello"); }
Dates:
Represents dates and times.
let today = new Date();
Regular Expressions:
Patterns used for matching character combinations.
let regex = /ab+c/;
Other Object Types:
 Map: Stores key-value pairs with unique keys.
 Set: Stores unique values.
 WeakMap: Like Map but keys must be objects, and they are
weakly referenced.
 WeakSet: Like Set but with weak references.

Type Checking in JavaScript


 typeof Operator:
Returns the data type of a value as a string.
 console.log(typeof 42); // "number"
 console.log(typeof "Hello"); // "string"
 console.log(typeof true); // "boolean"
 console.log(typeof undefined); // "undefined"
 console.log(typeof null); // "object" (quirk in JavaScript)
 console.log(typeof Symbol()); // "symbol"
 instanceof Operator:
Checks if an object is an instance of a specific class or constructor.
 console.log([] instanceof Array); // true
 console.log({} instanceof Object); // true

Dynamic Typing
Variables in JavaScript can change their data type at runtime.
let value = 42; // number
value = "Hello, world!"; // string
value = true; // boolean

Key Differences Between Null and Undefined

Aspect Null Undefined

Type object undefined

Represents the intentional Represents an uninitialized value


Purpose
absence of a value. or missing property.

Example let a = null; let b;

Type Conversion
 Implicit Conversion (Type Coercion):
JavaScript automatically converts one data type to another.
 console.log("5" + 2); // "52" (string concatenation)
 console.log("5" - 2); // 3 (string converted to number)
 Explicit Conversion:
Developers can convert types manually using functions like
Number(), String(), or Boolean().
 let num = Number("42"); // Converts string to number
 let str = String(42); // Converts number to string
 let bool = Boolean(1); // Converts number to boolean (true)

JavaScript Functions
Functions in JavaScript are reusable blocks of code designed to perform a
specific task. They allow developers to structure, reuse, and manage their
code effectively.

Key Features of JavaScript Functions


1. Reusable: Functions can be called multiple times with different
inputs.
2. Encapsulation: Functions encapsulate logic, improving modularity.
3. First-Class Objects: Functions in JavaScript can be assigned to
variables, passed as arguments, and returned from other functions.

Types of Functions
1. Function Declaration
 A named function defined using the function keyword.
 Can be called before its definition due to hoisting.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!

2. Function Expression
 A function assigned to a variable.
 Not hoisted, so it must be defined before use.
const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet("Bob")); // Output: Hello, Bob!

3. Arrow Functions
 A concise syntax introduced in ES6.
 Does not have its own this context, making it ideal for callbacks.
const greet = (name) => `Hello, ${name}!`;
console.log(greet("Charlie")); // Output: Hello, Charlie!

4. Anonymous Functions
 Functions without a name.
 Commonly used as arguments to other functions.
setTimeout(function() {
console.log("This is an anonymous function.");
}, 1000);

5. Immediately Invoked Function Expressions (IIFE)


 Functions executed immediately after their definition.
 Useful for creating isolated scopes.
(function() {
console.log("IIFE executed!");
})();

6. Constructor Functions
 Used to create objects, often with the new keyword.
function Person(name, age) {
this.name = name;
this.age = age;
}
const person1 = new Person("Dave", 30);
console.log(person1.name); // Output: Dave

7. Async Functions
 Introduced in ES8 for handling asynchronous code.
 Use the async keyword and can await promises.
async function fetchData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
}
fetchData();

Function Parameters
Default Parameters
 Provide default values for parameters if no value is passed.
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
console.log(greet()); // Output: Hello, Guest!
Rest Parameters
 Allow a function to accept an indefinite number of arguments as an
array.
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10

Function Return Values


Functions can return values using the return statement.
If no return statement is provided, the function returns undefined.
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // Output: 8

Higher-Order Functions
Functions that take other functions as arguments or return them as
results.
function greetUser(callback) {
callback("Eve");
}
greetUser((name) => console.log(`Hello, ${name}!`)); // Output: Hello,
Eve!

Closures
A closure is a function that remembers its outer scope even after the
outer function has executed.
function counter() {
let count = 0;
return function() {
count++;
return count;
};
}
const increment = counter();
console.log(increment()); // Output: 1
console.log(increment()); // Output: 2

Recursive Functions
A function that calls itself to solve a problem.
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120

Function Scope and “this”


Scope
 Local Scope: Variables declared inside a function are only
accessible within that function.
 Global Scope: Variables declared outside of any function are
accessible throughout the code.
function test() {
let localVar = "I'm local";
console.log(localVar); // Accessible
}
console.log(localVar); // Error: localVar is not defined
“this” Keyword
The value of this depends on how the function is called:
 Default: Refers to the global object (window in browsers).
 Method: Refers to the object calling the method.
 Arrow Functions: Inherits this from the enclosing context.
const obj = {
name: "Alice",
greet() {
console.log(this.name);
}
};
obj.greet(); // Output: Alice

AngularJS Basics

AngularJS is a JavaScript-based open-source front-end framework


developed by Google. It is used to build dynamic, single-page web
applications (SPAs) by extending HTML capabilities and simplifying
application development and testing.

Key Features of AngularJS


1. Two-Way Data Binding
o Automatically synchronizes data between the model
(JavaScript objects) and the view (HTML).
o Changes in the view update the model, and vice versa.
2. <div ng-app>
3. <input ng-model="name" placeholder="Enter your name">
4. <p>Hello, {{ name }}!</p>
5. </div>
6. Dependency Injection (DI)
o AngularJS manages dependencies and injects them where
needed, reducing tightly coupled code.
7. Directives
o Extend HTML by adding custom behavior to elements using
built-in or custom directives like ng-model, ng-repeat, and ng-
bind.
8. MVC Architecture
o Implements a simplified Model-View-Controller (MVC) pattern
to organize and structure code effectively.
9. Templating
o Allows dynamic creation of HTML templates using Angular
expressions ({{ }}).
10. Routing
o Facilitates navigation between different views in a single-page
application.
11. Filters
o Modify or format data displayed in the view without changing
the model.

Core Concepts
1. Modules
Modules group together related components, directives, services, filters,
and configuration settings in an AngularJS application.
var app = angular.module('myApp', []);

2. Directives
Directives are markers on DOM elements (e.g., attributes, elements, or
classes) that tell AngularJS to attach specified behaviors.
Directive Description

ng-app Defines the root element of an AngularJS application.

ng-model Binds input fields to the model.

ng-bind Binds data to HTML elements.

ng-repeat Iterates through arrays or objects.

ng-click Handles click events.

Example:
<div ng-app="myApp" ng-controller="myCtrl">
<p ng-bind="message"></p>
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
</div>

3. Controllers
Controllers manage application logic and interact with the model and view.
app.controller('myCtrl', function($scope) {
$scope.message = "Hello, AngularJS!";
$scope.items = ["Item 1", "Item 2", "Item 3"];
});

4. Scope
The $scope object acts as the glue between the controller and the view. It
contains data and functions used in the application.

5. Filters
Filters transform data in the view. Built-in filters include:
 currency: Formats numbers as currency.
 date: Formats dates.
 uppercase / lowercase: Converts text case.
 filter: Filters an array.
Example:
<p>{{ price | currency }}</p>
<p>{{ date | date:'fullDate' }}</p>

6. Services
Services are reusable components that encapsulate business logic or data
sharing.
Example of creating a service:
app.service('myService', function() {
this.getMessage = function() {
return "Service Message";
};
});

Routing in AngularJS
AngularJS uses the $routeProvider service for configuring routes in SPAs.
Example:
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
});
});

Two-Way Data Binding Example


<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="name">
<p>Your name is: {{ name }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>

Advantages of AngularJS
1. Declarative UI: HTML-based templates make the application more
intuitive.
2. Less Code: Directives and two-way data binding reduce the
amount of JavaScript needed.
3. Easy Testing: Supports unit and end-to-end testing.
4. Modular Architecture: Simplifies code organization and reuse.
Limitations of AngularJS
1. Performance Issues: Can become slow with large applications
due to two-way data binding.
2. Complex Debugging: Debugging AngularJS applications can be
challenging for beginners.
3. Outdated: AngularJS is an older framework, and newer versions
(Angular 2+ or React) are often preferred.

React: Introduction to JSX and Virtual DOM


React is a JavaScript library for building user interfaces. It enables
developers to create dynamic and interactive web applications efficiently
by leveraging components, JSX, and the Virtual DOM.

Introduction to React
 Developed by Facebook, React focuses on building reusable UI
components.
 React is declarative, component-based, and supports building
single-page applications (SPAs).
 React efficiently updates and renders components when data
changes.

JSX: JavaScript XML


What is JSX?
 JSX is a syntax extension for JavaScript that looks similar to HTML.
 It allows developers to write HTML-like code within JavaScript,
making the code more readable and expressive.
 JSX is transpiled to plain JavaScript using tools like Babel before
being executed in the browser.
Features of JSX
1. HTML-Like Syntax: Embeds HTML-like tags in JavaScript code.
2. Expressions: Allows embedding JavaScript expressions within {}.
3. Attributes: Supports setting attributes using JavaScript objects.
4. Conditional Rendering: Implements logic directly in JSX using
expressions like ternary operators.
Example of JSX
import React from 'react';

function Greeting() {
const name = "Kitty";
return <h1>Hello, {name}!</h1>;
}

export default Greeting;


Output:
Hello, Kitty!

Benefits of JSX
 Improved Readability: Combines HTML and JavaScript in one
place.
 Type Safety: Errors in JSX are caught during compilation.
 Rich Syntax: Enables embedding JavaScript logic easily.
 Reactivity: React efficiently updates the UI when data changes.

Virtual DOM
What is the Virtual DOM?
The Virtual DOM is a lightweight, in-memory representation of the actual
DOM. It’s an abstraction layer that React uses to optimize UI updates.
How it Works
1. When the state or props of a component changes, React creates a
Virtual DOM tree to represent the updated UI.
2. React compares the new Virtual DOM with the previous one using a
process called reconciliation.
3. Only the differences (diffs) are identified, and the real DOM is
updated selectively, minimizing performance overhead.

Benefits of the Virtual DOM


1. Performance: Reduces costly direct DOM manipulations.
2. Efficient Updates: Updates only the parts of the DOM that have
changed.
3. Cross-Browser Compatibility: Provides a consistent way of
updating the UI regardless of the browser.
4. Declarative Approach: Developers describe the UI, and React
handles the rendering process efficiently.

Virtual DOM vs. Real DOM

Feature Virtual DOM Real DOM

In-memory representation of Browser's actual DOM


Definition
the DOM. structure.

Faster updates with minimal Slower due to frequent


Performance
changes. direct updates.

Re- Updates only the changed Re-renders the entire UI.


Feature Virtual DOM Real DOM

rendering components.

Used by React for efficient Directly manipulated in


Usage
updates. vanilla JS.

Example: Virtual DOM in Action


import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

return (
<div>
<p>Current Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

export default Counter;


Explanation:
1. When the button is clicked, the state count changes.
2. React updates the Virtual DOM with the new state.
3. The Virtual DOM compares itself with the previous version.
4. React updates only the <p> element in the real DOM, improving
performance.

Setting Up Your React JS Development Environment


To start developing with React, you need to set up a development
environment. Below are the steps for setting up React and creating your
first React application.

1. Install Node.js and npm


 React requires Node.js and npm (Node Package Manager). If
you don't have them installed, download and install them from the
official website:
Node.js
 After installing, verify the installation by checking the versions of
Node.js and npm in your terminal:
node -v
npm -v

2. Install create-react-app
 create-react-app is an official tool from React to set up a new React
project easily.
 To install it globally, use npm:
npm install -g create-react-app

3. Create a React Application


 After installing create-react-app, you can create a new React project
by running the following command:
npx create-react-app my-app
 This will create a folder named my-app with all the necessary files
and configurations.

4. Navigate to Your App Folder


 Once the project is created, navigate to the project folder:
cd my-app
5. Start the Development Server
 To start the React development server and open your app in a web
browser, use the following command:
npm start
This should open your app at http://localhost:3000/.

Creating a Simple React Application

React applications are built using components, which are reusable pieces
of code that represent UI elements.
Example: Simple Counter App
1. App Component: Create a simple React component that displays a
counter and a button to increment it.
 Inside the src folder, open App.js and replace its content with the
following code:
import React, { useState } from 'react';

function App() {
const [count, setCount] = useState(0);

return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default App;
 This is a functional component using the useState hook to
manage the state (count).
 The onClick event of the button increments the counter.
2. Run the app:
o If the server isn't running already, run npm start again, and
open the app in a browser.

React UI and Forms


In React, building UI and handling forms can be done efficiently using
controlled components.

Handling Forms in React


1. Form Handling: In React, form elements like inputs are controlled
components, meaning their value is controlled by the state.

Example: Simple Form Handling


import React, { useState } from 'react';

function Form() {
const [name, setName] = useState('');

const handleSubmit = (e) => {


e.preventDefault();
alert(`Hello, ${name}!`);
};

return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
<button type="submit">Submit</button>
</form>
);
}

export default Form;


Explanation:
 The <input> element's value is controlled by the name state.
 The onChange event updates the state whenever the user types in
the input.
 The form is submitted using handleSubmit, which prevents the
default form submission behavior and displays the entered name in
an alert.

Component Life Cycle


React components have a life cycle that governs how they are created,
updated, and destroyed. There are three main phases: Mounting,
Updating, and Unmounting.
Class Components Life Cycle Methods:

In class components, React provides lifecycle methods that are invoked


at different stages of the component’s life.
1. Mounting: When a component is created and added to the DOM.
o componentDidMount(): Called once the component is
mounted.
2. Updating: When a component's state or props change.
o shouldComponentUpdate(): Determines if a component
should re-render.
o componentDidUpdate(): Called after the component updates.
3. Unmounting: When a component is removed from the DOM.
o componentWillUnmount(): Used to clean up resources.

Example of a Class Component with Lifecycle Methods


import React, { Component } from 'react';

class Timer extends Component {


constructor(props) {
super(props);
this.state = {
seconds: 0,
};
}

componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}

tick() {
this.setState({
seconds: this.state.seconds + 1,
});
}

render() {
return <h1>Timer: {this.state.seconds}s</h1>;
}
}

export default Timer;

Explanation:
 componentDidMount is called after the component is added to the
DOM, where we set up the timer.
 componentWillUnmount is called before the component is
removed from the DOM, which cleans up the interval.

Functional Components Life Cycle with Hooks

In modern React, functional components use hooks to manage the


component life cycle. The useEffect hook is used to perform actions
similar to lifecycle methods in class components.
1. useEffect Hook: It runs after the component renders and is used
for side effects like data fetching, subscriptions, or manual DOM
manipulations.
Example Using useEffect Hook
import React, { useState, useEffect } from 'react';

function Timer() {
const [seconds, setSeconds] = useState(0);

useEffect(() => {
const timerID = setInterval(() => setSeconds(prevSeconds =>
prevSeconds + 1), 1000);

// Cleanup function to clear the interval


return () => clearInterval(timerID);
}, []); // Empty dependency array means this effect runs only once (like
componentDidMount)

return <h1>Timer: {seconds}s</h1>;


}

export default Timer;

Explanation:
 The useEffect hook runs once when the component mounts and sets
up the interval to increment the seconds.
 The cleanup function inside useEffect is called when the component
unmounts, which clears the interval.
Conclusion
 React provides an efficient way to build interactive user interfaces
using components.
 JSX allows you to write HTML-like syntax within JavaScript, making
the development process more intuitive.
 React's component life cycle is essential for managing side effects
and cleaning up resources.
 Using functional components and hooks is the modern approach
for managing component state and life cycle in React applications.
191CAC602J - Web Technology

UNIT IV : SERVER SIDE PROGRAMMING

Java Servlets- Architecture -Overview-A Servlet-Generating Dynamic


Content-Life Cycle Parameter Data Sessions- JSP Technology
Introduction-JSP Architecture -Running JSP Applications-Basic JSPClasses
and JSP tags - Databases and JSP- Representing Web Data.

What is a Java Servlet?


Java Servlets are Java programs that run on a Java-enabled web server
or application server. They are primarily used to handle client requests
received from a web server, process those requests, generate a response,
and then send the response back to the web server. Servlets enable
dynamic web content creation and are a core component of Java web
application development.

Properties of Java Servlets


The key properties of Java Servlets are:

● Server-Side Execution: Servlets operate on the server side, making


them capable of efficiently managing client-server communication.

● Request Handling: Servlets can handle complex requests received


from the web server, including processing form data, session
management, and database interactions.
Architecture -Overview
The servlet architecture operates on a request-response model where
clients, typically web browsers, send HTTP requests to a web server. The
server forwards these requests to the servlet container, which processes
them via servlets. The servlets generate dynamic content, interact with
databases if necessary, and send responses back to the clients.

1
191CAC602J - Web Technology

Components of Servlet Architecture


1. Web Browser (Client):
o The web browser acts as the front end for user interactions.
o Users send HTTP requests (e.g., GET, POST) through the
browser.
o Once the servlet processes the request, the browser displays
the response.
2. Web Server:
o The web server (e.g., Apache HTTP Server) acts as an
intermediary between the client and the servlet container.
o It listens for incoming HTTP requests and forwards them to
the servlet container.
o After the servlet processes the request, the web server relays
the response back to the browser.
3. Servlet Container:
o The servlet container (also called a servlet engine) is a
runtime environment for Java Servlets.
o Examples: Apache Tomcat, Jetty, GlassFish.
o Key responsibilities:

2
▪ Servlet Lifecycle Management: Handles initialization,
execution, and destruction of servlets.

▪ Request Processing: Matches requests to the


appropriate servlet.

▪ Multithreading: Creates a thread for each client


request to improve performance.

191CAC602J - Web Technology


o It provides a Java runtime and manages communication
between the web server, servlets, and other resources (like a
database).
4. Servlets:
o Servlets are Java classes that extend either GenericServlet or
HttpServlet.
o They are the core components that handle the logic for
processing requests and generating responses.
o Key Tasks of Servlets:

▪ Parse HTTP requests.

▪ Execute business logic (e.g., querying a database or


processing user input).

▪ Generate dynamic responses like HTML, JSON, or XML.


5. Database:
o Servlets can interact with a backend database using JDBC
(Java Database Connectivity).
o Typical tasks:

▪ Querying data (e.g., retrieving user details).

▪ Updating records (e.g., saving user feedback).

▪ Handling large-scale transactions efficiently.


Workflow of Servlet Architecture
The servlet architecture follows this step-by-step process:

3
1. Client Request:
o A user interacts with a web browser (client) and sends an
HTTP request to a web server.
o Example: A user logs in by submitting their username and
password through a web form.
2. Request Forwarding:
o The web server receives the request and forwards it to the
servlet container.
3. Servlet Execution:
o The servlet container identifies the appropriate servlet to
handle the request.

191CAC602J - Web Technology


o A thread is created for this request, and the servlet's service()
method is executed.
o If using HttpServlet, the doGet() or doPost() method is
invoked based on the request type.
4. Processing and Database Interaction:
o The servlet processes the request. If needed, it interacts with
the database to retrieve or store data.
o Example: Querying the database for user authentication.
5. Response Generation:
o After processing the request, the servlet generates a dynamic
response (HTML, JSON, XML, etc.).
o The response is passed back to the web server.
6. Client Response:
o The web server sends the servlet's response back to the client
(web browser), which displays the content to the user.
Advantages of Servlet Architecture

● Scalable: Supports multithreading to handle multiple client


requests efficiently.

4
● Platform-Independent: Runs on any platform with a Java-
enabled server.

● Integration with Java: Allows seamless use of Java libraries,


JDBC for databases, and JSPs for UI.

● Performance: Eliminates the overhead of process creation seen in


CGI.

● Dynamic Content: Enables the creation of highly dynamic and


interactive web pages.
Disadvantages

● Designing a servlet can be pretty laborious.

● Exceptions need to be handled while designing a servlet since they


are not thread safe.

● Developers may need additional skills to program a servlet.

191CAC602J - Web Technology


A Servlet-Generating Dynamic Content
A Servlet is a Java programming language class used to extend the
capabilities of servers that host applications accessed by users through a
request-response model, such as web servers. Servlets are used for
generating dynamic web content, handling client requests, and generating
responses. They are part of the Java EE (Enterprise Edition) specification
and are typically used to create web-based applications.
Steps for a Basic Servlet to Generate Dynamic Content:
1. Create a Servlet Class: A Servlet class must extend HttpServlet
and override its doGet or doPost method to handle HTTP requests.
PROGRAM:

5
2.Servlet Configuration (web.xml): The Servlet needs to be
configured in the web.xml file of the web application to map it to a
specific URL pattern.
PROGRAM:

3.Deploy the Web Application: After writing the servlet class and
configuration, you need to compile the servlet class and deploy it in a web
container like Apache Tomcat. Place the

191CAC602J - Web Technology


compiled .class file in the appropriate directory (e.g., /WEB-INF/classes)
and the web.xml in /WEB-INF/web.xml.
4.Test the Servlet: After deployment, open a browser and visit the URL
pattern you configured (e.g., http://localhost:8080/your-web-app/hello).
The servlet will generate the dynamic HTML content as specified in the
doGet method.
Key Components of a Servlet:

6
● Request Handling: The doGet() or doPost() methods handle
incoming HTTP requests.

● Response Generation: Servlets generate dynamic content using


the response object, typically by writing to the PrintWriter stream.

● Servlet Context: The servlet is deployed in a web server or servlet


container (like Tomcat) that provides context and manages the
lifecycle of the servlet.
Advantages of Using Servlets for Dynamic Content:

● Performance: Servlets are loaded once and then reused for each
request, making them more efficient compared to CGI (Common
Gateway Interface).

● Integration with Other Java Technologies: Servlets can be


integrated with JSP (JavaServer Pages), EJB (Enterprise JavaBeans),
and other Java-based technologies.

● State Management: Servlets provide session management


through HttpSession for maintaining user state across multiple
requests.
Disadvantages of Using Servlets for Dynamic Content:

● Complexity: Servlets can become complex, especially for large


applications, requiring a lot of boilerplate code and manual
management of HTTP requests and responses.

● Limited Separation of Concerns: Unlike JSP (JavaServer Pages)


or modern frameworks like Spring, Servlets mix logic and
presentation, making it harder to maintain and manage the user
interface and business logic separately.

● Scalability Issues: Servlets maintain a single instance for multiple


requests, which can lead to memory consumption and scalability
issues in high-traffic applications without proper management like
session handling and connection pooling.
Life Cycle of a Servlet
The entire life cycle of a Servlet is managed by the Servlet
container which uses the javax.servlet.Servlet interface to understand
the Servlet object and manage it. So, before

7
191CAC602J - Web Technology
creating a Servlet object, let’s first understand the life cycle of the Servlet
object which is actually understanding how the Servlet container manages
the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes
through four stages,

● Loading a Servlet.

● Initializing the Servlet.

● Request handling.

● Destroying the Servlet.


Let’s look at each of these stages in details:
1. Loading a Servlet: The first stage of the Servlet lifecycle involves
loading and initializing the Servlet by the Servlet container. The
Web container or Servlet Container can load the Servlet at either of
the following two stages :

● Initializing the context, on configuring the Servlet with a zero


or positive integer value.

● If the Servlet is not preceding stage, it may delay the loading


process until the Web container determines that this Servlet is
needed to service a request.
The Servlet container performs two operations in this stage :

● Loading : Loads the Servlet class.

● Instantiation : Creates an instance of the Servlet. To create


a new instance of the Servlet, the container uses the no-
argument constructor.

8
191CAC602J - Web Technology

2. Initializing a Servlet: After the Servlet is instantiated successfully,


the Servlet container initializes the instantiated Servlet object. The
container initializes the Servlet object by invoking
the Servlet.init(ServletConfig) method which accepts
ServletConfig object reference as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method
only once, immediately after the Servlet.init(ServletConfig) object is
instantiated successfully. This method is used to initialize the resources,
such as JDBC datasource.
Now, if the Servlet fails to initialize, then it informs the Servlet container
by throwing the ServletException or UnavailableException.
3. Handling request: After initialization, the Servlet instance is ready
to serve the client requests. The Servlet container performs the
following operations when the Servlet instance is located to service
a request :

● It creates the ServletRequest and ServletResponse objects.


In this case, if this is a HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse obj
ects which are subtypes of

9
the ServletRequest and ServletResponse objects
respectively.

● After creating the request and response objects it invokes the


Servlet.service(ServletRequest, ServletResponse) method by
passing the request and response objects.

The service() method while processing the request may throw


the ServletException or UnavailableException or IOException.
4. Destroying a Servlet: When a Servlet container decides to destroy
the Servlet, it performs the following operations,

● It allows all the threads currently running in the service


method of the Servlet instance to complete their jobs and get
released.

● After currently running threads have completed their jobs, the


Servlet container calls the destroy() method on the Servlet
instance.
After the destroy() method is executed, the Servlet container releases all
the references of this Servlet instance so that it becomes eligible for
garbage collection.
Servlet Life Cycle Methods
There are three life cycle methods of a Servlet :

191CAC602J - Web Technology

● init()

● service()

● destroy()

10
Let’s look at each of these methods in details:
1. init() method: The Servlet.init() method is called by the Servlet
container to indicate that this Servlet instance is instantiated
successfully and is about to put into service.

2.service() method: The service() method of the Servlet is invoked to


inform the Servlet about the client requests.

● This method uses ServletRequest object to collect the data


requested by the client.

● This method uses ServletResponse object to generate the output


content.

191CAC602J - Web Technology

11
3.destroy() method: The destroy() method runs only once during the
lifetime of a Servlet and signals the end of the Servlet instance.

Advantages:
1. Efficient Resource Management: Servlets are initialized once
and can handle multiple requests, reducing overhead.
2. Multi-Request Handling: One instance handles many requests,
improving performance.
3. Custom Request Processing: Allows flexible handling of different
HTTP methods (GET, POST, etc.).
Disadvantages:
1. Complex Session Management: Managing user sessions across
requests can be tricky.
2. Resource Leaks: Improper cleanup can lead to resource
management issues.
3. Scalability Challenges: Handling high traffic with a single servlet
instance can be difficult without proper scaling techniques.
Parameter Data Sessions
Parameter Data and Sessions in web applications are crucial for
managing data across different user interactions and requests. Here's a
brief explanation of each:
1. Parameter Data:

12
191CAC602J - Web Technology

● Definition: Parameter data refers to the information sent from the


client (usually a browser) to the server in an HTTP request. It can
be passed in the URL (query string), form data (via POST), or as
part of the HTTP headers.

● Examples:
o URL parameters: http://example.com?name=John&age=25
o Form parameters: Submitted via a form <input type="text"
name="username" />
o HTTP headers: Custom data passed along with the request
headers.
Usage in Servlets:

● HttpServletRequest.getParameter() is used to retrieve


parameters passed in the request.

● Example:
String name = request.getParameter("name");
String age =
request.getParameter("age");
2. Sessions:

● Definition: A session is a way to store user-specific data on the


server during a user's interaction with a web application. It helps
maintain state between requests, as HTTP is stateless.

● Session ID: A unique identifier assigned to each session, often


stored in a cookie or URL.
Session Management in Servlets:

● Creating a Session: request.getSession() creates a new session or


retrieves an existing one.

● Storing Data in a Session:


Program:
HttpSession session = request.getSession();
session.setAttribute("username", "John");

● Retrieving Data from a Session:

13
191CAC602J - Web Technology

Program:
String username = (String) session.getAttribute("username");

● Session Timeout: Sessions can have a timeout period after which


they are invalidated automatically.
Key Differences Between Parameter Data and Sessions:

● Parameter Data is typically passed with each request (URL, form,


or header) and is specific to a single request.

● Sessions store data across multiple requests during a user's


interaction with the application, maintaining state between those
requests.
Advantages of Using Sessions:
1. User State Management: Allows tracking of user activity across
multiple pages.
2. Security: Sensitive information can be stored server-side, reducing
exposure.
Disadvantages of Sessions:
1. Memory Usage: Storing session data can increase server memory
usage.
2. Scalability: Managing sessions in a distributed environment
(multiple servers) can be complex.

Jakarta Server Pages (JSP) Overview


JSP (Jakarta Server Pages) is a server-side technology for creating
dynamic web applications by embedding Java code into HTML/XML
pages. It acts as an extension of Servlet technology, allowing for
easier development of platform-independent web pages.
Advantages of JSP Over Servlets

● Ease of Maintenance: Less complex to maintain than servlets.

14
● No Recompilation/ Redeployment: Changes in JSP pages don't
require recompilation or redeployment.

● Less Coding: JSP reduces boilerplate code compared to servlets.

● Access to Java API: Full access to Java's extensive API.

● Extended Servlets: Inherits features of servlets and adds


enhancements.

191CAC602J - Web Technology

Key Features of JSP

● Ease of Coding: Combines Java with HTML/XML for simplicity.

● Straightforward Learning Curve: Suitable for users with basic


Java skills.

● Reduction in Code Length: Action and custom tags minimize


redundancy.

● Java Scriplets and Expression Language: Embed Java logic and


evaluate expressions seamlessly.

● Implicit Objects: Provides built-in objects like request, response,


and session.

● Database Connectivity: Simplifies data interaction.

● Portable and Platform-Independent: Works across different


servers and platforms.

● Dynamic Content: Generates HTML dynamically based on server-


side logic.

● Exception Handling: Manages errors and exceptions effectively.

Architecture of JSP

The JSP (Jakarta Server Pages) architecture defines the process of how a
JSP file is requested, processed, and returned to the client. JSP is a
server-side technology that simplifies web development by embedding
Java code within HTML pages. Its architecture is built on top of the

15
Servlet API and follows the Model-View-Controller (MVC) design
pattern.

Key Components of JSP Architecture

1. Client (Browser):

191CAC602J - Web Technology

o The client is a web browser or application that sends HTTP


requests to the web server for accessing JSP pages.
2. Web Server:
o The web server receives the client request and forwards it to
the JSP Engine for processing. Popular web servers
supporting JSP include Apache Tomcat, WebLogic, and JBoss.
3. JSP Engine:
o The JSP engine is responsible for translating and executing
JSP files. It plays a key role in converting JSP code into
servlets for dynamic web content generation.
o Steps in JSP Engine:
1. Read JSP Files: It reads the .jsp file requested by the
client.
2. Translate JSP to Servlet: The JSP file is translated
into a servlet class.
3. Compile Servlet Code: The servlet class is compiled
into Java bytecode.
4. Execute Servlet: The compiled servlet is executed to
generate the response (usually HTML or other formats).
5. Send Response: The output is sent back to the client.
4. Servlet Container:

16
oThe servlet container manages the lifecycle of servlets
generated from JSP files. It handles the translation,
compilation, and execution of servlets and provides HTTP
request/response handling.
5. Database/Backend (Optional):
o In most cases, JSP applications interact with databases to
retrieve or store data. JDBC (Java Database Connectivity) is
commonly used for database interaction in JSP applications.

Process Flow in JSP Architecture

1. Client Request:
o A client sends an HTTP request to the web server for a .jsp file.
2. JSP File Processing:
o The web server forwards the request to the JSP engine, which
handles the following:
▪ Translation: Converts the JSP file into a servlet.
▪ Compilation: Compiles the servlet into bytecode.
3. Servlet Execution:
o The servlet processes the request, executes any embedded
Java code, and generates a response (usually HTML).
4. Response to Client:
o The generated HTML or other web content is sent back to the
client.

191CAC602J - Web Technology

Advantages of JSP Architecture

● Simplifies Development: Java code can be embedded directly


into HTML.
● Dynamic Content: JSP allows dynamic generation of web pages
based on user inputs or data from a backend.
● Scalability: As part of the Servlet API, JSP applications are scalable
and can handle high traffic.
● Integration with Java: Access to Java libraries and APIs makes
JSP powerful and flexible.
● MVC Support: Encourages the separation of business logic,
presentation, and data for maintainable applications.

Disadvantages of JSP (Short)

17
● Complex Debugging: Debugging is challenging due to the mix of
Java code and HTML, making errors harder to isolate.
● First-Time Access Delay: Initial access requires compilation into a
servlet, causing latency.
● Outdated Technology: Modern frameworks like Spring, React, and
Angular offer better features and support, making JSP less preferred.

Steps to Run JSP Applications (Detailed Explanation)

1. Set Up Your Environment:


o Install Java Development Kit (JDK): Ensure you have the
latest JDK installed and configured with environment variables
(JAVA_HOME and PATH).
o Install a Servlet Container: Popular choices include Apache
Tomcat, GlassFish, or Jetty. Tomcat is widely used for
running JSP applications.
2. Create a Project Folder Structure:
o Organize your project files properly:

191CAC602J - Web Technology

3. Write Your JSP Files:


o Create a .jsp file, for example, index.jsp. This file can include
a mix of HTML and Java code:

18
4. Configure the web.xml File (Deployment Descriptor):

● Place this file in the WEB-INF folder to map URLs to JSP files or
servlets.

5.Start the Server:

● Start your servlet container (e.g., Tomcat):


o For Tomcat, navigate to the bin directory and run startup.bat
(Windows) or ./startup.sh (Linux/Mac).

6. Deploy the Application:

● Package your application into a WAR (Web Application Archive)


file or place the project folder in the server's webapps directory.

Example

191CAC602J - Web Technology

7.Access the Application:

19
● Open a web browser and access your application by navigating to
the URL:

8. Test the Application:

● Interact with the web application to ensure it responds to user


inputs and requests correctly.

9.Debug and Optimize:

● Use server logs (e.g., Tomcat's logs/catalina.out) to debug any


issues.
● Optimize the JSP code and server configuration for performance.

10.Database Integration (Optional):

● Add database connectivity by using JDBC:


o Import the required JDBC driver (e.g., MySQL Connector JAR).
o Use Java code in JSP to connect and execute SQL queries:

Basic JSP Classes

In JSP, certain classes are used for core functionalities. These are derived
from the Java Servlet API and enable dynamic web content generation.

191CAC602J - Web Technology

20
1. javax.servlet.jsp.JspPage:
o An interface that all JSP pages must implement.
o Includes lifecycle methods like:
▪ jspInit(): Invoked during the initialization of the JSP
page.
▪ jspDestroy(): Invoked when the JSP page is destroyed.
2. javax.servlet.jsp.HttpJspPage:
o A subinterface of JspPage specifically for HTTP-based JSPs.
o Includes the service(HttpServletRequest req,
HttpServletResponse res) method, used to handle client
requests.
3. javax.servlet.jsp.JspWriter:
o Used to write content to the response stream.
o Provides methods like:
▪ print()
▪ println()
▪ clear()
▪ flush()
4. javax.servlet.jsp.PageContext:
o Provides access to various JSP scopes (page, request, session,
application).
o Manages shared resources like attributes and beans.
5. javax.servlet.jsp.tagext.Tag:
o Represents custom tags in JSP.
o Classes implementing this interface can define reusable tag
behaviors.

Basic JSP Tags

JSP tags enable embedding Java code within HTML for creating
dynamic web pages. These tags fall into three categories: Scripting
Elements, Directive Tags, and Action Tags.

1. Scripting Elements

Used to embed Java code within JSP files.

● Declaration (<%! %>):


o Declares variables or methods that are accessible throughout
the JSP page.
o Example:

21
191CAC602J - Web Technology

● Expression (<%= %>):


● Evaluates an expression and displays its result in the output.
● Example:

● Scriptlet (<% %>):


● Embeds Java code to be executed during request processing.
● Example:

2. Directive Tags

Provide instructions to the JSP engine about page settings.

● Page Directive (<%@ page ... %>):


o Defines global attributes for the JSP page, like language,
buffer size, etc.
o Example

Include Directive (<%@ include ... %>):

● Includes the content of another file during page translation.


● Example:

Taglib Directive (<%@ taglib ... %>):

● Declares the use of custom tag libraries.


● Example:

22
3. Action Tags

Perform tasks like forwarding requests, using beans, and including


resources.

191CAC602J - Web Technology

● <jsp:useBean>:
o Creates or accesses a JavaBean object.
o Example:

● <jsp:setProperty>:
● Sets properties of a bean.
● Example:

● <jsp:getProperty>:

● Retrieves and displays a bean property.


● Example:

● <jsp:include>:

● Dynamically includes another JSP or HTML file at runtime.


● Example:

● <jsp:forward>:

● Forwards the request to another resource.


● Example:

23
● <jsp:param>:

● Passes parameters to another resource.


● Example:

191CAC602J - Web Technology

Databases and JSP (JavaServer Pages) - Representing Web Data

In a web application, databases are commonly used to store and retrieve


data, and JSP (JavaServer Pages) helps represent this data dynamically
on web pages. Below are the key aspects of how databases and JSP work
together in a typical web application:

1. Understanding JSP (JavaServer Pages):

● JSP is a technology that allows embedding Java code into HTML


pages to dynamically generate web content.
● It is part of the Java EE (Enterprise Edition) and can interact with
databases through JDBC (Java Database Connectivity) to represent
data.
● JSP pages are typically processed by a web server to generate
HTML content, which is sent to the client browser.

2. JSP and Database Interaction:

● JSP interacts with databases using JDBC to retrieve, insert, update,


or delete data.
● The typical flow of data from a database to a JSP page involves:
1. Connecting to the Database: Using JDBC to establish a
connection to the database.
2. Executing Queries: Performing SQL queries (e.g., SELECT)
to retrieve data.
3. Processing the Results: Handling the results of the queries
(e.g., iterating over a ResultSet).

24
4. Displaying Data on JSP: Using JSP tags or scriptlets to
dynamically insert the retrieved data into HTML.

3. Steps for Representing Web Data using JSP and Database:

Step 1: Set up the Database Connection

● Use JDBC to connect to the database. Here’s a sample code snippet


for a database connection:

191CAC602J - Web Technology

Step 2: Query the Database

● Execute SQL queries to fetch the required data from the database.
For example:

Step 3: Process the Query Results

● Process the ResultSet to fetch data row by row.

25
Step 4: Pass Data to JSP Page

● You can pass the fetched data from the Servlet to the JSP page via
request attributes:

Step 5: Display Data on JSP Page

● On the JSP page, use EL (Expression Language) or JSP tags to


display the data.

191CAC602J - Web Technology

Advantages of Using JSP for Representing Web Data:

● Separation of Concerns: JSP allows the separation of business


logic (Java) and presentation (HTML). It also supports MVC
architecture, where the model represents the data, and the view
(JSP) represents the presentation layer.
● Dynamic Content: JSP allows dynamic content generation based
on data retrieved from databases.

26
● Integration with Java Technologies: JSP integrates well with
other Java-based technologies like Servlets, EJB, and JDBC for
database interaction.

Differences Between Servlet and JSP:

Servlet JSP

Java code HTML with embedded Java code

Harder to code (HTML in Java) Easier to code (Java in HTML)

Acts as a controller Acts as a view

Faster Slower (compiles to Servlet first)

Session management not enabled Session management enabled by


by default default

Combines business and Separates business logic via


presentation logic JavaBeans

No implicit objects Includes built-in implicit objects

Requires recompilation and server


Just refresh the page
restart

Custom tags not supported Custom tags supported

Not suitable for extensive data


Handles extensive data processing
processing

27
191CAC602J - Web Technology

UNIT V : XML AND WEB SERVICES


XML-Documents -Versions and Declaration-Namespaces- Transforming
XML Documents-Selecting XML Data: XPATH- XSLT Displaying XML
Documents in Browsers -Web Services: Writing a Java Web Service-
Writing a Java Web Service Client- UDDI-WSDLSOAP.

What is XML?
Extensible Markup Language (XML) is a markup language designed to
store, organize, and transfer data in a structured format that is both
machine-readable and human-readable. XML is widely used across web
applications, APIs, and data storage systems due to its flexibility and
simplicity.
Key Features of XML
1. Structured Data Representation: Data is organized hierarchically
using tags.
2. Human-Readable: The plain-text format makes it easy to read
and debug.
3. Platform Independent: Works across different programming
languages and operating systems.
4. Extensibility: Developers can define their own tags to suit their
data needs.
5. Self-Descriptive: Tags and attributes clearly describe the data
they enclose.

XML Documents

● XML Document: A structured file that adheres to the rules of XML


(Extensible Markup Language). It is used to store, transport, and
organize data in a hierarchical format.

1
● XML documents are both machine-readable and human-
readable.
Structure of an XML Document
1. XML Declaration:
o Appears at the top of the file and specifies the XML version
and encoding.
o Example: <?xml version="1.0" encoding="UTF-8"?>
2. Root Element:
o

191CAC602J - Web Technology


o Every XML document must have one root element that
encloses all other elements.
o Example: <books> in the following document.
3. Elements:
o Represent the data and are defined using opening and closing
tags.
o Example:
<title>XML Basics</title>
4. Attributes:
o Provide additional information about elements.
o Example:
<book id="101">
<title>XML Basics</title>
</book>
5. Text Content:
o The data enclosed within an element.
o Example:
<author>Jane Doe</author>

2
6. Comments:
o Used to add notes or explanations.
o Example:
<!-- This is a comment -->

191CAC602J - Web Technology

Example XML Document

Key Features of XML Documents


1. Hierarchical Structure:
o Data is represented in a tree-like structure.
o Allows nesting of elements.
2. Platform-Independent:

3
o Can be used on any operating system and programming
language.
3. Self-Descriptive:
o Tags are user-defined, making the data easily understandable.
4. Supports Metadata:
o Attributes provide additional details about data.
5. Flexible and Extensible:
o Custom tags can be created to suit application needs.
Types of XML Documents
1. Well-Formed XML:
o Follows XML syntax rules.

191CAC602J - Web Technology


o Every opening tag must have a corresponding closing tag.
o Single root element is mandatory.
2. Valid XML:
o Well-formed XML that conforms to a defined DTD (Document
Type Definition) or XSD (XML Schema Definition).
Uses of XML Documents
1. Data Storage:
o Used to store structured data for applications.
2. Data Exchange:
o Facilitates communication between different systems.
3. Web Services:
o SOAP and REST APIs use XML for data transmission.
4. Content Syndication:
o Formats like RSS and Atom for news feeds are based on XML.
5. Configuration Files:

4
o XML is widely used in applications for storing configuration
details (e.g., Android Manifest files).
Advantages of XML Documents
1. Interoperability:
o Standardized format ensures compatibility across systems.
2. Ease of Use:
o Simple syntax makes it easy to learn and implement.
3. Customizable:
o Tags and attributes can be tailored to specific applications.
4. Readable by Humans and Machines:
o Ensures clarity for developers and systems alike.

191CAC602J - Web Technology


XML Version:

● The version refers to the version of XML being used in the


document.

● The most common version is 1.0, but there's also 1.1, although it's
less commonly used.

● This is specified in the XML declaration as version="1.0".


XML Declaration:

● The declaration is the header at the beginning of an XML


document that provides information about the document’s version,
encoding, and sometimes the standalone status.

● The XML declaration is optional, but it is typically included at the top


of XML documents.
Example of XML declaration:
<?xml version="1.0" encoding="UTF-8"?>

5
● version="1.0": Specifies the version of XML. Currently, the most
widely used version is 1.0, but version 1.1 also exists, though it's
not commonly used.
● encoding="UTF-8": Specifies the character encoding used in the
document. UTF-8 is a common encoding because it supports a wide
range of characters from different languages.
● standalone="yes" or "no" (optional): Specifies whether the
document is self-contained or needs external resources (such as
DTD).
o standalone="yes" means the document doesn't
require a DTD to be valid.
o standalone="no" means the document depends on
a DTD.

XML Namespaces
XML namespaces prevent naming conflicts between elements and
attributes in XML documents, especially when various XML vocabularies
are joined or elements with the same name come from different sources.
Table of Content

● Default Namespace Declaration

● Prefixed Namespace Declaration

191CAC602J - Web Technology


Default Namespace Declaration
Default Namespace Declaration in XML namespaces assigns a default
namespace to all unprefixed components inside a given scope. This
signifies that elements without a prefix are presumed from the given
namespace. The "xmlns" element is used to declare the default
namespace.
Syntax:
<root xmlns="http://example.com/ns">
<child>Content</child>
</root>

6
Example: To demonstrate the XML library catalog file structure in XML.
<?xml version="1.0" encoding="UTF-8"?>
<library output:
xmlns="http://example.com/library">
<book>
<title>XML Basics</title>
<author>John Doe</author>
</book>
<book>
<title>Advanced XML</title>
<author>Jane Smith</author>
</book>
</library>
Prefixed Namespace Declaration
In XML namespaces, the Prefixed Namespace Declaration method assigns
a prefix to a namespace URI. This allows elements and attributes from
that namespace to be identified with the specified prefix. Prefixed
namespaces are especially beneficial when items from different
namespaces appear in the same XML document.

191CAC602J - Web Technology


Syntax:
<root xmlns:prefix="http://example.com/ns">
<prefix:child>Content</prefix:child>
</root>
Example: To demonsrtate the books catalog file structure in XML.
<?xml version="1.0" encoding="UTF-8"?>

7
<catalog output:
xmlns:bk="http://example.com/books"
xmlns:auth="http://example.com/authors">
<bk:book>
<bk:title>XML Basics</bk:title>
<auth:author>John Doe</auth:author>
</bk:book>
<bk:book>
<bk:title>Advanced XML</bk:title>
<auth:author>Jane Smith</auth:author>
</bk:book>
</catalog>
Advantages of Using Namespaces in XML
1. Avoid Naming Conflicts: Ensures that elements with the same
name in different documents or vocabularies don't clash.
2. Organized and Structured Data: Helps in managing complex
data models with multiple domains.
3. Extensibility: Allows you to combine multiple XML formats and
vocabularies without conflicts.
Transforming XML Documents
Transforming XML documents refers to the process of converting XML
data from one format to another. This can be useful when you want to
present or manipulate the XML data differently

191CAC602J - Web Technology


for various purposes such as rendering it in a web browser or exporting it
in another format (like HTML, CSV, etc.).

8
The most common methods for transforming XML documents are XSLT
(Extensible Stylesheet Language Transformations) and XPath. Here are
the key concepts:
1. XSLT (Extensible Stylesheet Language Transformations)
XSLT is a language used for transforming XML documents into different
formats such as HTML, plain text, or even other XML formats. It is the
primary method for transforming XML in web applications.

● XSLT Stylesheet: This defines the rules for transforming the XML
document.

● Transforming Process: The XSLT processor reads an XML


document and applies the stylesheet to transform it into another
document.
How XSLT Works:
1. Input: An XML document (source document).
2. XSLT Stylesheet: Contains the transformation rules (written in
XML syntax) that define how the input XML should be transformed.
3. Output: A transformed document (HTML, XML, text, etc.).
Basic Structure of XSLT:

● An XSLT document uses the <xsl:stylesheet> element as the root


element.

● Inside the stylesheet, the <xsl:template> element defines the


transformation rules.

● The <xsl:value-of> element is used to retrieve values from the XML


document.
Example:
Here is an example of an XML document and an XSLT stylesheet to
transform it into HTML.
Input XML (source document):

9
191CAC602J - Web Technology
XSLT Stylesheet:

Output (HTML):

2. XPath (XML Path Language)


XPath is a language used to navigate through elements and attributes in
an XML document. XPath is often used in conjunction with XSLT for
selecting and extracting data from XML documents during transformation.

10
191CAC602J - Web Technology

● XPath Expressions: Used to locate elements, attributes, and text


within the XML document.

● XPath allows for simple navigation, such as selecting nodes based


on their names, attributes, or position in the XML tree.

Example of XPath:
1. Select the title element of the first book:
/books/book[1]/title
2. Select all title elements under book:
/books/book/title
Selecting XML Data with XPath
XPath (XML Path Language) is a language used to navigate through and
select specific parts of an XML document. XPath is integral to XSLT for
extracting and manipulating XML data.
Key Features of XPath:

● Navigation: Traverse elements, attributes, and text nodes.

● Expression Syntax: XPath expressions are used to locate nodes.

● Predicates: Specify conditions to filter results.


Basic XPath Syntax:
1. / - Selects the root node.
2. // - Selects nodes from anywhere in the document.
3. @ - Selects attributes.
4. [ ] - Applies filters.
Examples:
1. Select all book elements:
//book

11
2. Select the title element of the first book:
/books/book[1]/title

191CAC602J - Web Technology


3. Select all book elements with an author named "John Doe":
//book[author='John Doe']
Using XPath in XSLT:
In XSLT, XPath expressions help define which data to transform or display.
<xsl:value-of select="//book/title"/>
Displaying XML Documents in Browsers
Web browsers can display XML documents directly, and their presentation
can be enhanced using XSLT (Extensible Stylesheet Language
Transformations). This section describes how XML documents can be
viewed and styled for better readability in browsers.
1. Raw XML Display in Browsers
Most modern browsers (e.g., Chrome, Firefox, Edge) can display XML
documents directly in their raw form. When you open an XML file in a
browser:

● The browser renders the XML structure as a collapsible tree.

● Tags, attributes, and text content are displayed in a readable


hierarchy.

● Syntax errors, if any, are flagged by the browser.

Example: Simple XML File Browser Output:

2. Styled Display Using XSLT

12
To enhance the visual representation of XML, XSLT stylesheets can be
applied. The XSLT defines how the XML data should be transformed and
displayed, typically as HTML.
Steps to Display Styled XML in Browsers:
1. Create an XML file containing the data.
2. Write an XSLT stylesheet to define how the data should appear
(e.g., as HTML).
3. Link the XSLT to the XML document using the <?xml-
stylesheet?> processing instruction.

191CAC602J - Web Technology

Example: Styled XML Display

XML File (books.xml):

XSLT Stylesheet (style.xsl):

13
Output in Browser:

When you open books.xml in a browser, the XSLT transforms the XML
data into an HTML table:

191CAC602J - Web Technology

Book List
Yea
Title Author
r

XML for John 202


Beginners Doe 4

Jane 202
Advanced XML
Java Web Services: Smith 3

Web services enable applications to communicate over the internet or


within networks by providing a standard way to exchange data and
perform operations. These services can be used across different

14
platforms and programming languages, making them highly
interoperable.

In Java, there are two main types of web services:

1. SOAP-based Web Services:


o SOAP (Simple Object Access Protocol) is a protocol used for
exchanging structured information in the form of XML. It is
highly extensible and relies on XML for messaging, which
ensures platform independence.
o SOAP is typically used for applications that require strict
security, transactions, and ACID compliance. It operates over
a variety of protocols such as HTTP, SMTP, and more.
2. RESTful Web Services:
o REST (Representational State Transfer) is an architectural
style that uses HTTP methods (GET, POST, PUT, DELETE) for
communication. It is lightweight, stateless, and uses standard
web protocols, making it ideal for web-based applications.
o RESTful services use simple data formats like JSON or XML,
and are commonly used for web applications, mobile apps,
and cloud-based services due to their ease of use and
efficiency.

Writing a Java Web Service

Writing a Java Web Service typically involves creating a SOAP-based or


RESTful web service. Here, we will focus on a SOAP web service using
JAX-WS (Java API for XML Web Services).

Steps to Write a SOAP Web Service:

1. Define the Service Endpoint Interface (SEI):


o

191CAC602J - Web Technology

o An SEI is an interface that declares the web service


operations (methods) that will be exposed as a web service.
o Example:

@WebService

public interface HelloWorld {

15
String sayHello(String name);

2. Implement the SEI:

● Create a Java class that implements the methods defined in the SEI.
● Example:

@WebService(endpointInterface = "com.example.HelloWorld")

public class HelloWorldImpl implements HelloWorld {

public String sayHello(String name) {

return "Hello, " + name;

3. Annotate with JAX-WS Annotations:

● Use JAX-WS annotations (@WebService, @WebMethod) to mark the


SEI and implementation class.
● Example:

@WebService

public class HelloWorldImpl implements HelloWorld {

@WebMethod

public String sayHello(String name) {

191CAC602J - Web Technology

return "Hello, " + name;

16
4. Publish the Web Service:

● Create an endpoint to publish the service, which makes it available


for clients to consume.
● Example:

public class HelloWorldPublisher {

public static void main(String[] args) {

Endpoint.publish("http://localhost:8080/hello", new
HelloWorldImpl());

5. Deploy the Service:


o Package the service as a WAR file (Web Application Archive)
and deploy it to a web server like Tomcat or any Jakarta EE-
compatible server.

Writing a Java Web Service Client

Once the web service is created and deployed, you can write a Java Web
Service Client to consume the service. A client typically sends requests
to the web service and handles the responses.

Steps to Write a Web Service Client:

1. Generate the Client Stub:


o Use the wsimport tool to generate client code (stubs) from the
WSDL (Web Services Description Language) document
provided by the server.
o Example:

wsimport -keep -d ./src


http://localhost:8080/hello?wsdl

191CAC602J - Web Technology

17
2. Create a Client Class:
o Use the generated classes to interact with the web
service.
o Example:

3. Run the Client:

● Execute the client application to see the response from the web
service.

UDDI (Universal Description, Discovery, and Integration)

UDDI is a directory service where businesses can register their web


services and other applications can discover and interact with them. UDDI
provides a platform-independent framework for discovering web services.

● Key Features of UDDI:


o Business Registration: Businesses can register their web
services.
o Discovery: Other applications can search the UDDI registry
to find and use available web services.
o Information: UDDI provides metadata about the web
services, such as operation descriptions, service addresses,
and more.

Steps for Using UDDI:

1. Register Web Service: A business registers its web service in the


UDDI registry with a name, description, and location.
2. Search Web Services: Other businesses or applications can search
the UDDI registry to find services that match their needs.

WSDL (Web Services Description Language)

WSDL is an XML-based language used for describing the functionalities of


a web service. It defines the interface for the service, including the
available operations and how to interact with them.

● WSDL Structure:
o <types>: Defines the data types used in the service.
o

18
191CAC602J - Web Technology

o <message>: Describes the messages exchanged between


the client and the service.
o <portType>: Specifies the operations (methods) available in
the web service.
o <binding>: Defines the communication protocol used (e.g.,
SOAP, HTTP).
o <service>: Specifies the endpoint where the service is
available.

WSDL Example:

SOAP (Simple Object Access Protocol)

SOAP is a protocol used for exchanging structured information in the


implementation of web services. It relies on XML to encode messages,
which are typically sent over HTTP or SMTP.

● SOAP Message Structure:


o Envelope: Wraps the message and contains the header and
body.

19
o Header: Contains metadata about the message, such as
authentication or transaction information.
o Body: Contains the actual message or request/response data.

191CAC602J - Web Technology

Example SOAP Request:

20
21

You might also like