0% found this document useful (0 votes)
363 views188 pages

WT Unit-1 To 5

Uploaded by

venkyvivek425
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)
363 views188 pages

WT Unit-1 To 5

Uploaded by

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

WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.

PROF & HOD

Unit-1
UNIT I:
Web Basics- Introduction, Concept of Internet- History of Internet, Protocols of
Internet, World Wide Web, URL, Web Server, Web Browser. HTML- Introduction,
History of HTML, Structure of HTML Document: Text Basics, Structure of HTML
Document: Images and Multimedia, Links and webs, Document Layout, Creating Forms,
Frames and Tables, Cascading style sheets.

Web Basics:
What is the Web?

The World Wide Web, often just called the "web," is a vast collection of interconnected
digital documents and resources. It's a part of the internet that allows people to access and
share information, media, and services through websites. The web has transformed how
we communicate, learn, shop, entertain ourselves, and conduct business.

Key Components of the Web:

1. Web Pages: These are the individual documents you see on the web. They can
contain text, images, videos, links, and interactive elements.

2. URL (Uniform Resource Locator): A URL is the web address used to locate a
specific resource, like a webpage. It consists of a protocol (e.g., "http" or "https"), a
domain name (like "www.example.com"), and a path to the resource.

3. HTTP and HTTPS: Hypertext Transfer Protocol (HTTP) is the language


computers use to communicate on the web. It's how your browser requests web
pages. HTTPS is the secure version of HTTP, encrypting data to ensure privacy and
security.

4. Web Browsers: These are software applications (e.g., Chrome, Firefox, Safari) that
you use to access and view web content. Browsers interpret the code of web pages,
fetch resources, and display them on your screen.

5. HTML (Hypertext Markup Language): HTML is the standard language for


creating web pages. It uses tags to structure content, define headings, paragraphs,
links, images, and more.

1|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

6. CSS (Cascading Style Sheets): CSS is used to style and format web pages. It
controls the presentation aspects, like colors, fonts, layouts, and animations.

7. JavaScript: JavaScript is a programming language that adds interactivity to web


pages. It enables dynamic elements, like form validation, animations, and real-time
updates.

8. Web Hosting: To make a website accessible on the internet, its files are stored on
web servers. Web hosting services provide the technology and space for these files.

9. Domain Names: These are human-readable addresses for websites. They're


translated into IP addresses (computer-readable) by DNS servers. For instance,
"amazon.com" is a domain name.

10. Responsive Design: Websites should adapt to various screen sizes and devices.
Responsive design ensures that the content looks good and is usable on desktops,
tablets, and smartphones.

How it Works:

When you enter a URL in your browser and hit "Enter," your browser sends an HTTP or
HTTPS request to the server hosting the requested webpage. The server processes the
request, retrieves the necessary files (HTML, CSS, JavaScript, images), and sends them
back to your browser, which then renders and displays the web page.

In essence, the web is a digital ecosystem where information is created, shared, and
accessed globally. Its components work together seamlessly to provide a rich and
interactive online experience.

This introduction covers the fundamental concepts of the web. As you delve deeper, you'll
discover more about creating web content, designing user-friendly interfaces, and utilizing
advanced technologies to build dynamic online experiences.

Concept of Internet- History of Internet:

Concept of the Internet:

The internet is a global network of interconnected computers and devices that


communicate with each other using standardized protocols. It allows for the sharing of
information, communication, and access to various services and resources across the

2|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

world. The internet is decentralized, meaning that no single entity or organization controls
it. Instead, it's a network of networks, with each network connecting various devices and
systems.

History of the Internet:

The history of the internet dates back to the 1960s and involves the development of
technologies and concepts that laid the groundwork for the modern internet we know
today. Here's a brief timeline:

1. 1960s - ARPANET: The Advanced Research Projects Agency Network


(ARPANET) was a project funded by the U.S. Department of Defense's Advanced
Research Projects Agency (ARPA). It aimed to create a computer network that
could withstand failures and continue functioning even if parts of it were damaged.
ARPANET is often considered the precursor to the internet.

2. 1970s - Packet Switching: The concept of packet switching, developed by Paul


Baran and Donald Davies, allowed data to be broken into packets and sent across a
network to its destination. This approach made communication more efficient and
robust.

3. 1980s - TCP/IP and the Birth of the Internet: The Transmission Control Protocol
(TCP) and Internet Protocol (IP) were developed by Vinton Cerf and Robert Kahn.
These protocols standardized data transmission across different types of networks,
creating the foundation for the modern internet.

4. 1983 - Domain Name System (DNS): The DNS was introduced to replace the need
for users to memorize numerical IP addresses. DNS translates human-readable
domain names (like www.example.com) into IP addresses that computers
understand.

5. 1990s - World Wide Web: British computer scientist Tim Berners-Lee invented
the World Wide Web in 1989 while working at CERN. He created the first web
browser and web server, making it possible to access web pages with hyperlinks,
images, and multimedia.

6. 1990s - Commercialization and Dot-com Boom: The 1990s saw the


commercialization of the internet and the rise of the dot-com boom, with companies

3|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

rushing to establish an online presence. Many new internet-based businesses


emerged, though some also faced a crash in the early 2000s.

7. 2000s and Beyond - Internet Evolution: The 2000s brought advancements like
broadband internet, increased connectivity, and the proliferation of online services
and social media platforms. The rise of smartphones and mobile internet further
transformed how people access the web.

8. Current State - Internet of Things (IoT) and Beyond: Today, the internet has
expanded to include not only computers and smartphones but also a wide range of
connected devices known as the Internet of Things (IoT). This includes smart home
devices, wearables, and more. Additionally, the internet continues to evolve with
the development of technologies like 5G, artificial intelligence, and blockchain.

The history of the internet is marked by collaboration, innovation, and the pursuit of
making information and communication more accessible and efficient. It has become an
integral part of modern society, impacting almost every aspect of our lives.

Protocols of Internet:

The protocols of the internet are a set of rules and conventions that govern how data is
transmitted, received, and interpreted across computer networks. These protocols enable
devices to communicate and exchange information seamlessly. Here are some of the key
protocols that form the foundation of the internet:

1. TCP/IP (Transmission Control Protocol/Internet Protocol): TCP/IP is a suite of


protocols that serves as the backbone of the internet. It enables data to be broken
down into packets, which are then transmitted over networks and reassembled at the
destination. TCP ensures reliable and ordered delivery of data packets, while IP is
responsible for addressing and routing those packets.

2. HTTP (Hypertext Transfer Protocol): HTTP is used for transferring hypertext


(text that contains links) over the web. It's the protocol that allows your browser to
request web pages from servers and receive the corresponding content. For secure
communication, HTTPS (HTTP Secure) uses encryption to protect data during
transmission.

4|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

3. FTP (File Transfer Protocol): FTP is used to transfer files between computers on
a network. It's commonly used for uploading files to a website's server or
downloading files from a server to a local machine.

4. SMTP (Simple Mail Transfer Protocol): SMTP is used for sending emails. It
defines how emails are sent from a client to a server and how servers communicate
to deliver emails to recipients.

5. POP3 (Post Office Protocol version 3) and IMAP (Internet Message Access
Protocol): These protocols are used for receiving emails. POP3 downloads emails
to a local device, while IMAP allows users to access their emails directly from the
server, keeping them synchronized across devices.

6. DNS (Domain Name System): DNS translates human-readable domain names


(like "google.com") into IP addresses that computers can understand. It's what
allows you to use domain names instead of memorizing numerical IP addresses.

7. DHCP (Dynamic Host Configuration Protocol): DHCP is used to automatically


assign IP addresses and other network configuration parameters to devices on a
network. It simplifies the process of connecting devices to networks.

8. ICMP (Internet Control Message Protocol): ICMP is used for sending error
messages and operational information about network conditions. It's commonly
associated with the "ping" command to test network connectivity.

9. ARP (Address Resolution Protocol): ARP is used to map IP addresses to physical


MAC addresses in a local network. It helps devices identify each other in the same
network segment.

10. SSH (Secure Shell): SSH is a cryptographic network protocol used for secure
remote access to devices and servers. It provides encrypted communication over an
unsecured network.

11. SSL/TLS (Secure Sockets Layer/Transport Layer Security): These protocols


provide secure and encrypted communication between a client and a server. They
are commonly used for securing sensitive data, such as online transactions and login
credentials.

5|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

These protocols, among others, work together to enable communication, data transfer, and
various online services on the internet. They ensure that devices and systems can
interoperate reliably and securely across different networks and platforms.

World Wide Web:

The World Wide Web (WWW or simply the web) is a system of interconnected
documents and resources that are accessed via the internet using web browsers. It's a
subset of the broader internet and is a fundamental aspect of how people interact with
digital content, information, and services online. Here's a closer look at the World Wide
Web:

Key Components:

1. Web Pages: Web pages are individual documents created using HTML (Hypertext
Markup Language), which is a standardized language for structuring content on the
web. These pages can contain text, images, videos, links, forms, and other
interactive elements.

2. Hyperlinks: Hyperlinks (often referred to as "links") are clickable elements within


web pages that connect to other web pages, resources, or documents. They enable
users to navigate between different parts of a website or to access external content.

3. URL (Uniform Resource Locator): URLs are addresses used to locate specific
resources on the web. They consist of the protocol (e.g., "http" or "https"), the
domain name (e.g., "www.example.com"), and the path to the resource (e.g.,
"/page.html").

4. HTTP and HTTPS: Hypertext Transfer Protocol (HTTP) is the protocol that
defines how web browsers and web servers communicate to request and deliver
web pages. HTTPS (HTTP Secure) is a secure version of HTTP that uses
encryption to protect data transmission.

5. Web Browsers: Web browsers (e.g., Chrome, Firefox, Safari, Edge) are
applications that interpret HTML, CSS, and JavaScript code to display web pages.

6|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

They enable users to navigate the web, interact with content, and access online
services.

History and Evolution:

The World Wide Web was invented by British computer scientist Tim Berners-Lee while
he was working at CERN (the European Organization for Nuclear Research) in the late
1980s. Berners-Lee proposed a system that allowed information to be linked together
using hypertext. He developed the first web browser ("WorldWideWeb") and the first web
server, laying the foundation for what we now know as the web.

The web gained popularity in the 1990s as browsers and web development tools became
more accessible. The introduction of graphical web browsers like Mosaic and Netscape
Navigator made the web more visually appealing and user-friendly. During this time,
websites began to incorporate images, multimedia, and early forms of interactivity.

Modern Web:

The modern web is characterized by dynamic and interactive content. Web development
technologies like JavaScript, CSS, and various libraries and frameworks have allowed for
sophisticated user interfaces and experiences. Websites now offer online shopping, social
networking, multimedia streaming, educational resources, and much more.

The rise of mobile devices led to the development of responsive web design, which
ensures that websites adapt and display correctly on different screen sizes.

Additionally, web services and APIs (Application Programming Interfaces) have enabled
the integration of web functionality into other applications, allowing for data sharing and
enhanced user experiences.

Overall, the World Wide Web has revolutionized the way we access and share
information, communicate, conduct business, and engage with digital content in our daily
lives.

URL:

A URL (Uniform Resource Locator) is a reference or address used to locate a resource on


the internet. It's essentially a way to specify the location of a particular file, webpage,
image, video, or any other resource that can be accessed online. URLs are the links you

7|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

click on or enter into your web browser's address bar to access websites and online
content.

A URL is composed of several components, each of which provides specific information


about the location and type of resource you're trying to access. Here's a breakdown of the
components of a typical URL:

1. Protocol: This indicates the method or protocol that will be used to access the
resource. Common protocols include "http" (Hypertext Transfer Protocol) and
"https" (Hypertext Transfer Protocol Secure) for web pages, "ftp" (File Transfer
Protocol) for file downloads, and "mailto" for email addresses.

2. Domain: The domain name is the human-readable address of the website. For
example, in the URL "https://www.example.com," "www.example.com" is the
domain name.

3. Subdomain: Sometimes, a URL might include a subdomain that precedes the main
domain. Subdomains allow websites to organize content and services. For instance,
in "https://blog.example.com," "blog" is the subdomain.

4. Top-Level Domain (TLD): The TLD is the last part of the domain name,
indicating the type of organization or country associated with the website. Common
TLDs include ".com," ".org," ".net," and country-specific TLDs like ".uk" or ".ca."

5. Path: The path specifies the specific location of the resource within the website's
directory structure. It's represented as a forward slash (/) followed by a series of
directories and filenames. For example, in
"https://www.example.com/page/index.html," "/page/index.html" is the path.

6. Query Parameters: Query parameters, also known as query strings, are used to
pass data to a resource, such as a script or a database. They follow a question mark
(?) and consist of key-value pairs separated by ampersands (&). For example, in
"https://www.example.com/search?q=keyword," "?q=keyword" is the query
parameter.

7. Fragment Identifier: The fragment identifier, often preceded by a hash (#) symbol,
points to a specific section within a web page. It's often used to direct users to a
particular part of a long webpage. For example, in
"https://www.example.com/article#section3," "#section3" is the fragment identifier.
8|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Here's an example of a complete URL:

https://www.example.com/blog/article?id=123#section2

 Protocol: "https"

 Subdomain: "www"

 Domain: "example.com"

 Path: "/blog/article"

 Query Parameter: "id=123"

 Fragment Identifier: "section2"

URLs play a crucial role in navigating and accessing content on the internet. They allow
users and systems to locate and retrieve specific resources from various websites and
servers.

Web Server:

A web server is a specialized software application or hardware device that stores and
serves web content to users over the internet. It's a foundational component of the World
Wide Web and plays a crucial role in delivering websites, web pages, images, videos, and
other digital resources to users' web browsers. Web servers handle requests from clients
(such as web browsers) and respond by sending the requested content.

Here's an overview of how web servers work and their key features:

How Web Servers Work:

1. Request-Response Cycle: When a user enters a URL in their web browser or clicks
on a link, the browser sends a request to the appropriate web server for the
requested resource.

9|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

2. Processing Requests: The web server receives the request, interprets the URL, and
identifies the specific resource being requested (e.g., a webpage, image file).

3. Retrieving Resources: If the requested resource is available, the web server


retrieves the relevant file from its storage system. This could involve accessing files
on the server's local storage or connecting to external databases.

4. Dynamic Content: In cases where the content is generated dynamically (such as


data from a database or personalized content), the web server might need to process
the data and generate the content before sending it back to the client.

5. Generating Response: The web server constructs an appropriate response that


includes the requested resource and associated metadata.

6. Sending Response: The response is sent back to the client (usually a web browser)
over the internet using the appropriate protocol, often HTTP or HTTPS.

Key Features and Functions:

1. HTTP Protocol Handling: Web servers are designed to handle HTTP (Hypertext
Transfer Protocol) requests. They understand the structure of HTTP requests and
know how to respond with HTTP responses containing requested content and
relevant status codes.

2. Content Storage: Web servers store website files, including HTML documents,
CSS stylesheets, JavaScript files, images, videos, and more. These files are
organized in a directory structure.

3. Virtual Hosting: A single web server can host multiple websites, each with its own
domain name and content. This is achieved through techniques like virtual hosting
and server configuration.

4. Load Balancing: For high-traffic websites, multiple web servers can be set up to
balance the load and ensure efficient distribution of incoming requests.

5. Security: Web servers implement security measures to protect against unauthorized


access and cyberattacks. This includes encryption (HTTPS), firewalls, and security
patches.

10 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

6. Server-Side Scripting: Some web servers support server-side scripting languages


(like PHP, Python, Ruby) that allow dynamic generation of web content before
sending it to the client.

7. Caching: Web servers can cache frequently accessed content to improve


performance and reduce the load on the server.

Common web server software includes Apache HTTP Server, Nginx, Microsoft Internet
Information Services (IIS), and LiteSpeed. These servers are configured and customized
based on the needs of the websites they host, and they work together with other
technologies like databases and scripting languages to deliver dynamic and interactive
web experiences.

Web Browser:

A web browser is a software application used to access, view, and interact with content on
the World Wide Web. It allows users to navigate websites, view web pages, access
multimedia content, and interact with various online services. Web browsers play a critical
role in making the internet accessible and user-friendly. Here's a closer look at web
browsers and their key features:

Key Features of Web Browsers:

1. User Interface: Web browsers have a graphical user interface (GUI) that includes
navigation buttons (back, forward, refresh), an address bar for entering URLs, tabs
for opening multiple web pages simultaneously, and various menu options.

2. Rendering Engine: The rendering engine is the core component of a web browser
that interprets HTML, CSS, and other web technologies to display web pages.
Different browsers use different rendering engines, such as Blink (used by
Chrome), Gecko (used by Firefox), and WebKit (used by Safari).

3. Address Bar: Users can enter URLs (Uniform Resource Locators) in the address
bar to navigate to specific websites or resources on the web.

4. Tabs: Tabs allow users to have multiple web pages open within the same browser
window, making it easier to switch between different websites or tasks.

5. Bookmarks: Bookmarks (also called favorites) allow users to save and organize
URLs for quick access later.
11 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

6. History: Browsers maintain a history of visited websites, enabling users to revisit


pages they've previously viewed.

7. Extensions and Add-ons: Many browsers support extensions or add-ons, which are
small software modules that enhance browser functionality. Extensions can provide
features like ad-blocking, language translation, and password management.

8. Security: Browsers implement security measures to protect users from malicious


websites and cyberattacks. This includes features like pop-up blockers, phishing
protection, and support for secure connections (HTTPS).

9. Privacy Settings: Browsers offer privacy controls that allow users to manage
cookies, browsing history, and other forms of online tracking.

10. Developer Tools: Web browsers come with built-in developer tools that help web
developers inspect and debug web pages, analyze performance, and experiment
with web technologies.

How Web Browsers Work:

1. User Interaction: Users interact with a browser by entering URLs, clicking links,
and using various browser features.

2. Request Handling: When a user requests a web page by entering a URL or


clicking a link, the browser sends a request to the appropriate web server.

3. Receiving and Rendering: The browser receives the HTML, CSS, and other
resources from the web server. The rendering engine interprets the code and
displays the web page accordingly.

4. Rendering Process: The rendering engine processes HTML to structure the


content, CSS to style it, and JavaScript to add interactivity. The browser displays
the rendered page on the user's screen.

5. Content Interaction: Users can interact with content on web pages through
clicking links, filling out forms, watching videos, and using various interactive
elements.

6. Security Checks: Browsers conduct security checks to identify potential threats,


such as phishing sites or malicious downloads.

12 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

7. Updates and Improvements: Web browser developers release regular updates to


improve security, performance, and compatibility with evolving web standards.

Common web browsers include Google Chrome, Mozilla Firefox, Microsoft Edge, Apple
Safari, and Opera. Each browser offers a unique user experience while adhering to web
standards to ensure websites are displayed consistently across different platforms.

HTML- Introduction:

HTML, which stands for "Hypertext Markup Language," is the standard language used to
create and structure content on the World Wide Web. It's a foundational technology for
building web pages and defining the elements and structure of a webpage's content.
HTML uses a system of tags and elements to describe the meaning and organization of
text, images, links, forms, and other types of content that make up a webpage.

Key Concepts in HTML:

1. Markup Language: HTML is a markup language, which means it uses tags to


mark elements within a document. These tags define the structure and appearance
of content on a webpage.

2. Elements and Tags: HTML elements are the building blocks of a webpage. Each
element is enclosed within opening and closing tags. Opening tags have the
element's name within angle brackets (< >), and closing tags have a forward slash
before the element's name (</ >). For example, <p> is the opening tag for a
paragraph, and </p> is the closing tag.

3. Hierarchy and Nesting: HTML elements can be nested within other elements to
create a hierarchical structure. For example, a paragraph <p> element can contain
text and other inline elements like <strong> (bold) or <a> (link).

4. Attributes: Elements can have attributes that provide additional information about
the element or modify its behavior. Attributes are added to the opening tag and are
written as name-value pairs. For instance, the <a> element can have an href
attribute to define the URL of the link.

5. Document Structure: An HTML document is typically structured with an opening


<html> tag, followed by <head> (which contains meta information) and <body>
(which contains the visible content) sections.

13 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Basic Example:

Here's a simple example of an HTML document:

<!DOCTYPE html>

<html>

<head>

<title>My First Webpage</title>

</head>

<body>

<h1>Welcome to My Webpage</h1>

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

<a href="https://www.example.com">Visit Example</a>

</body>

</html>

In this example:

 <!DOCTYPE html> defines the document type and version of HTML being used.

 <html> is the root element of the HTML document.

 <head> contains meta information about the document, like the title that appears in
the browser's tab.

 <body> contains the visible content of the webpage.

 <h1> is a heading element.

 <p> is a paragraph element.

 <a> is a link element, with an href attribute specifying the link's URL.

HTML provides the structure and semantics of content, but it doesn't control the visual
appearance directly. Styling is typically done using CSS (Cascading Style Sheets), and
14 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

interactivity is added with JavaScript. Together, HTML, CSS, and JavaScript form the
core technologies for building modern and interactive web pages.

History of HTML:

The history of HTML (Hypertext Markup Language) is closely tied to the development of
the World Wide Web and the evolution of web technologies. HTML has gone through
several versions, each introducing new features, improvements, and compatibility with the
changing demands of the web. Here's an overview of the history of HTML:

HTML 1.0 (1991):

 HTML 1.0, the earliest version of HTML, was introduced by Tim Berners-Lee, the
inventor of the World Wide Web.

 It included basic elements like headings, paragraphs, lists, and hyperlinks, allowing
for the creation of simple text-based web pages.

HTML 2.0 (1995):

 HTML 2.0 brought improvements over its predecessor, including support for inline
images and form elements.

 This version introduced the <img> and <form> elements.

HTML 3.2 (1997):

 HTML 3.2 introduced significant enhancements, including support for tables,


frames, and background images.

 Tables allowed for better layout control, while frames enabled the creation of multi-
pane web layouts.

HTML 4.01 (1999):

 HTML 4.01 further refined the language and introduced stricter rules for adhering
to standards.

 It included new structural elements like headings, paragraphs, and lists, as well as
improvements to forms, tables, and multimedia support.

XHTML 1.0 (2000):

15 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 XHTML (Extensible HyperText Markup Language) 1.0 marked a transition toward


combining HTML with XML (eXtensible Markup Language).

 XHTML was designed to be more strict in its syntax, making it more compatible
with XML tools and parsers.

HTML5 (2008 - Present):

 HTML5 is the current and most significant version of HTML. It was developed by
the World Wide Web Consortium (W3C) and the Web Hypertext Application
Technology Working Group (WHATWG).

 HTML5 introduced a wide range of new elements, attributes, and APIs, enhancing
the capabilities of web development.

 New semantic elements like <header>, <nav>, <article>, <footer>, and more
were introduced to provide better structuring of content.

 Multimedia support was greatly improved with the introduction of <video> and
<audio> elements.

 HTML5 also introduced the <canvas> element for dynamic graphics and
animations.

 Web forms received enhancements with new input types and attributes.

 APIs like the Geolocation API, Web Storage API, and WebSockets were introduced
to enable advanced web applications.

HTML Living Standard (Ongoing):

 After HTML5, the development approach shifted to a "living standard" model,


where specifications are continuously updated and refined.

 The WHATWG maintains the HTML Living Standard, which is an ever-evolving


document that describes the current state and future developments of HTML.

HTML continues to evolve to meet the demands of modern web development, with
ongoing efforts to improve accessibility, interactivity, and compatibility with different
devices and platforms.

16 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Structure of HTML Document:

An HTML (Hypertext Markup Language) document follows a specific structure that


defines the elements and organization of content on a webpage. Understanding this
structure is essential for creating well-formed and properly functioning web pages. Here's
a breakdown of the typical structure of an HTML document:

<!DOCTYPE html>

<html>
<head>
<meta charset="UTF-8">
<title>Page Title</title>
</head>
<body>
<!-- Content goes here -->
</body>
</html>
Let's delve into the details of each section:

1. <!DOCTYPE html> Declaration: This is the document type declaration and


indicates that you are using HTML5. It helps browsers interpret the document
correctly. The declaration should be placed at the very beginning of your HTML
document.

2. <html> Element: The <html> element is the root element of an HTML document.
It wraps around all other content on the page. Inside the <html> element, you'll find
the <head> and <body> elements.

3. <head> Element: The <head> element contains meta-information about the


document, such as the character encoding, title, and links to external resources like
stylesheets and scripts. It doesn't display content directly on the page.

17 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 <meta charset="UTF-8">: This meta tag specifies the character encoding


for the document, usually set to UTF-8 to support a wide range of characters
and languages.

 <title>: This element sets the title of the webpage, which is displayed in the
browser's tab or window title bar.

4. <body> Element: The <body> element contains the visible content of the
webpage, including text, images, videos, forms, and other elements that users
interact with.

 You'll place all your content within the <body> element. This is where your
text, headings, paragraphs, links, images, and other visual elements go.

Example:

<body>

<h1>Welcome to My Webpage</h1>

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

<img src="image.jpg" alt="An example image">

<a href="https://www.example.com">Visit Example</a>

</body>

In this example, there's an <h1> heading, a <p> paragraph, an <img> image, and an
<a> link within the <body>.

This basic structure provides a foundation for creating web pages. You'll add your
content within the <body> section and can enhance the page further with CSS for styling
and JavaScript for interactivity. Keep in mind that HTML is hierarchical, so elements can
be nested within one another to create more complex layouts and structures.

Text Basics:

Text is a fundamental component of web content, and understanding how to work with
text in HTML (Hypertext Markup Language) is essential for creating well-structured and
visually appealing web pages. Here are the basics of working with text in HTML:

18 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Text Elements:

1. Headings (<h1> to <h6>): Headings are used to create hierarchical structure and
emphasize different sections of content. <h1> is the highest level (main title), and
<h6> is the lowest level (subheading).

Example:

<h1>Main Title</h1>

<h2>Subheading</h2>

<h3>Another Subheading</h3>

2. Paragraphs (<p>): The <p> element is used to create paragraphs of text. It's the
standard way to present blocks of content, and browsers automatically add spacing
between paragraphs.

Example:

<p>This is a paragraph of text. It provides context and information.</p>

3. Text Formatting:

 Bold (<strong> or <b>): The <strong> element (or <b>) is used to indicate strong
importance or emphasis. It typically renders as bold text.

 Italic (<em> or <i>): The <em> element (or <i>) is used to indicate emphasis, and
it usually renders as italicized text.

Example:

<p>This is <strong>important</strong> information.</p>

<p>This text is <em>emphasized</em>.</p>

4. Line Breaks (<br>): The <br> element is used to create a line break within text,
allowing you to force text onto a new line.

Example:

19 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<p>This is the first line.<br>This is the second line.</p>

5. Horizontal Rule (<hr>): The <hr> element creates a horizontal rule, which is a
visible line that can be used to separate content.

Example:

<p>This is above the rule.</p>

<hr>

<p>This is below the rule.</p>

6. Text Content: You can include regular text directly within elements. HTML will
preserve spaces and line breaks, but consecutive spaces may be collapsed into a
single space.

Example:

<p>This is some text with multiple spaces.</p>

7. Whitespace: HTML generally treats consecutive spaces and line breaks as a single
space. To create significant whitespace, you can use the HTML entity &nbsp;
(non-breaking space) or CSS properties.

Example:

<p>This is&nbsp;an example&nbsp;of&nbsp;non-breaking spaces.</p>

These are the foundational concepts of working with text in HTML. As you
continue learning, you'll discover how to use CSS to style text, adjust fonts, colors, and
sizes, and create more advanced text layouts.

Structure of HTML Document: Images:

Adding images to your HTML (Hypertext Markup Language) documents can enhance
visual appeal and convey information effectively. Images can be photographs,
illustrations, icons, logos, and more. Here's how you can include images in your HTML
documents:

20 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Using the <img> Element:

The <img> element is used to embed images in an HTML document. It's a self-closing
tag, meaning it doesn't have a closing tag. Instead, it uses attributes to provide information
about the image.

<img src="image.jpg" alt="Description of the image">

 src: The src attribute specifies the URL (file path) of the image. This is the most
important attribute, as it tells the browser where to find the image.

 alt: The alt attribute provides alternative text that's displayed if the image cannot be
loaded or if the user is using assistive technologies like screen readers. It's also
useful for search engines and improves accessibility.

Example:

<!DOCTYPE html>
<html>
<head>
<title>Image Example</title>
</head>
<body>
<h1>Adding Images to Your Page</h1>
<p>Here's an example image:</p>
<img src="example.jpg" alt="An example image">
</body>
</html>
In this example, the image file "example.jpg" is located in the same directory as the
HTML document. The image is displayed within the paragraph, and if the image cannot
be loaded, the text "An example image" will be shown.

Image Attributes:

21 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

In addition to the src and alt attributes, you can use other attributes to further
customize how images are displayed:

 width: Specifies the width of the image in pixels or a percentage of the parent
container.

 height: Specifies the height of the image in pixels or a percentage.

 title: Provides additional information about the image when the user hovers over it.
It's displayed as a tooltip.

 align: Specifies how the image should be aligned with surrounding content. This
attribute is now deprecated in favor of using CSS for alignment.

Image Formats:

Common image formats used on the web include JPEG (.jpg), PNG (.png), GIF
(.gif), and SVG (.svg). Choose the format that best suits the type of image and the desired
level of quality and compression.

Remember that images should be appropriately sized and optimized for the web to
ensure faster loading times and a better user experience.

Multimedia, Links And Webs:

Multimedia:

Multimedia refers to content that combines various forms of media, such as text, images,
audio, video, animations, and interactive elements. It enriches the user experience by
providing a dynamic and engaging way to present information. In web development,
multimedia elements can be seamlessly integrated into HTML documents using
appropriate HTML tags or other technologies. Here are some key multimedia elements:

1. Images (<img>): Images are commonly used to convey visual information on


websites. You can include images using the <img> element and specify the src
attribute to provide the image URL.

2. Audio (<audio>): The <audio> element allows you to embed audio files directly
within web pages. You can control playback, volume, and other audio settings using
HTML attributes.

22 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

3. Video (<video>): Similar to audio, the <video> element lets you embed videos on
your web pages. You can specify video sources, set controls, and add captions or
subtitles.

4. Embedding Content: You can embed content from external sources like YouTube
or social media platforms by using embedded players or iframes.

5. Animations and Interactivity: You can use technologies like CSS animations and
JavaScript to create interactive and animated multimedia elements.

Links:

Links are an essential aspect of web navigation, allowing users to move from one
webpage to another, access resources, and explore different parts of the internet. In
HTML, links are created using the <a> (anchor) element. Here's how they work:

<a href="https://www.example.com">Visit Example</a>

 href: The href attribute specifies the URL that the link points to.

 Text: The text between the opening and closing <a> tags is the visible link text that
users click on.

Web:

The term "web" often refers to the World Wide Web, a system of interconnected
documents and resources accessible over the internet. It's the medium through which users
access information, services, and interact with content online. Here are some key concepts
related to the web:

1. Web Pages: Web pages are individual documents created using HTML that are
viewed in web browsers. They can include text, images, multimedia, and interactive
elements.

2. Web Servers: Web servers store and serve web content to users' browsers upon
request. They play a crucial role in delivering web pages and resources over the
internet.

23 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

3. Web Browsers: Web browsers are software applications that users use to access
and interact with web content. They interpret HTML, CSS, and JavaScript to render
web pages.

4. Hyperlinks: Hyperlinks are clickable elements that connect web pages and
resources. They allow users to navigate between different parts of a website or
access external content.

5. URLs (Uniform Resource Locators): URLs are addresses used to locate resources
on the web. They consist of a protocol (http/https), domain, path, and other
components.

6. Web Development: Web development involves creating and maintaining websites


and web applications. It includes front-end development (HTML, CSS, JavaScript)
and back-end development (server-side scripting, databases).

7. Web Standards: Web standards ensure consistency and compatibility across


different browsers and devices. Organizations like the W3C and WHATWG
develop and maintain these standards.

The web is a dynamic and ever-evolving platform that connects people, information, and
services on a global scale. It has transformed the way we communicate, access
information, and conduct business.

Document Layout:

Document layout in web development refers to the arrangement and positioning of


elements on a web page to create a visually appealing and functional design. The layout
determines how content is organized, how different elements relate to each other, and how
users navigate through the page. Achieving a well-structured and responsive layout is
crucial for providing a positive user experience across different devices and screen sizes.

Here are key concepts and techniques related to document layout in web development:

1. HTML Structure: The structure of your HTML document provides the foundation for
your layout. Use structural elements like headings, paragraphs, lists, and semantic tags
(such as <header>, <nav>, <main>, <article>, <footer>) to properly organize your
content.

24 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

2. CSS for Styling: Cascading Style Sheets (CSS) is used to control the visual
presentation of your HTML elements. You can define styles for text, colors, spacing, and
more. CSS enables you to create consistent and aesthetically pleasing layouts.

3. Box Model: The box model in CSS describes how elements are structured and spaced.
Each HTML element is treated as a rectangular box with content, padding, borders, and
margins. Understanding the box model is crucial for precise layout control.

4. Positioning: CSS offers different positioning techniques to control how elements are
placed on the page. The position property includes values like static, relative, absolute,
and fixed, each affecting the element's position within its parent or the viewport.

5. Display Property: The display property controls how elements are displayed in
relation to other elements. Common values include block (takes up full width), inline
(only as wide as content), and inline-block (combines inline and block behaviors).

6. Flexbox Layout: Flexbox is a CSS layout model that provides a flexible way to align
and distribute elements within a container. It's especially useful for creating dynamic
layouts and aligning items along the main and cross axes.

7. CSS Grid Layout: CSS Grid is a two-dimensional layout system that allows you to
create complex grid-based layouts. It's useful for arranging items in both rows and
columns and works well for responsive designs.

8. Responsive Design: With the prevalence of various devices and screen sizes,
responsive design is essential. Use media queries in CSS to adapt your layout based on
factors like screen width. This ensures your layout looks and functions well across
different devices.

9. Mobile-First Design: Mobile-first design involves designing for mobile devices first
and then adapting the layout for larger screens. This approach ensures a user-friendly
experience on smaller screens and simplifies scaling up.

10. Frameworks and Libraries: Frameworks like Bootstrap and libraries like Flexbox
and CSS Grid frameworks provide pre-designed layout components and structures,
helping developers create consistent and responsive designs more efficiently.

25 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

By understanding and implementing these concepts and techniques, you can create layouts
that effectively organize content, enhance user engagement, and adapt to various screen
sizes and devices.

Here's an example of a basic web page layout using HTML and CSS. We'll create a simple
layout with a header, navigation menu, main content area, and footer. This layout will use
CSS Flexbox for its simplicity in arranging elements

HTML:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Sample Layout</title>
</head>
<body>
<header>
<h1>My Website</h1>
</header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<main>

26 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<section>
<h2>Welcome to Our Website!</h2>
<p>This is the main content section of our webpage.</p>
</section>
</main>
<footer>
<p>&copy; 2023 My Website. All rights reserved.</p>
</footer>
</body>
</html>

CSS (styles.css):
/* Reset some default styles and set a base font size */
body, h1, h2, h3, p {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}

/* Basic styling for the header */


header {
background-color: #333;
color: #fff;
text-align: center;
padding: 1rem;
}

/* Styling for the navigation menu */


nav {
background-color: #555;
color: #fff;

27 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

display: flex;
justify-content: center;
padding: 0.5rem 0;
}

nav ul {
list-style: none;
display: flex;
}

nav li {
margin: 0 1rem;
}

nav a {
text-decoration: none;
color: #fff;
}

/* Styling for the main content section */


main {
padding: 2rem;
}

section {
border: 1px solid #ddd;
padding: 1rem;
}

/* Styling for the footer */


footer {
background-color: #333;
color: #fff;
text-align: center;
padding: 1rem;
}

In this example:

 The <header> contains the website's main title.

28 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 The <nav> contains navigation links using an unordered list (<ul>) and list items
(<li>).

 The <main> element holds the main content, and within it, a <section> with some
sample text.

 The <footer> contains copyright information.

The CSS styles defined in the styles.css file use Flexbox to align and arrange elements
within their respective sections.

Remember that this is a simplified example. In real-world scenarios, you would likely
have more complex content and styles, and you might consider using CSS Grid or other
layout techniques for more advanced layouts.

Creating Forms:

Creating forms in HTML allows users to submit data to a web server for processing.
Forms are essential for various purposes, such as user registration, login, contact forms,
surveys, and more. Here's how you can create basic HTML forms:

Basic Form Structure:

<!DOCTYPE html>
<html>
<head>
<title>Sample Form</title>
</head>
<body>
<h1>Contact Us</h1>
<form action="process-form.php" method="post">
<!-- Form fields go here -->
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>

29 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" required></textarea>
<button type="submit">Submit</button>
</form>
</body>
</html>
Explanation:

 <form>: The <form> element defines the container for form elements. The action
attribute specifies where the form data will be sent, and the method attribute
specifies the HTTP method (post or get) to use when sending data.

 <label>: The <label> element associates a label with an input field. It improves
accessibility and user experience.

 <input>: The <input> element is used for single-line input fields. Common types
include text, email, password, checkbox, radio, etc.

 <textarea>: The <textarea> element is used for multiline text input fields. The
rows attribute specifies the visible number of lines.

 <button>: The <button> element creates a button for submitting the form. The
type attribute can be set to submit, reset, or button.

 required: The required attribute indicates that a field must be filled out before the
form can be submitted.

Server-Side Processing:

After the user submits the form, the data is typically sent to a server for processing. The
action attribute of the form specifies the server-side script or URL where the form data
will be sent. The server-side script (e.g., PHP, Python, Node.js) receives the data and
processes it as needed.

30 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

For example, if you're using PHP, you can create a process-form.php script to handle the
form data:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Process and save the data as needed
}
?>
Remember that this is a basic example, and real-world forms may involve additional
validation, security measures, and more complex processing.

When creating forms, consider user experience, accessibility, and security best practices.
Always validate and sanitize user input on the server-side to prevent potential security
vulnerabilities.

Frames and Tables:

Frames and tables are both older HTML elements that were commonly used for layout
and structuring content on web pages. However, they have become somewhat outdated
due to advancements in web design techniques and the introduction of more modern
layout methods like CSS Grid and Flexbox. Nonetheless, understanding frames and tables
can provide insights into the history of web development.

Frames:

Frames allowed developers to divide a web page into multiple sections, each containing a
separate HTML document. This was often used to create complex layouts with multiple
independent scrollable areas. Frames were defined using the <frame> and <frameset>
elements.

Example of a frameset:

31 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<!DOCTYPE html>

<html>

<head>

<title>Frames Example</title>

</head>

<frameset cols="25%,75%">

<frame src="menu.html" />

<frame src="content.html" />

</frameset>

</html>

Due to various usability and accessibility issues, frames have fallen out of favor. Instead,
modern layouts are achieved using CSS techniques like Flexbox and Grid, which offer
more control over positioning and responsiveness.

Tables:

Tables were often used to structure content into rows and columns, similar to a
spreadsheet. They were initially designed for displaying tabular data but were sometimes
misused for layout purposes, resulting in "table-based layouts."

Example of a basic table:

<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
32 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
While tables are still valid for displaying actual tabular data, they are discouraged for
creating page layouts due to accessibility issues, difficulty in maintaining responsive
designs, and the availability of better layout techniques like CSS Grid and Flexbox.

Modern Alternatives:

For complex layouts, use modern CSS techniques such as:

 CSS Grid: A powerful two-dimensional layout system that allows you to create
complex grid-based layouts with ease.

 Flexbox: A one-dimensional layout model that excels at distributing space and


aligning items along a single axis.

 CSS Positioning: Control the position of elements using properties like position,
top, right, bottom, and left.

By using these modern methods, you can achieve more flexible, responsive, and
accessible layouts while adhering to current web standards.

Cascading Style Sheets:

Cascading Style Sheets, commonly known as CSS, is a stylesheet language used to


describe the presentation and styling of HTML (Hypertext Markup Language) documents.
CSS separates the content and structure of a webpage from its visual design, allowing
developers to control how elements are displayed on the screen, in print, or on other
media.

CSS provides the following benefits:

33 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

1. Separation of Concerns: CSS allows you to separate the structure (HTML) from
the style (CSS) and behavior (JavaScript) of a webpage. This separation makes it
easier to maintain and update different aspects of your site.

2. Consistency: CSS enables consistent styling across multiple pages of a website.


You can define styles once and apply them to multiple elements, ensuring a unified
look and feel.

3. Ease of Maintenance: With CSS, you can make global changes to the design of
your site by modifying a few lines of code in a CSS file, rather than updating each
HTML element individually.

4. Responsive Design: CSS allows you to create responsive designs that adapt to
different screen sizes and devices, improving the user experience on smartphones,
tablets, and desktops.

5. Accessibility: By applying proper CSS techniques, you can enhance the


accessibility of your site for users with disabilities, improving readability and
navigation.

6. Efficiency: CSS reduces redundancy by allowing you to apply styles to multiple


elements using classes and IDs. This minimizes the amount of code and speeds up
page loading.

How CSS Works:

CSS works by associating style rules with HTML elements. These rules define how
elements should be displayed. Each style rule consists of a selector and a declaration
block.

selector

property: value;

/* more properties */

34 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 Selector: The selector identifies the HTML elements to which the styles will be
applied. Selectors can target specific elements, classes, IDs, attributes, and more.

 Property: The property specifies what aspect of the element's style will be
modified. Examples include color, font-size, margin, padding, background, etc.

 Value: The value is the setting you assign to the property. It can be a color, size,
measurement, keyword, or other valid value.

Example:

Here's a simple CSS example that changes the color and font size of all <h1> elements:

h1

color: blue;

font-size: 24px;

CSS can be included in an HTML document using the <style> element within the
document's <head> section or in an external CSS file linked to the HTML using the
<link> element.

<!DOCTYPE html>

<html>

<head>

<link rel="stylesheet" type="text/css" href="styles.css">

<title>My Website</title>

</head>

<body>

<h1>Welcome to My Website</h1>

<p>This is some content.</p>

35 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

</body>

</html>

In this example, the styles.css file contains the CSS rules that will be applied to the
HTML elements on the page.

CSS is a powerful tool that empowers web developers to create visually appealing and
responsive websites. It's important to learn and understand CSS in conjunction with
HTML to become proficient in web development.

TYPES OF Cascading Style Sheets:

Cascading Style Sheets (CSS) come in different types or levels, each representing a
version of the CSS specification with new features, improvements, and changes. Here are
some of the main types of CSS:

1. CSS1 (Cascading Style Sheets Level 1): CSS1 was the initial version of CSS
introduced in 1996. It provided basic styling capabilities for web documents, including
font styles, colors, and text alignment. However, it had limited support for layout control.

2. CSS2 (Cascading Style Sheets Level 2): CSS2 was released in 1998 and built upon
the foundation of CSS1. It introduced significant improvements, including support for
positioning and layout through the introduction of properties like position, float, and
clear. It also added features like z-index and media types for print and screen.

3. CSS2.1: CSS2.1 is essentially a cleaned-up version of CSS2 with some features


removed due to inconsistencies and browser-specific issues. It became a W3C
recommendation in 2011 and is widely supported by modern web browsers.

4. CSS3 (Cascading Style Sheets Level 3): CSS3 refers to a collection of individual
modules, each introducing new features and capabilities. Unlike previous versions, CSS3
is not a single specification but a set of independent modules. Some of the notable CSS3
modules include:

 Selectors: Introduced advanced selectors like :nth-child(), :not(), and more.

 Box Model: Added features like box-sizing and border-radius for more flexible
layout and design.

36 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 Backgrounds and Borders: Introduced gradients, multiple background images,


and rounded borders.

 Text Effects: Added properties for text shadows, multi-column layouts, and text
wrapping.

 Transitions and Animations: Provided mechanisms for creating smooth


transitions and animations using transition and @keyframes.

 Transforms: Enabled 2D and 3D transformations, including scaling, rotation, and


perspective.

 Media Queries: Allowed responsive design by applying styles based on the


device's characteristics, such as screen size.

 Flexbox and Grid: Introduced powerful layout tools, CSS Flexbox and CSS Grid,
for creating complex layouts.

5. CSS4: Unlike previous versions, CSS4 doesn't represent a new level of CSS
specification. Instead, the development of CSS continues as a single specification called
the CSS "Living Standard." It is continuously updated with new features, improvements,
and changes.

Keep in mind that CSS is an evolving technology, and new features are being developed
and added over time. It's essential for web developers to stay updated with the latest
specifications and best practices to create modern and responsive web designs.

37 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

Unit-2
UNIT II:
XML Introduction- Introduction of XML, , Defining XML tags, their attributes and values,
Document Type Definition, XML Schemes, Document Object Model, XHTML Parsing XML
Data – DOM and SAX Parsers in java.

Introduction of XML:

XML (eXtensible Markup Language) is a versatile markup language designed to store,


transport, and structure data in a human-readable and machine-readable format. It's not
designed to display data like HTML, but rather to describe and categorize structured
information. XML plays a crucial role in data exchange between applications, platforms,
and databases. Here's an introduction to XML:

Key Concepts of XML:

1. Markup Language: Like HTML, XML uses tags to define elements within a
document. However, unlike HTML, XML doesn't prescribe how elements should
be displayed; it's used to define data elements and their relationships.

2. Hierarchical Structure: XML documents have a hierarchical structure consisting


of elements nested within one another. This structure allows for the representation
of complex relationships.

3. Tags and Elements: XML elements are enclosed in angle brackets, like
<element>, and consist of a start tag, content, and an end tag (</element>).
Elements can have attributes with values.

4. Well-Formed vs. Valid: An XML document must be "well-formed," adhering to


specific syntax rules. Additionally, it can be "valid" if it adheres to a specific
document type definition (DTD) or schema.

5. Elements and Text: XML documents can contain elements, attributes, and text
data. Text data is enclosed within elements, making it possible to structure
information logically.

Example of an XML Document:

1|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

<person>

<name>John Doe</name>

<age>30</age>

<address>

<street>Main Street</street>

<city>Cityville</city>

</address>

</person>

In this example, the XML document describes a person's information with nested elements
for name, age, and address.

Use Cases for XML:

1. Data Exchange: XML is used to exchange data between different software systems
regardless of their platforms or programming languages. It's commonly used in web
services, APIs, and data integration.

2. Configuration Files: XML can be used to store configuration settings for


applications. Software can read and interpret these settings to customize behavior.

3. Data Storage: XML is used to store structured data in a human-readable format.


Databases can export data in XML format, making it accessible to other
applications.

4. Syndication and Feeds: RSS and Atom feeds use XML to syndicate content and
updates from websites to subscribers.

5. Web Services: SOAP (Simple Object Access Protocol) messages, which enable
communication between different systems, are XML-based.

Limitations and Alternatives:

XML can be verbose, which can lead to larger file sizes compared to other data
interchange formats like JSON (JavaScript Object Notation). JSON is commonly used in

2|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

modern web development due to its lightweight syntax and easy integration with
JavaScript.

In summary, XML is a versatile markup language that serves as a foundation for data
exchange and storage. While it's not as prevalent as it once was, it still has its use cases,
especially in scenarios where compatibility and structured data are important.

Defining XML Tags:

In XML (eXtensible Markup Language), tags are used to define the elements and structure
of the data within the document. Each XML tag consists of a start tag, content, and an end
tag. Tags are enclosed in angle brackets <>.

Here's how XML tags are defined:

1. Start Tag: The opening tag that defines the beginning of an element. It contains the
name of the element and can also include attributes.

<elementName attribute="value">

2. End Tag: The closing tag that defines the end of an element. It has the same name
as the start tag but with a forward slash / before the element name.

</elementName>

3. Self-Closing Tag: For elements without content, you can use a self-closing tag. It
combines the start and end tags into one tag.

<emptyElement />

4. Content: The data or text enclosed within the start and end tags. It's the actual
information that the XML element represents.

Here's an example of XML tags in action:

<person>
<name>John Doe</name>
<age>30</age>
<address>
3|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

<street>Main Street</street>
<city>Cityville</city>
</address>
</person>
In this example:

 <person> is the start tag of the root element.

 </person> is the end tag of the root element.

 <name> and </name> define the start and end tags of the "name" element.

 The text "John Doe" is the content of the "name" element.

Remember that XML is case-sensitive, so <person> and <Person> would be treated as


different tags. Additionally, you can use attributes within the start tags to provide
additional information about the element. For example:

<book ISBN="123456789">

<title>XML Basics</title>

<author>Jane Smith</author>

</book>

In this example, the <book> element has an "ISBN" attribute with the value
"123456789".

XML tags play a crucial role in defining the structure of data in XML documents, enabling
the representation of complex hierarchical relationships and structured information.

Their Attributes And Values:

In XML, attributes provide additional information about an element. Attributes are


defined within the opening tag of an element and consist of a name-value pair. The value
is enclosed in quotation marks (single or double).

4|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

Here's how attributes and their values are used in XML:

<elementName attributeName="attributeValue">

Let's consider an example of an XML document describing a book:

<book ISBN="123456789">

<title>XML Basics</title>

<author>Jane Smith</author>

</book>

In this example:

 <book> is the start tag of the "book" element.

 ISBN is the attribute name, and "123456789" is the attribute value.

 The <title> and <author> elements are nested within the <book> element.

You can have multiple attributes within a single opening tag:

<person firstName="John" lastName="Doe" age="30">

<address street="Main Street" city="Cityville" />

</person>

Here, the <person> element has attributes firstName, lastName, and age.

Attributes are used to provide metadata or additional information about the element.
They are commonly used for specifying identifiers, classes, styles, or any other data that
doesn't fit within the content of the element.

Remember the following when working with XML attributes:

5|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

 Attribute names are case-sensitive and must be unique within an element.

 Attribute values are enclosed in single or double quotes.

 You can use both single and double quotes interchangeably.

 Attributes provide information about the element and don't affect the content
structure.

It's important to use attributes appropriately and adhere to the conventions of the
specific XML format or schema you're working with.

Document Type Definition:

A Document Type Definition (DTD) is a formal set of rules that defines the structure and
the legal elements and attributes of an XML document. DTDs ensure that XML
documents adhere to a specific structure, making them easier to validate and process.
DTDs are a legacy method for defining the structure of XML documents, and they have
been largely replaced by XML Schemas (XSD) for more advanced validation.

Here's an introduction to DTDs:

DTD Structure:

A DTD is an external file or an internal subset of an XML document that defines the rules
for valid elements, attributes, and their relationships. DTDs define elements using angle
brackets and pipes (|) to indicate choices and parentheses to indicate grouping.

Here's a basic example of a DTD for a simple "book" element:

<!DOCTYPE catalog [

<!ELEMENT catalog (book+)>

<!ELEMENT book (title, author)>

<!ELEMENT title (#PCDATA)>

<!ELEMENT author (#PCDATA)>

6|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

]>

In this example:

 <!DOCTYPE catalog [...]> declares the document type and the internal DTD subset.

 <!ELEMENT> defines the structure of elements. For example, (book+) indicates


that the "catalog" element can contain one or more "book" elements.

 <!ELEMENT title (#PCDATA)> defines the "title" element as containing parsed


character data (#PCDATA), meaning it can hold text content.

Attributes in DTD:

Attributes can also be defined in a DTD using the <!ATTLIST> declaration. For instance:

<!ATTLIST book ISBN CDATA #REQUIRED>

In this example, ISBN is the attribute name, CDATA specifies the attribute type as
character data, and #REQUIRED indicates that the attribute is mandatory.

DTD Validation:

XML documents can be validated against a DTD to ensure that they adhere to the
defined structure. Validation helps catch errors early in the development process and
ensures data consistency.

Limitations and Alternatives:

While DTDs are a standardized way to define XML document structures, they have some
limitations:

 Limited support for data types and constraints.

 Lack of support for namespaces.

 Complex syntax for more advanced structures.

7|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

XML Schemas (XSD) address many of these limitations and offer more powerful
validation and structural definition capabilities. XSD provides data types, namespaces,
and more expressive structures.

In modern XML development, XML Schemas are often preferred over DTDs due to their
more comprehensive features and better support for complex document structures and
data validation.

XML Schemes:
I believe you are referring to "XML Schemas," which are a more advanced and modern
way of defining the structure and rules for XML documents. XML Schemas provide a
more powerful and flexible way to validate and describe the structure of XML data
compared to Document Type Definitions (DTDs). Let's dive into XML Schemas:

XML Schema Definition (XSD):

An XML Schema, often referred to as XSD, is a standard for defining the structure,
content, and data types of XML documents. It offers a more precise and expressive way
to specify the allowed elements, attributes, and their relationships within an XML
document.

Key Features of XML Schemas:

1. Data Types: XSD supports a variety of data types, including strings, numbers,
dates, and more. This enables precise validation and description of data values.

2. Complex Types: XML Schemas allow you to define complex types for elements
that can contain other elements, attributes, or a mixture of both. This supports the
representation of complex data structures.

3. Simple Types: You can define simple types for elements that hold a single value,
such as strings or numbers. Simple types include data validation and constraints.

4. Namespaces: XML Schemas support namespaces, which help avoid naming


conflicts and allow for more modular and organized document structures.

8|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

5. Inheritance: XSD allows for inheritance and extension of types, enabling the reuse
and extension of existing definitions.

6. Facets: Facets are constraints applied to simple types. For example, you can
restrict the length of a string or define a range for numeric values.

Example of an XML Schema (XSD):

Here's a simplified example of an XML Schema for a "book" element:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="book">

<xs:complexType>

<xs:sequence>

<xs:element name="title" type="xs:string"/>

<xs:element name="author" type="xs:string"/>

</xs:sequence>

<xs:attribute name="ISBN" type="xs:string"/>

</xs:complexType>

</xs:element>

</xs:schema>
In this example, the XSD defines the structure of the "book" element with nested "title"
and "author" elements. It also includes an "ISBN" attribute.

Benefits of XML Schemas:

 Precise Validation: XML Schemas provide more detailed and accurate validation of
XML documents, including data types and constraints.

9|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

 Modularity: XML Schemas support namespaces and allow for the creation of
reusable components, making it easier to manage large and complex schemas.

 Rich Data Typing: With support for various data types, you can define the
expected formats and constraints for data values.

 Expressive Structure: XML Schemas offer a more expressive syntax for describing
intricate document structures.

XML Schemas are widely used in industries that require strict data validation and well-
defined document structures, such as in web services, data exchange formats, and
database schemas.

Document Object Model:

The Document Object Model (DOM) is a programming interface and representation of


structured documents, such as HTML and XML, that allows programs to dynamically
access, manipulate, and update the content, structure, and style of a document. The
DOM treats an XML or HTML document as a tree-like structure, where each element,
attribute, and text node is a node in the tree.

In web development, the DOM is a crucial concept, as it enables interaction with web
pages using programming languages like JavaScript. It provides a way for scripts to access
and modify the content and structure of a web page in real time, allowing for dynamic
and interactive user experiences.

Key Concepts of the DOM:

1. Node: A node is an individual element, attribute, or text within an XML or HTML


document. Nodes form a hierarchical tree structure.

2. Element: Elements correspond to HTML or XML tags. They can contain other
elements, attributes, and text nodes.

3. Attribute: Attributes are properties associated with elements that provide


additional information about them.

4. Text Node: Text nodes contain the actual text content within elements.

10 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

5. Parent, Child, Sibling Nodes: Nodes in the DOM have relationships with other
nodes. For example, an element's parent is the element that contains it, its
children are the elements or text nodes it contains, and its siblings are elements at
the same level in the hierarchy.

Using the DOM:

Here's a simplified example of how you might use the DOM with JavaScript to change the
content of a webpage:

<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
<script>
function changeText()
{
var element = document.getElementById("myElement");
element.innerHTML = "New Text!";
}
</script>
</head>
<body>
<p id="myElement">Original Text</p>
<button onclick="changeText()">Change Text</button>
</body>
</html>

11 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

In this example:

 The JavaScript function changeText() is called when the button is clicked.

 The function uses the document.getElementById() method to access the element


with the ID "myElement."

 The innerHTML property of the element is modified to change its content.

Manipulating the DOM:

The DOM allows you to perform various operations, such as:

 Accessing and modifying element content, attributes, and styles.

 Adding and removing elements.

 Navigating the tree structure to traverse and manipulate nodes.

 Responding to user interactions (e.g., clicks, input) by updating the DOM.

Modern web development heavily relies on the DOM to create dynamic and interactive
web applications. It's important to note that while the DOM provides powerful
capabilities, excessive manipulation can impact performance. Best practices involve
optimizing DOM interactions for better user experiences.

XHTML Parsing:

XHTML (eXtensible Hypertext Markup Language) parsing refers to the process of


analyzing an XHTML document to understand its structure, content, and relationships
between different elements. Parsing is a fundamental step in web development, as it
allows software to read and manipulate XHTML documents. XHTML is a stricter version
of HTML that follows XML rules, making parsing more standardized and structured.

XHTML parsing is often performed by web browsers, server-side scripts, web scraping
tools, and other applications that need to extract data or manipulate content from web
pages. The process involves several steps:

1. Lexical Analysis (Tokenization): The XHTML document is broken down into


individual tokens, including tags, attributes, text content, and special characters.

12 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

2. Syntax Analysis (Parsing): The tokens are analyzed to identify the hierarchical structure
and relationships among elements. The parser checks if the document adheres to the
XHTML rules and specifications.

3. Document Object Model (DOM) Creation: Once the parsing is complete, the parsed
content is transformed into a tree-like structure known as the Document Object Model
(DOM). The DOM represents the structure of the document in a way that can be easily
manipulated using programming languages like JavaScript.

4. Tree Traversal and Manipulation: After the DOM is created, applications can traverse
the tree, access elements, attributes, and text nodes, and perform various operations such
as updating content, adding new elements, or removing elements.

Here's a simplified example of parsing and manipulating an XHTML document using


JavaScript:

<!DOCTYPE html>
<html>
<head>
<title>XHTML Parsing Example</title>
<script>
window.onload = function() {
// Access the <p> element by ID
var paragraphElement = document.getElementById("myParagraph");

// Change the text content


paragraphElement.innerHTML = "Updated Text";

// Create a new <div> element


var newDivElement = document.createElement("div");
newDivElement.innerHTML = "New Div Element";
13 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

// Append the new <div> to the body


document.body.appendChild(newDivElement);
};
</script>
</head>
<body>
<p id="myParagraph">Original Text</p>
</body>
</html>
In this example:

 The JavaScript code runs when the window loads.

 The getElementById() method is used to access the <p> element with the ID
"myParagraph."

 The innerHTML property is used to change the text content of the element.

 The createElement() method is used to create a new <div> element.

 The appendChild() method is used to add the new <div> element to the body of
the document.

Remember that parsing and manipulating XHTML documents using the DOM is a
fundamental skill in web development, as it enables you to create dynamic and interactive
web applications.

XHTML Parsing XML Data:

Parsing XML data, whether it's in the form of an XHTML document or a standalone XML
file, involves similar principles to what we discussed earlier. The key steps involve
tokenization, parsing, and working with the resulting Document Object Model (DOM).
Here's how you can parse XML data using JavaScript:

14 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

<!DOCTYPE html>
<html>
<head>
<title>XML Parsing Example</title>
<script>
window.onload = function() {
// Load the XML data
var xmlString = `
<bookstore>
<book>
<title>XML Basics</title>
<author>Gopal</author>
</book>
<book>
<title>Web Development</title>
<author>Krishna</author>
</book>
</bookstore>
`;
// Create a DOMParser object
var parser = new DOMParser();
// Parse the XML string
var xmlDoc = parser.parseFromString(xmlString, "text/xml");
// Access and manipulate the parsed XML
var books = xmlDoc.getElementsByTagName("book");
15 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

for (var i = 0; i < books.length; i++) {


var title = books[i].getElementsByTagName("title")[0].textContent;
var author =
books[i].getElementsByTagName("author")[0].textContent;
console.log("Title: " + title + ", Author: " + author);
}
};
</script>
</head>
<body>
</body>
</html>
In this example:

 The XML data is provided as a string within the xmlString variable.

 The DOMParser object is used to parse the XML string and create a Document
Object Model (DOM) representation.

 The getElementsByTagName method is used to access elements within the DOM.

 The textContent property is used to retrieve the text content of elements.

The provided XML data represents a simple "bookstore" structure with "book"
elements containing "title" and "author" elements. The JavaScript code parses this XML
data and extracts the title and author information for each book.

Remember that when parsing XML data, it's important to handle potential errors
and edge cases, especially when working with data from external sources. Additionally,
consider using modern techniques and libraries like fetch or XMLHttpRequest to load
XML data from external URLs.

DOM:

16 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

The Document Object Model (DOM) is a programming interface and representation of


structured documents, such as HTML, XHTML, and XML. It provides a way for
programs (typically scripts written in languages like JavaScript) to interact with the
content, structure, and style of documents. The DOM treats a document as a tree-like
structure of nodes, where each node represents an element, attribute, or piece of text.

Key points about the DOM:

1. Hierarchical Structure: The DOM represents a document as a hierarchical tree


structure. Each element, attribute, and text node corresponds to a node in the tree.

2. Access and Manipulation: The DOM provides methods and properties to access,
modify, and manipulate the content and structure of a document. This allows for
dynamic updates and interactions.

3. Platform and Language Agnostic: While it's most commonly used with
JavaScript in web browsers, the DOM is not limited to browsers. It's a language-
agnostic standard, meaning it can be used with other programming languages and
on various platforms.

4. Dynamic Web Interaction: The DOM enables the creation of interactive and
dynamic web applications. For example, it allows you to update text, add or remove
elements, handle user input, and more.

5. Tree Structure: Nodes in the DOM have parent-child relationships, forming a tree.
For instance, a paragraph element (child) can be contained within a div element
(parent), and both can be children of the body element (parent).

6. Document Manipulation: You can create, modify, or delete elements, attributes,


and text nodes. This is often used for user interfaces, animations, form validation,
and more.

7. Event Handling: The DOM enables the handling of events like clicks, inputs, and
changes. You can attach event listeners to elements to trigger specific actions when
events occur.

8. Traversal: You can navigate the DOM tree using methods like childNodes,
parentNode, and others. This allows you to move between nodes and access their
properties.
17 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

9. Cross-Platform Compatibility: Although different browsers may have variations


in how they implement the DOM, the DOM standards ensure a level of consistency
and compatibility across browsers.

Here's a simple example in HTML and JavaScript:

<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
<script>
window.onload = function() {
// Access an element by its ID
var myElement = document.getElementById("myDiv");

// Modify its content


myElement.innerHTML = "Hello, DOM!";

// Create a new element and append it


var newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
myElement.appendChild(newParagraph);
};
</script>
</head>
<body>
<div id="myDiv">Original Content</div>

18 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

</body>
</html>
In this example, the JavaScript code uses the DOM to modify the content of a <div>
element and add a new <p> element.

The DOM is a foundational concept in web development, enabling the creation of


interactive and dynamic web pages.

SAX Parsers in java:

SAX (Simple API for XML) is a widely used event-based API for parsing XML
documents in Java. It's designed for efficiently processing large XML documents without
loading the entire document into memory. SAX parsers read XML documents sequentially
and trigger events as they encounter different elements, attributes, and content. This
makes SAX parsers memory-efficient and suitable for parsing large datasets.

Here's an overview of how to use SAX parsers in Java:

1. Import Required Classes: To use SAX parsing, you need to import the relevant
classes from the Java API. Some of the key classes include SAXParserFactory,
SAXParser, DefaultHandler, and related interfaces.

2. Create a SAX Parser: You create a SAX parser using the SAXParserFactory class.
This class provides a way to obtain a new SAX parser instance.

import javax.xml.parsers.SAXParser;

import javax.xml.parsers.SAXParserFactory;

SAXParserFactory factory = SAXParserFactory.newInstance();

SAXParser saxParser = factory.newSAXParser();

3. Create a Handler: A handler is responsible for processing the events triggered by the
SAX parser as it reads through the XML document. You need to create a class that
implements the DefaultHandler interface or extends the DefaultHandler class and
overrides the relevant event methods.

19 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

import org.xml.sax.helpers.DefaultHandler;

public class MyHandler extends DefaultHandler

// Override event methods here

4.Configure and Parse: You need to configure the SAX parser with your custom handler
and then parse the XML document.

import java.io.InputStream;
import org.xml.sax.InputSource;

// Load XML content (e.g., from a file or network)


InputStream xmlInputStream = ...;

// Create an InputSource from the XML content


InputSource inputSource = new InputSource(xmlInputStream);

// Set the custom handler


saxParser.parse(inputSource, new MyHandler());

5. Override Event Methods: In your custom handler class, you'll override methods that
correspond to different XML events, such as the start and end of elements, character data,
and more.
@Override

20 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

public void startElement(String uri, String localName, String qName, Attributes


attributes)

// Called when a start tag is encountered

@Override

public void endElement(String uri, String localName, String qName)

// Called when an end tag is encountered

@Override

public void characters(char[] ch, int start, int length)

// Called when character data is encountered

SAX parsers are efficient for reading and processing large XML documents or streams.
However, they require you to manage the state of parsing manually. If you need to access
and manipulate data across the entire document, a DOM-based approach might be more
suitable.

Keep in mind that the code snippets provided are simplified examples. Real-world
scenarios might involve error handling, validation, and more advanced parsing techniques.

Difference Betwen DOM And SAX:

DOM (Document Object Model) and SAX (Simple API for XML) are two different
approaches to parsing and processing XML documents in programming. They have

21 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

distinct characteristics and are suited for different use cases. Here's a comparison of DOM
and SAX:

1. Parsing Approach:

 DOM: DOM parsers load the entire XML document into memory and construct a
tree-like structure (the DOM) that represents the document's hierarchy. This allows
for random access to any part of the document but can be memory-intensive for
large documents.

 SAX: SAX parsers read the XML document sequentially and trigger events as they
encounter different elements, attributes, and content. They do not load the entire
document into memory, making them memory-efficient and suitable for processing
large documents.

2. Memory Usage:

 DOM: DOM parsers require enough memory to hold the entire document in
memory as a tree structure. This can be a concern for very large documents or when
memory resources are limited.

 SAX: SAX parsers use minimal memory because they process the document
sequentially and don't keep the entire document in memory. They are memory-
friendly even for large documents.

3. Accessibility:

 DOM: The entire document is loaded into memory as a tree structure, so you can
easily traverse, access, and manipulate any part of the document using the DOM
API. This allows for more flexible data manipulation.

 SAX: SAX parsers provide read-only access and process the document
sequentially. You can't easily go back and forth within the document. However,
they are suitable for scenarios where you only need to process and extract data,
without extensive modifications.

4. Performance:

 DOM: DOM parsing can be slower for large documents due to the overhead of
loading the entire document into memory.
22 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF &
HOD

 SAX: SAX parsing is generally faster for large documents because it processes the
document as a stream and doesn't require loading the entire document into memory.

5. Use Cases:

 DOM: DOM is suitable when you need to frequently access, update, or modify
different parts of the XML document. It's often used for XML documents that need
extensive manipulation and traversal.

 SAX: SAX is suitable when you need to process large XML documents or streams
efficiently and don't require random access to different parts of the document. It's
commonly used for data extraction, validation, and tasks where memory usage is a
concern.

6. Error Handling:

 DOM: DOM parsing usually provides better error handling and reporting, as the
entire document structure is loaded into memory, making it easier to identify errors
and inconsistencies.

 SAX: SAX parsing provides basic error handling, but since it processes the
document sequentially, it might not provide the same level of detailed error
reporting as DOM.

In summary, the choice between DOM and SAX depends on your specific requirements
and the characteristics of your XML data. DOM is more suitable for scenarios that require
extensive manipulation and traversal, while SAX is preferred for efficient processing of
large documents and data extraction tasks.

23 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Unit-3
UNIT III:
Introduction to Servlets: Common Gateway Interface (CGI), Life cycle of a Servlet,
deploying a Servlet, The Servlet API, Reading Servlet parameters, Reading Initialization
parameters, Handling Http Request & Responses, Using Cookies and Sessions, connecting
to a database using JDBC.

Introduction to Servlets:

Servlets are Java-based components that are used to extend the capabilities of a web server
and provide dynamic, server-side processing for web applications. They are a key part of
the Java EE (Enterprise Edition) platform, now known as Jakarta EE, and are commonly
used to build interactive and dynamic web applications.

Servlets are designed to handle requests and generate responses, enabling developers to
create dynamic content that can be sent to clients (usually web browsers) over the HTTP
protocol. Servlets are particularly useful for tasks such as collecting and processing user
input, accessing databases, generating dynamic content, and managing session data.

Key Features of Servlets:

1. Platform Independence: Servlets are written in Java, making them platform-


independent and capable of running on any server that supports the Java Servlet
specification.

2. Lifecycle: Servlets have a well-defined lifecycle that includes initialization, request


handling, and destruction phases. Developers can override methods in the lifecycle
to execute code at different stages.

3. HTTP Handling: Servlets are typically used to handle HTTP requests and
responses. They can process GET and POST requests, access request parameters,
and set response headers.

4. Session Management: Servlets can manage user sessions, maintaining data across
multiple requests and responses. This is essential for building interactive web
applications.

1|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

5. Concurrency: Web servers automatically manage the threading of servlets,


allowing multiple requests to be processed concurrently without developers needing
to manage threads explicitly.

6. Server Extensions: Servlets extend the capabilities of web servers, enabling


developers to create customized functionality without modifying the core server
code.

7. MVC Support: Servlets can be used as part of the Model-View-Controller (MVC)


architectural pattern to separate business logic, data, and presentation concerns.

8. Integration with Other Technologies: Servlets can be combined with technologies


like JavaServer Pages (JSP), JavaBeans, and frameworks like Spring for more
complex web applications.

Basic Structure of a Servlet:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, Servlet!</h1>");
out.println("</body></html>");
}

2|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

In this simple example:


 The MyServlet class extends HttpServlet, providing the necessary methods to
handle HTTP requests.
 The doGet method is overridden to generate an HTML response.
 The response object is used to set the content type and write the response data.
Deployment:
Servlets are packaged as .war (web archive) files and deployed on servlet containers
(web servers that support servlets). Popular servlet containers include Apache Tomcat,
Jetty, and WildFly.
Servlets play a crucial role in Java web development, offering a powerful way to
build dynamic and interactive web applications. They are widely used in enterprise-level
applications, e-commerce platforms, content management systems, and more.
Life Cycle Of Servlets:
The life cycle of a servlet refers to the various stages that a servlet goes through from its
instantiation to its destruction. Understanding the servlet life cycle is essential for proper
development and management of servlet-based applications. The life cycle methods
provide hooks that developers can use to execute custom code at specific points in the
servlet's existence. Here are the main stages of the servlet life cycle:

1. Instantiation:

 When a servlet is first requested or the web application is started, the servlet
container (web server) loads the servlet class and creates an instance of it.

 This happens only once for the servlet's entire lifecycle.

2. Initialization (init method):

 After the servlet is instantiated, the container calls the init method on the
servlet.

3|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 This method is used for performing one-time initialization tasks, such as


setting up resources, establishing database connections, and loading
configuration data.

 The init method is called only once during the servlet's lifetime.

 Signature: public void init(ServletConfig config) throws ServletException

3. Request Handling (service method):

 Once the servlet is initialized, it can start processing incoming requests.

 The service method is responsible for handling client requests.

 The servlet container calls the appropriate service method (e.g., doGet,
doPost, etc.) based on the type of request received.

 Signature: protected void service(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException

4. Request Processing (doXXX methods):

 Each specific HTTP method (GET, POST, PUT, DELETE, etc.) has a
corresponding method in the servlet class (e.g., doGet, doPost, doPut,
doDelete, etc.).

 Developers override these methods to provide the implementation for


processing requests of that particular type.

 These methods can be called multiple times during the servlet's life cycle,
depending on the number of requests received.

5. Termination (destroy method):

 When the servlet container decides to remove the servlet instance (usually
during web application shutdown or redeployment), it calls the destroy
method.

 The destroy method is used to clean up resources, close database


connections, and perform other cleanup tasks.

4|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 Like the init method, the destroy method is called only once during the
servlet's lifetime.

 Signature: public void destroy()

It's important to note that each request to a servlet typically runs in its own thread.
Therefore, multiple requests can be handled simultaneously by the same servlet instance.
Servlet containers handle the management of threads and ensure thread safety for the
servlet instance.

Understanding the servlet life cycle is crucial for managing resources efficiently and for
implementing proper initialization and cleanup procedures in your servlet-based
applications.

Common Gateway Interface (CGI):

The Common Gateway Interface (CGI) is a protocol that enables web servers to interact
with external programs or scripts to generate dynamic content and respond to client
requests. It's one of the earliest methods for creating dynamic web content and enabling
server-side scripting. CGI allows web servers to pass data between the server and external
programs, execute those programs, and return the output to the client's web browser.

Here are the key components and concepts of CGI:

1. External Programs: CGI allows web servers to execute external programs or


scripts (written in languages like Perl, Python, C, etc.) in response to incoming
requests.

2. Dynamic Content Generation: Instead of serving static files, CGI scripts generate
dynamic content, such as personalized web pages, database-driven responses, and
interactive web applications.

3. HTTP Request and Response: When a CGI script is invoked, the web server
provides environment variables and input data (such as form data) to the script. The
script processes this data and produces output, which the server then sends as the
HTTP response to the client.

4. Standard I/O: CGI scripts read input data from the standard input (stdin) and write
output data to the standard output (stdout). The web server captures this output and
includes it in the HTTP response.
5|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

5. Environment Variables: Web servers provide environment variables to CGI


scripts, containing information about the request, server configuration, and client
information. These variables help the script adapt to the context of the request.

6. Execution Model: When a request matches a CGI script's URL, the web server
invokes the script, passes the request data, environment variables, and waits for the
script to generate output.

7. Scalability Concerns: CGI scripts are executed in separate processes for each
request, which can lead to resource-intensive overhead and scalability challenges.
As a result, alternative technologies like FastCGI and server-side scripting
languages (e.g., PHP, Java Servlets) emerged to address these issues.

8. File Permissions and Security: Because CGI scripts run external programs, file
permissions and security are critical considerations to prevent unauthorized access
to server resources.

It's important to note that while CGI was once widely used, its direct use has significantly
diminished due to performance and security concerns. Modern web servers and scripting
languages offer more efficient and secure alternatives for generating dynamic content.
However, understanding the basics of CGI can provide historical context and insight into
the evolution of web development technologies.

Deploying A Servlet:

Deploying a servlet involves making your servlet class accessible to a web server,
allowing the server to handle requests and responses related to your servlet. Servlets are
typically packaged within web applications, which are usually organized as Java web
archive (WAR) files. Here's a general guide on how to deploy a servlet:

1.Create a Servlet:

First, create your servlet class by extending javax.servlet.http.HttpServlet and


overriding the necessary methods (such as doGet or doPost).

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

6|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

public class MyServlet extends HttpServlet {

// Override doGet/doPost methods

2. Package Your Servlet:

To deploy a servlet, you need to package it within a web application. The servlet, along
with any other resources like HTML files, JSPs, and configuration files, is organized in a
directory structure.

my-web-app/

|-- WEB-INF/

| |-- classes/

| | |-- MyServlet.class

| |

| |-- web.xml

|-- index.html

In this example, the servlet class MyServlet is compiled and placed in the WEB-
INF/classes/ directory of the web application.

3. Configure web.xml:

The web.xml file, located in the WEB-INF/ directory, is the deployment descriptor for
your web application. It defines servlet mappings, URL patterns, and other configuration
settings

<web-app>

<servlet>

<servlet-name>MyServlet</servlet-name>
7|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>MyServlet</servlet-name>

<url-pattern>/myservlet</url-pattern>

</servlet-mapping>

</web-app>

In this example, the web.xml file maps the servlet class MyServlet to the URL
pattern /myservlet.

4. Package as WAR: Once your web application directory is ready, you need to package
it into a Java web archive (WAR) file. A WAR file is a compressed file containing your
web application's resources and configuration.

From the command line, navigate to the root directory of your web application and use a
tool like jar to create the WAR file:

jar -cvf my-web-app.war *

5. Deploy to Web Server: After creating the WAR file, you can deploy it to a web server
that supports servlets, such as Apache Tomcat, Jetty, or WildFly.

 For Apache Tomcat: Copy the my-web-app.war file to the webapps/ directory of
your Tomcat installation. Tomcat will automatically deploy the web application.

 For Jetty: Copy the my-web-app.war file to the webapps/ directory of your Jetty
installation. Jetty will automatically deploy the web application.

 For WildFly: Deploy the WAR file using the WildFly management console or by
placing it in the standalone/deployments/ directory.

8|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

6. Access Your Servlet: Once deployed, you can access your servlet using the URL
pattern you defined in the web.xml file. For example, if your servlet is mapped to
/myservlet, you can access it at http://localhost:8080/my-web-app/myservlet

Remember that the specific steps might vary based on the web server you're using. It's
important to consult the documentation of your chosen web server for detailed
deployment instructions.

The Servlet API:

The Servlet API is a set of Java classes and interfaces that provide a standard way to build
web applications and dynamic content using servlets. Servlets are Java components that
run on a web server and handle incoming HTTP requests and generate corresponding
HTTP responses. The Servlet API defines the contract between a web server and the
servlets it manages, allowing developers to create dynamic and interactive web
applications.

Key components and features of the Servlet API include:

1. javax.servlet Package:

 The core package that contains classes and interfaces for building servlets.

 Servlet interface: Defines the methods that all servlets must implement, such
as init, service, and destroy.

 GenericServlet class: An abstract class that provides a base implementation


for servlets. It's often extended by servlets to simplify their implementation.

 HttpServlet class: An abstract subclass of GenericServlet that specifically


handles HTTP requests and provides methods like doGet, doPost, etc.

2. Servlet Lifecycle:

 The Servlet API defines the lifecycle of servlets, including initialization,


request handling, and destruction stages.

 Developers can override methods like init, service, and destroy to execute
custom code at specific stages of the servlet's lifecycle.

9|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

3. javax.servlet.http Package:

 An extension of the javax.servlet package that focuses on HTTP-specific


functionality.

 HttpServletRequest interface: Represents the incoming HTTP request and


provides methods to access request parameters, headers, and other details.

 HttpServletResponse interface: Represents the outgoing HTTP response and


provides methods to set response content, headers, and other attributes.

4. Session Management:

 The HttpSession interface allows servlets to manage user sessions and store
data that persists across multiple requests from the same client.

5. Request Dispatching:

 Servlets can forward requests to other servlets or resources using methods


like RequestDispatcher.forward.

6. URL Mapping and Configuration:

 The web.xml deployment descriptor is used to configure servlet mappings,


initialization parameters, security constraints, and other settings.

7. Annotations:

 Servlets can be configured using annotations such as @WebServlet, which


simplifies the web.xml configuration and maps servlets to URL patterns
directly in the source code.

8. Exception Handling:

 Servlets can handle exceptions using the HttpServlet's service method or by


specifying error-page mappings in the web.xml.

9. Filter and Listener Support:

 The Servlet API also includes features for creating filters that preprocess and
post-process requests and responses, as well as listeners that respond to
lifecycle events.

10 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

The Servlet API is part of the Java EE standard (now Jakarta EE) and provides a powerful
foundation for building dynamic web applications in Java. It's important to understand the
Servlet API when working with servlet-based development, as it forms the basis for
creating servlets and interacting with the web server.

Reading Servlet Parameters:

Servlet parameters, also known as query parameters or request parameters, are key-value
pairs that are sent to a servlet as part of an HTTP request. These parameters are often used
to pass data from a client (typically a web browser) to the server for processing. Servlets
can read these parameters and use the data to generate appropriate responses. Here's how
you can read servlet parameters in a Java servlet:

Assuming you have a URL like


http://example.com/myservlet?param1=value1&param2=value2, where param1 and
param2 are parameter names and value1 and value2 are their corresponding values.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Reading single parameter

String param1Value = request.getParameter("param1");

// Reading multiple parameters with the same name

11 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

String[] param2Values = request.getParameterValues("param2");

// Writing the response

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body>");

out.println("<p>Param 1 Value: " + param1Value + "</p>");

if (param2Values != null) {

out.println("<p>Param 2 Values:</p>");

out.println("<ul>");

for (String value : param2Values) {

out.println("<li>" + value + "</li>");

out.println("</ul>");

out.println("</body></html>");

In this example:

 The doGet method of the servlet is invoked when an HTTP GET request is made to
the servlet.

12 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 The HttpServletRequest object, represented by the request parameter, provides


methods to access request parameters.

 The getParameter method retrieves the value of a single parameter based on its
name.

 The getParameterValues method retrieves multiple values of a parameter with the


same name, which is useful when the parameter appears multiple times in the
request (e.g., multiple checkboxes with the same name).

Remember to import the required packages (javax.servlet, javax.servlet.http, etc.)


and handle exceptions appropriately (such as IOException and ServletException).

These parameters are often used to pass data from HTML forms, query strings, or
URLs to the server for processing. Reading servlet parameters is a fundamental skill when
working with servlet-based web applications.

Reading Initialization Parameters:

Servlets can also have initialization parameters that are specified in the deployment
descriptor (web.xml) or through annotations. These parameters provide configuration
values that can be used by the servlet during its initialization. Initialization parameters are
useful for providing settings that are specific to a servlet instance. Here's how you can
read initialization parameters in a Java servlet:

1. Using web.xml:

In your web.xml deployment descriptor, you can define initialization parameters for your
servlet:

<web-app>

<servlet>

<servlet-name>MyServlet</servlet-name>

<servlet-class>com.example.MyServlet</servlet-class>

<init-param>

<param-name>paramName</param-name>

13 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<param-value>paramValue</param-value>

</init-param>

</servlet>

<!-- ...other configurations... -->

</web-app>

2. Using Annotations:

You can also use annotations to define initialization parameters for a servlet:

import javax.servlet.*;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

@WebServlet(

name = "MyServlet",

urlPatterns = {"/myservlet"},

initParams = {

@WebInitParam(name = "paramName", value = "paramValue")

public class MyServlet extends HttpServlet {

// ...

14 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

3. Reading Initialization Parameters:

Inside your servlet's init method, you can use the getInitParameter method to read
initialization parameters:

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class MyServlet extends HttpServlet {

public void init(ServletConfig config) throws ServletException {

super.init(config);

// Reading initialization parameter

String paramName = config.getInitParameter("paramName");

// Use the paramName value as needed

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// ...your servlet code...

15 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

In this example, the init method is overridden to read the initialization parameter
using the getInitParameter method of the ServletConfig object. This parameter can then
be used as needed within your servlet's logic.

Initialization parameters are often used to provide configuration values that affect
the behavior of a servlet. This allows you to configure each servlet instance independently
without modifying the servlet code itself.

Handling Http Request:

Handling HTTP requests is a core task of servlets. Servlets receive requests from clients
(usually web browsers) and generate appropriate responses based on the request type,
URL, and parameters. Here's how you can handle HTTP requests in a Java servlet:

Assuming you have a servlet named MyServlet:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MyServlet extends HttpServlet


{

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{
// This method handles HTTP GET requests

// Read parameters from the request


String paramName = request.getParameter("paramName");

16 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

// Set response content type


response.setContentType("text/html");

// Get the response writer


PrintWriter out = response.getWriter();

// Write HTML response


out.println("<html><body>");
out.println("<h1>Hello, " + paramName + "!</h1>");
out.println("</body></html>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{
// This method handles HTTP POST requests

// Read parameters from the request


String paramName = request.getParameter("paramName");

// Set response content type


response.setContentType("text/html");

// Get the response writer


PrintWriter out = response.getWriter();

17 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

// Write HTML response


out.println("<html><body>");
out.println("<h1>Hello from POST, " + paramName + "!</h1>");
out.println("</body></html>");
}
}
In this example:

 The doGet and doPost methods are overridden to handle HTTP GET and POST
requests, respectively.

 The HttpServletRequest object provides methods to access request parameters,


headers, and other details.

 The HttpServletResponse object allows you to set response content type, headers,
and write the response data.

 Depending on the request type, you can read parameters using the getParameter
method and process them accordingly.

 The response data is generated using the PrintWriter obtained from


response.getWriter().

Accessing Servlets:

Assuming your servlet is mapped to the URL pattern /myservlet:

 For a GET request: Access the servlet at http://example.com/context-


path/myservlet?paramName=value

 For a POST request: Submit a form with the action set to /context-path/myservlet
and include the required parameters.

Replace context-path with the actual context path of your web application.

18 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Remember to import the required packages (javax.servlet, javax.servlet.http, etc.) and


handle exceptions (IOException, ServletException, etc.) properly.

Handling HTTP requests in servlets allows you to create dynamic and interactive web
applications that respond to user actions and input.

Handling Http Responses:

Handling HTTP responses in a servlet involves generating the content that will be sent
back to the client (usually a web browser) in response to the client's request. Servlets
generate responses by writing data to the HttpServletResponse object. Here's how you
can handle HTTP responses in a Java servlet:

Assuming you have a servlet named MyServlet:

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class MyServlet extends HttpServlet

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

// Set response content type

response.setContentType("text/html");

// Get the response writer

PrintWriter out = response.getWriter();

19 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

// Write HTML response

out.println("<html><body>");

out.println("<h1>Hello, Servlet Response!</h1>");

out.println("</body></html>");

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

// Handling POST requests

// Set response content type

response.setContentType("text/plain");

// Get the response writer

PrintWriter out = response.getWriter();

// Write plain text response

out.println("This is a POST response from the servlet.");

In this example:

20 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 The doGet and doPost methods are overridden to handle HTTP GET and POST
requests, respectively.

 The HttpServletResponse object allows you to set the content type of the response
using the setContentType method.

 The PrintWriter obtained from response.getWriter() is used to write the response


data to the client.

Accessing Servlet Responses:

When a client makes a request to your servlet, the servlet generates a response that is sent
back to the client's browser. The response content is generated based on the logic you
implement in your servlet methods (doGet, doPost, etc.).

For example, in a web browser, if you access your servlet at http://example.com/context-


path/myservlet, the servlet's response content will be displayed in the browser window.

Remember to import the required packages (javax.servlet, javax.servlet.http, etc.) and


handle exceptions (IOException, ServletException, etc.) properly.

Handling HTTP responses in a servlet is essential for generating dynamic content that is
sent back to the client based on the client's request and the servlet's logic.

Using Cookies:

Cookies are small pieces of data that are stored on the client's browser and sent back to the
server with subsequent requests. They are commonly used to maintain user sessions, store
user preferences, and track user activities across different pages of a website. In a servlet,
you can create, read, and manipulate cookies using the javax.servlet.http.Cookie class.
Here's how you can use cookies in a Java servlet:

Creating Cookies:

You can create cookies and set their values, expiration time, and other attributes before
sending them to the client's browser.

import javax.servlet.*;
import javax.servlet.http.*;
21 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

import java.io.*;

public class CookieServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Create a cookie
Cookie userNameCookie = new Cookie("username", "john_doe");
Cookie languageCookie = new Cookie("language", "en_US");

// Set cookie attributes


userNameCookie.setMaxAge(3600); // Cookie expires in 1 hour (in seconds)
languageCookie.setMaxAge(24 * 60 * 60); // Cookie expires in 24 hours

// Add cookies to the response


response.addCookie(userNameCookie);
response.addCookie(languageCookie);

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<p>Cookies have been created and sent to the client.</p>");
out.println("</body></html>");
}

22 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

}
Reading Cookies:

You can read cookies sent by the client's browser using the HttpServletRequest object.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class CookieReaderServlet extends HttpServlet


{

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{

Cookie[] cookies = request.getCookies();

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");

if (cookies != null) {
out.println("<p>Read Cookies:</p>");
out.println("<ul>");

for (Cookie cookie : cookies)

23 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

{
out.println("<li>" + cookie.getName() + ": " + cookie.getValue() +
"</li>");
}
out.println("</ul>");
} else
{
out.println("<p>No cookies found.</p>");
}
out.println("</body></html>");
}
}
In this example, the getCookies method of the HttpServletRequest object is used to
retrieve an array of cookies sent by the client's browser.

Remember that cookies have limitations, such as a small storage size, and they can be
manipulated by the client. Security considerations are important when dealing with
sensitive data in cookies. Modern web development often uses more secure and scalable
methods for session management, such as tokens and session IDs.

Import the required packages (javax.servlet, javax.servlet.http, etc.) and handle


exceptions (IOException, ServletException, etc.) properly.

Sessions:
Sessions in web applications refer to a way of maintaining state and data for individual
users as they navigate and interact with a website. Since HTTP is a stateless protocol,
sessions are used to overcome the limitation of not having inherent memory of previous
interactions. In Java servlets, sessions are managed using the HttpSession interface.

Here's how sessions are typically used in servlets:

24 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

1. Creating a Session: When a user visits a website for the first time, a session is created
for them. This session is associated with a unique identifier, often stored as a cookie on
the user's browser.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class SessionServlet extends HttpServlet

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

// Creating or retrieving a session

HttpSession session = request.getSession();

// Storing data in the session

session.setAttribute("username", "john_doe");

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body>");

out.println("<p>Session created. Username stored in the session.</p>");

out.println("</body></html>");

2. Accessing Session Data:


25 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Subsequent requests from the same user will include the session identifier, allowing the
servlet to retrieve and update session data.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class SessionReaderServlet extends HttpServlet


{
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");

if (username != null)
{
out.println("<p>Welcome back, " + username + "!</p>");
} else
{
out.println("<p>No username found in the session.</p>");
}
out.println("</body></html>");
26 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

}
}
3. Invalidating a Session:

You can also invalidate a session when a user logs out or when a certain condition
is met.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class SessionLogoutServlet extends HttpServlet

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

HttpSession session = request.getSession();

// Invalidate the session

session.invalidate();

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body>");

out.println("<p>Session invalidated. User logged out.</p>");

27 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

out.println("</body></html>");

Using sessions, you can store and manage user-specific data throughout their interaction
with your web application. This is especially useful for maintaining user authentication,
shopping cart items, user preferences, and more.

Remember to import the required packages (javax.servlet, javax.servlet.http, etc.) and


handle exceptions (IOException, ServletException, etc.) properly.

Connecting To A Database Using JDBC:

Java Database Connectivity (JDBC) is a Java API that provides a standard way to interact
with relational databases. It allows Java applications, including servlets, to connect to
databases, execute SQL queries, and manipulate data. Here's how you can connect to a
database using JDBC in a servlet:

1. Import the JDBC Libraries: First, you need to include the JDBC driver library for the
specific database you're using. Different databases have their own JDBC drivers.
Download the JDBC driver JAR file and include it in your project's classpath.

2. Establish a Database Connection: In your servlet, you can establish a connection to


the database using the DriverManager class and the JDBC URL, username, and
password.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.sql.*;

public class DatabaseServlet extends HttpServlet

28 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

Connection connection = null;

Statement statement = null;

Try

// Establish the database connection

String jdbcUrl = "jdbc:mysql://localhost:3306/mydb";

String username = "root";

String password = "password";

connection = DriverManager.getConnection(jdbcUrl, username,


password);

// Create a statement

statement = connection.createStatement();

// Execute a query

String sqlQuery = "SELECT * FROM users";

ResultSet resultSet = statement.executeQuery(sqlQuery);

// Process the result set

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body>");

29 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

out.println("<h1>User List</h1>");

while (resultSet.next())

String username = resultSet.getString("username");

String email = resultSet.getString("email");

out.println("<p>Username: " + username + ", Email: " + email + "</p>");

out.println("</body></html>");

} catch (SQLException e)

e.printStackTrace();

} finally

// Close resources

try {

if (statement != null)

statement.close();

if (connection != null)

connection.close();

30 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

} catch (SQLException e)

e.printStackTrace();

3. Handling Exceptions and Resource Management: It's important to properly handle


exceptions and close database resources (connection, statement, result sets) in the finally
block to ensure efficient resource management and prevent memory leaks.

4. Replace JDBC URL, Username, and Password: Replace the JDBC URL, username,
and password with your actual database connection details.

5. Import the Required Packages: Import the necessary JDBC packages (java.sql) and
servlet packages (javax.servlet, javax.servlet.http, etc.).

Remember that in real-world scenarios, you would typically use connection pooling to
manage database connections efficiently, and you should avoid storing sensitive
information like passwords directly in your code. Use environment variables or
configuration files to manage such sensitive data securely.

31 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

UNIT-4
UNIT IV:

Introduction to JSP: The Anatomy of a JSP Page, JSP Processing, Declarations,


Directives, Expressions, Code Snippets, implicit objects, Using Beans in JSP Pages, Using
Cookies and session for session tracking, connecting to database in JSP. Client-side
Scripting: Introduction to JavaScript, JavaScript language – declaring variables, scope of
variables, functions. event handlers (onClick, onSubmit etc.), Document Object Model,
Form validation.

Introduction to JSP:

JavaServer Pages (JSP) is a technology that allows you to create dynamic web pages by
embedding Java code within HTML templates. JSP is part of the Java EE (now Jakarta
EE) platform and provides an alternative way to generate dynamic content compared to
servlets. With JSP, you can separate the presentation logic (HTML) from the business
logic (Java code), making it easier to develop and maintain web applications.

Key features of JSP include:

1. Embedded Java Code: JSP allows you to embed Java code directly into HTML
templates using special tags. This enables you to generate dynamic content and
execute business logic within the HTML.

2. Seamless Integration: JSP pages are compiled into servlets before being executed,
so they seamlessly integrate with the servlet container and follow the servlet life
cycle.

3. Tag Libraries: JSP provides custom tag libraries that allow you to encapsulate
common tasks and functions, making your JSP pages cleaner and more
maintainable.

4. Expression Language (EL): JSP EL is a simplified way to access JavaBeans


components, request parameters, session attributes, and more directly within JSP
pages, without using scriptlet code.

1|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

5. Standard Actions: JSP provides standard actions that enable you to perform
various tasks, such as forwarding requests, including other resources, and iterating
over collections.

6. MVC Architecture: JSP is often used in combination with servlets to implement


the Model-View-Controller (MVC) architectural pattern. Servlets handle the
controller logic, while JSP pages handle the view.

Here's a simple example of a JSP page that displays a message using embedded Java code:

<!DOCTYPE html>

<html>

<head>

<title>My JSP Page</title>

</head>

<body>

<h1>Hello, <%= "John" %></h1>

<p>Current time: <%= new java.util.Date() %></p>

</body>

</html>

In this example:

 <%= ... %> is a JSP expression tag that evaluates the enclosed Java expression and
outputs its result within the HTML content.

 The expression <%= "John" %> is replaced with "John" in the generated HTML.

 The expression <%= new java.util.Date() %> evaluates to the current date and
time.

JSP simplifies the process of combining dynamic content with static HTML, making it a
powerful tool for building interactive and data-driven web applications. It's important to
note that while JSP is a powerful technology, modern web development often leans

2|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

towards using template engines, front-end frameworks, and APIs for building more
complex and responsive web applications.

The Anatomy Of A Jsp Page:

A JavaServer Page (JSP) is an HTML-based template that allows you to embed Java code
within it. A JSP page is compiled into a servlet by the web container before being
executed, which means that the Java code you write in the JSP is translated into Java code
that is executed on the server side. Here's the basic anatomy of a JSP page:

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8" %>

<!DOCTYPE html>

<html>

<head>

<title>My JSP Page</title>

</head>

<body>

<%-- JSP Declaration --%>

<%! int counter = 0; %>

<%-- JSP Scriptlet --%>

<%

String message = "Hello, JSP!";

counter++;

%>

<%-- JSP Expression --%>

3|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<h1><%= message %></h1>

<%-- JSP Directive --%>

<%-- This page directive sets the content type of the response --%>

<%@ page contentType="text/html; charset=UTF-8" %>

<%-- JSP Expression using EL (Expression Language) --%>

<p>Counter: ${counter}</p>

<%-- JSP Action --%>

<jsp:useBean id="person" class="com.example.Person" scope="session" />

<%-- JSP Comment --%>

<%-- This is a JSP comment --%>

</body>

</html>

Here's a breakdown of the different elements in the JSP page:

1. Directives (<%@ ... %>) : Directives provide instructions to the JSP container
about how the page should be processed. Common directives include:

 page: Specifies page-related attributes like the scripting language and content
type.

 include: Includes an external file during translation phase.

 taglib: Declares custom tag libraries.

4|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

2. JSP Declarations (<%! ... %>) : Declarations allow you to define variables and
methods that can be used in the JSP page outside of the scripting area. Declarations
are placed outside the <% ... %> scriptlet tags.

3. JSP Scriptlets (<% ... %>) : Scriptlets contain Java code that is executed when the
JSP page is requested. You can write any valid Java code here, and the output is
written directly into the HTML content.

4. JSP Expressions (<%= ... %>) : Expressions are used to embed Java expressions
that are evaluated and their results are directly inserted into the HTML content.

5. JSP Actions (<jsp:...>) : Actions are XML-based tags that provide high-level
functionality and encapsulate tasks like including beans, controlling flow, and more.

6. JSP Comments (`<%-- ... --%>) : Comments are used to add explanatory notes to
your code that won't appear in the rendered output.

7. Expression Language (EL) (${ ... }) : EL simplifies the usage of JavaBeans,


request attributes, session attributes, and other objects in JSP pages without using
Java code.

8. HTML and Text : The HTML content forms the static structure of the page, and
you can mix it with the JSP elements as needed.

Remember that a well-designed JSP separates logic from presentation, and it's a good
practice to keep Java code to a minimum within the JSP and use servlets or other Java
classes for complex logic.

JSP Processing:

The processing of JavaServer Pages (JSP) involves several stages that transform your JSP
code into executable Java servlets, which are then executed by the web container. The JSP
processing lifecycle consists of the following steps:

1. Translation: When a JSP page is requested for the first time, the JSP container
translates the JSP code into a Java servlet source code. This generated servlet is
responsible for generating the dynamic content of the page.

5|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

2. Compilation: The generated servlet source code is compiled into bytecode by the
Java compiler. This compiled servlet class is then loaded and instantiated when a
request is made to the JSP.

3. Initialization (Optional): If you have used JSP declarations (<%! ... %>) to define
variables or methods, they are initialized during the servlet's instantiation. This
happens only once when the servlet is first loaded into memory.

4. Service (doGet/doPost) Method Execution: The service method of the servlet is


called by the container in response to an HTTP request (GET or POST). This is
where the dynamic content generation takes place.

5. JSP Elements Execution:

 JSP scriptlets (<% ... %>) are executed, and their Java code is processed.
Any output generated by the scriptlet is included in the response.

 JSP expressions (<%= ... %>) are evaluated, and their results are converted
to strings and included in the response.

 JSP actions (<jsp:...>) are processed, which may involve calling JavaBeans,
controlling flow, or performing other tasks.

6. Expression Language (EL) Processing: Any EL expressions (${ ... }) present in


the JSP are evaluated to retrieve values from JavaBeans, request attributes, session
attributes, etc., and these values are included in the response.

7. Generation of HTML Output: The generated HTML content, along with the
dynamic content generated by scriptlets, expressions, and EL, is included in the
response sent to the client's browser.

8. Destruction (Optional): If you have used JSP declarations to define resources that
need to be released (e.g., closing a database connection), you can use the destroy
method to perform cleanup before the servlet is unloaded from memory.

It's important to note that while JSPs provide a convenient way to mix HTML and Java
code, it's considered good practice to separate business logic from presentation. Complex
Java logic is better placed in Java classes, servlets, or other appropriate components, while
JSPs should primarily focus on rendering the user interface.

6|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Also, modern web development trends often lean towards using template engines and
front-end frameworks, which further separate presentation concerns from back-end logic.

Declarations:

In JavaServer Pages (JSP), declarations are used to define variables, methods, and other
code elements that are accessible across different parts of the JSP page. Declarations are
enclosed within the <%! ... %> tags. They are typically used to define members of the
servlet class generated from the JSP, making them available throughout the servlet's
lifecycle. Here's how declarations work in JSP:

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8" %>

<!DOCTYPE html>

<html>

<head>

<title>Declarations in JSP</title>

</head>

<body>

<%-- JSP Declaration --%>

<%!

// Declare variables and methods here

int count = 0;

void incrementCounter() {

count++;

7|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

%>

<%-- Use the declared variables and methods --%>

<h1>Counter: <%= count %></h1>

<button onclick="<%= incrementCounter() %>">Increment</button>

</body>

</html>

In this example:

 The <%! ... %> declaration tag is used to declare a variable count and a method
incrementCounter() within the JSP.

 The variable count is accessible throughout the JSP and its value is incremented
using the incrementCounter() method.

 The <%= count %> expression is used to display the value of count in the HTML.

 The <%= incrementCounter() %> expression is used to call the


incrementCounter() method when the button is clicked.

Declarations are processed by the JSP container at translation time, and the code inside the
declaration is included in the generated servlet's class definition. This means that variables
and methods declared using declarations are available throughout the servlet's lifecycle,
similar to instance variables and methods of a regular Java class.

It's important to use declarations judiciously and avoid putting complex logic or business
rules directly within them. Declarations are most appropriate for defining simple variables
and utility methods that are used across different parts of the JSP page.

Directives:

8|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

JSP directives are special instructions that provide information to the JavaServer Pages
(JSP) container about how to process a JSP page. Directives are typically placed at the
beginning of a JSP file, before any HTML or Java code. There are three main types of
directives in JSP: page, include, and taglib.

Here's an overview of each type of directive:

1. **Page Directive (<%@ page ... %>):** The page` directive provides instructions
related to the properties and behavior of the JSP page itself. It's used to set attributes
like the scripting language, content type, error handling, and more.

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8" %>

Some common attributes of the page directive include:

 language: Specifies the scripting language (default is Java).

 contentType: Sets the content type of the response.

 pageEncoding: Specifies the character encoding for the JSP page.

 import: Imports Java classes or packages.

2. **Include Directive (<%@ include ... %>):** The include` directive is used to
include the content of another file (usually another JSP or HTML file) within the
current JSP during the translation phase. This can be useful for reusing common
content across multiple pages.

<%@ include file="header.jsp" %>

The include directive does not create a separate servlet class for the included file;
instead, it's as if the content of the included file is copied and pasted into the current
JSP.

3 **Taglib Directive (<%@ taglib ... %>):** The taglib` directive is used to declare
and configure custom tag libraries that provide additional functionality to your JSP
pages. Tag libraries encapsulate reusable components that can be used in your JSP
code.

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

9|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

4. The prefix attribute defines a short name (prefix) that you can use in your JSP to
reference the tag library, while the uri attribute specifies the location of the tag
library's tag definitions.

Directives are processed during the JSP translation phase, before the actual execution of
the JSP. They provide important metadata and configuration information to the JSP
container. Using directives, you can control how the JSP is translated, what resources are
included, and how custom tag libraries are imported.

Remember that while directives are powerful tools for configuring and customizing your
JSP, excessive use of directives can lead to more complex and harder-to-maintain code.
Use directives judiciously and keep the code organized and readable.

Expressions:

Expressions in JavaServer Pages (JSP) allow you to insert the result of a Java expression
directly into the output HTML content. Expressions are enclosed within <%= ... %> tags
in the JSP page. When the JSP page is processed, the expression is evaluated, and its
result is automatically converted to a string and inserted into the generated HTML. Here's
how expressions work in JSP:

<!DOCTYPE html>

<html>

<head>

<title>JSP Expressions</title>

</head>

<body>

<%-- JSP Expression --%>

<h1>Welcome, <%= "John Doe" %></h1>

<%-- Expressions can include variables and calculations --%>

<p>Sum: <%= 2 + 3 %></p>

10 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<%-- Expressions can also call methods --%>

<p>Current Date: <%= new java.util.Date() %></p>

</body> </html>

In this example:

 The <%= ... %> expression tag is used to insert the result of the enclosed Java
expression into the HTML content.

 The expression <%= "John Doe" %> is replaced with "John Doe" in the generated
HTML.

 The expression <%= 2 + 3 %> is replaced with "5" in the generated HTML.

 The expression <%= new java.util.Date() %> is replaced with the current date and
time in the generated HTML.

Important points to note:

 Expressions are evaluated and their results are automatically escaped to prevent
cross-site scripting (XSS) vulnerabilities.

 The result of an expression is automatically converted to a string using the


toString() method of the object, if applicable.

 Expressions cannot contain statements, control flow, or assignments. They are


meant for simple evaluations.

 You can use variables, literals, method calls, and arithmetic expressions in
expressions.

Expressions are a convenient way to include dynamic data in your HTML output without
having to use scriptlets (<% ... %>) or separate Java code blocks. However, for more
complex logic or dynamic behavior, you might need to use scriptlets, custom tags, or
JavaBeans in combination with expressions.

11 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Code Snippets:

Here are a few code snippets for common tasks in JSP (JavaServer Pages):

Displaying a Variable:

To display a variable in JSP, you can use the <%= %> syntax.

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<title>Display Variable</title>

</head>

<body>

<h1>Hello, <%= "John Doe" %></h1>

</body>

</html>

Looping through a List:

You can use JSTL (JavaServer Pages Standard Tag Library) to loop through a list and
display its elements.

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

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

12 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<title>Looping Through List</title>

</head>

<body>

<ul>

<c:forEach var="item" items="${items}">

<li>${item}</li>

</c:forEach>

</ul>

</body>

</html>

Conditional Statements:

You can use JSTL for conditional statements as well.

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

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<title>Conditional Statement</title>

</head>

<body>

<c:choose>

13 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<c:when test="${userType eq 'admin'}">

<p>Welcome, Admin!</p>

</c:when>

<c:otherwise>

<p>Welcome, Guest!</p>

</c:otherwise>

</c:choose>

</body>

</html>

Including Another JSP:

You can use the <jsp:include> tag to include content from another JSP file.

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<title>Including Another JSP</title>

</head>

<body>

<h1>Main Page</h1>

<jsp:include page="included.jsp"/>

</body>

</html>

14 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

These are just a few examples of code snippets in JSP. If you have a specific task in mind
or need more examples, feel free to ask!

Implicit Objects:
In JavaServer Pages (JSP), implicit objects are pre-defined objects that are automatically
available to you without needing to declare or instantiate them. These objects provide
useful information about the environment and context of the JSP page. Here are some
commonly used implicit objects in JSP:

1) Request:

Represents the client's HTTP request to the server.

<%

String parameterValue = request.getParameter("paramName");

%>

2)Response:

Represents the server's HTTP response to the client.

<%

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("Hello, world!");

%>

3)Out:

Represents the output stream for writing content to the response.

<%

out.println("This is written to the response.");

15 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

%>

4)Session:

Represents the user's session, allowing you to store session-specific data.

<%

session.setAttribute("username", "john");

%>

5)Application:

Represents the servlet context, allowing you to access application-level data.

<%

String appName = application.getInitParameter("app_name");

%>

6)Pagecontext:

Provides access to various objects and information about the JSP page.

<%

String servletName = pageContext.getServletConfig().getServletName();

%>

These implicit objects simplify the development process by abstracting away common
tasks and providing easy access to important data. Developers can use these objects
directly within their JSP code without the need to explicitly create or manage them.

It's important to note that the concept of implicit objects is not limited to JSP or web
development. Different programming environments, frameworks, and languages may have
their own set of implicit objects or variables that provide similar convenience and
functionality.

Using Beans in JSP Pages:

16 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Using beans in JSP (JavaServer Pages) allows you to separate the logic from the
presentation in your web application. Beans are Java objects that encapsulate data and
provide methods to access and manipulate that data. They can be used to pass data
between the server-side Java code and the client-side JSP pages. Here's how you can use
beans in JSP pages:

1. Create a Java Bean:

A Java bean is a simple Java class that follows certain conventions. It typically has private
instance variables (fields), public getter and setter methods for those fields, and optionally,
additional methods for performing operations on the data.

public class PersonBean


{
private String name;
private int age;
// Constructors
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
17 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

{
this.age = age;
}
}

Use the Bean in a JSP Page:


To use a bean in a JSP page, you need to import the bean's class at the top of your JSP file.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.example.PersonBean" %>
<!DOCTYPE html>
<html>
<head>
<title>Bean Example</title>
</head>
<body>
<%
// Create an instance of the bean
PersonBean person = new PersonBean();
person.setName("John Doe");
person.setAge(30);
%>
<h1>Person Details</h1>
<p>Name: <%= person.getName() %></p>

18 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<p>Age: <%= person.getAge() %></p>


</body>
</html>

Using Beans for Data Flow:

Beans can also be used to pass data from servlets to JSP pages. For instance, you might
retrieve data from a database using a servlet and then set that data in a bean. The JSP page
can then access the bean's properties to display the data.

java

// In a servlet

PersonBean person = new PersonBean();

person.setName("Alice");

person.setAge(25);

request.setAttribute("person", person);

request.getRequestDispatcher("example.jsp").forward(request, response);

jsp

<!-- In example.jsp -->

<%

PersonBean person = (PersonBean) request.getAttribute("person");

%>

<h1>Person Details</h1>

19 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<p>Name: <%= person.getName() %></p>

<p>Age: <%= person.getAge() %></p>

By using beans in JSP pages, you can create a more organized and maintainable
separation between the business logic (Java code) and the presentation (HTML and client-
side interactions).

Using Cookies And Session For Session Tracking:

Cookies and sessions are mechanisms used for session tracking in web applications. They
allow you to maintain stateful information about a user's interaction with your website
across multiple requests. Here's how you can use cookies and sessions for session
tracking:

1. Cookies:

Cookies are small pieces of data that a server sends to a user's web browser, which are
then stored and sent back with subsequent requests to the same server. Cookies are often
used to store user-specific information.

Setting Cookies:

Java

// In a servlet or JSP

Cookie usernameCookie = new Cookie("username", "john_doe");

usernameCookie.setMaxAge(60 * 60 * 24 * 7); // Cookie will last for 7 days

response.addCookie(usernameCookie);

Accessing Cookies:

// In a servlet or JSP

20 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Cookie[] cookies = request.getCookies();

if (cookies != null) {

for (Cookie cookie : cookies) {

if (cookie.getName().equals("username")) {

String username = cookie.getValue();

// Do something with the username

break;

2. Sessions:

Sessions are server-side objects that store user-specific data and maintain it throughout the
user's interaction with the application. Each user is assigned a unique session ID, which is
often stored in a cookie.

java

Creating and Accessing Sessions:

// In a servlet or JSP

HttpSession session = request.getSession();

session.setAttribute("username", "john_doe");

java

// In another servlet or JSP

HttpSession session = request.getSession();

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

Session Timeout:
21 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

By default, sessions have a timeout period after which they expire and are invalidated.
You can set the session timeout duration in web.xml or programmatically:

java

// Set session timeout programmatically

HttpSession session = request.getSession();

session.setMaxInactiveInterval(60 * 30); // Session will expire after 30 minutes of


inactivity

Invalidating Sessions:

// In a servlet or JSP

HttpSession session = request.getSession();

session.invalidate(); // Invalidate the current session

Using cookies and sessions together can provide effective session tracking:

1. When a user visits your site, you can set a cookie containing a unique session ID.

2. On subsequent requests, the browser sends the session ID cookie, allowing the
server to identify the user's session.

3. The server uses the session ID to retrieve the corresponding session object,
maintaining user-specific data.

Remember to use session tracking responsibly and consider user privacy. Avoid storing
sensitive information in cookies, and be cautious about what information you store in
sessions.

Connecting To Database In JSP:

Connecting directly to a database from JSP pages is generally not recommended due to
security and maintainability concerns. Instead, it's a good practice to encapsulate database
access within a separate layer, such as servlets or dedicated Java classes. This approach

22 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

adheres to the Model-View-Controller (MVC) architecture, where JSP pages (the View)
are responsible for displaying data, while the database interaction (the Model) is handled
elsewhere.

Here's a high-level example of how you can connect to a database using a servlet and
JDBC (Java Database Connectivity):

1. Create a Database Connection Utility:

Create a Java class responsible for establishing and managing the database connection.
This class should handle database connection pooling for efficiency.

java

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class DatabaseConnectionUtil

private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";

private static final String DB_USER = "username";

private static final String DB_PASSWORD = "password";

public static Connection getConnection() throws SQLException

return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);

23 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

2. Create a Servlet for Database Interaction:

Create a servlet that handles database interactions and forwards the data to a JSP for
presentation.

java
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DatabaseServlet extends HttpServlet


{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try
{
Connection connection = DatabaseConnectionUtil.getConnection();
String query = "SELECT * FROM users";
PreparedStatement statement = connection.prepareStatement(query);

24 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

ResultSet resultSet = statement.executeQuery();

request.setAttribute("userList", resultSet);
request.getRequestDispatcher("display.jsp").forward(request, response);

resultSet.close();
statement.close();
connection.close();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
3. Create a JSP for Display:

Create a JSP page that receives data from the servlet and displays it.

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<title>User List</title>

</head>

<body>

25 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<h1>User List</h1>

<table>

<tr>

<th>ID</th>

<th>Name</th>

<th>Email</th>

</tr>

<c:forEach var="user" items="${userList}">

<tr>

<td>${user.id}</td>

<td>${user.name}</td>

<td>${user.email}</td>

</tr>

</c:forEach>

</table>

</body>

</html>

In this example, the servlet handles the database interaction, retrieves data from the
database, and then forwards it to the JSP page for display. The JSP uses JSTL (JavaServer
Pages Standard Tag Library) to iterate over the ResultSet and display the data.

Remember to properly handle exceptions, close resources, and follow best practices for
security, such as using parameterized queries to prevent SQL injection. Additionally,
consider using more advanced techniques like ORM frameworks (Hibernate, JPA) for
database access to further simplify and enhance your database interactions.

Client-side Scripting:
26 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Client-side scripting refers to the practice of writing and executing scripts directly within a
user's web browser on the client side of a web application. In this context, the client side
refers to the user's computer or device that is accessing a website. The opposite of client-
side scripting is server-side scripting, where scripts are executed on the web server before
the content is sent to the client's browser.

JavaScript is the most commonly used programming language for client-side scripting. It
allows web developers to create interactive and dynamic web pages by manipulating the
Document Object Model (DOM) of a web page. The DOM represents the structure of a
web page, and JavaScript can be used to modify this structure, update content, respond to
user interactions, and perform various actions without requiring a full page reload.

Client-side scripting has several advantages:

1. Interactivity: Client-side scripting allows developers to create responsive and


interactive user interfaces. Elements on a page can be updated in real-time based on
user actions, without needing to reload the entire page.

2. Reduced Server Load: Since much of the processing is done on the client's side,
there is less strain on the server. This can lead to improved performance and
reduced server costs.

3. Immediate Feedback: Client-side scripts can provide immediate feedback to users


without requiring them to wait for server responses. For example, form validation
can be done instantly as users fill out forms.

4. Rich User Experience: By utilizing client-side scripting, web applications can


provide a richer and more engaging user experience with animations, transitions,
and other dynamic elements.

5. Offline Functionality: With modern technologies like service workers, client-side


scripts can enable offline functionality, allowing users to interact with certain
features of a web app even when they are not connected to the internet.

However, there are also some considerations and challenges with client-side scripting:

1. Security: Since the code is executed on the client's machine, it can be susceptible to
security vulnerabilities and attacks if not properly secured.

27 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

2. Compatibility: Different browsers may interpret JavaScript differently, leading to


cross-browser compatibility issues. Developers often need to test and adapt their
scripts for multiple browsers.

3. Performance: Poorly optimized client-side scripts can negatively impact the


performance of a web page, leading to slow load times and unresponsive interfaces.

4. Accessibility: Not all users have JavaScript enabled or may use assistive
technologies. It's important to ensure that essential content and functionality are
accessible even without JavaScript.

In summary, client-side scripting is a powerful approach for creating dynamic and


interactive web applications. JavaScript, in particular, is a key tool in this realm, enabling
developers to build feature-rich user experiences that run directly within the browser.

Introduction to JavaScript:

JavaScript is a versatile and widely-used programming language that plays a crucial role
in web development. It was initially created to make websites more interactive and
dynamic by allowing developers to manipulate web page elements directly within a user's
browser. Since its inception, JavaScript has evolved to become a full-fledged
programming language used for both client-side and server-side development.

Key Features of JavaScript:

1. Client-Side Scripting: JavaScript is primarily known for its role in client-side


scripting. It enables developers to create dynamic and responsive web pages by
modifying the Document Object Model (DOM) of a webpage. This means you can
update content, respond to user interactions, and create engaging user interfaces
without needing to reload the entire page.

2. Versatility: While JavaScript is heavily used in web development, it's not limited
to just that. It can also be used for server-side programming (Node.js), creating
desktop applications (Electron), and even mobile app development (React Native).

3. Interactivity: With JavaScript, you can make web pages come alive with
interactive elements like buttons, forms, animations, and more. User input can
trigger actions, and you can provide real-time feedback without requiring server
interactions.

28 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

4. Asynchronous Programming: JavaScript excels at handling asynchronous tasks,


which allows you to perform operations without blocking the main thread. This is
crucial for tasks like making network requests without freezing the user interface.

5. Event Handling: JavaScript lets you respond to various events that occur in a web
page, such as clicks, key presses, and mouse movements. This enables you to build
dynamic and engaging user experiences.

6. Libraries and Frameworks: JavaScript has a vast ecosystem of libraries and


frameworks that simplify common tasks and provide reusable components.
Examples include jQuery, React, Angular, and Vue.js.

7. Cross-Browser Compatibility: While there can be browser-specific differences,


JavaScript has become much more standardized across browsers. Modern
development practices and tools help ensure better cross-browser compatibility.

Basic Syntax:

Here's a simple example of JavaScript syntax:

javascript

// This is a single-line comment

/* This is a
multi-line comment */
// Variables
let greeting = "Hello, ";
const recipient = "World";

// Output
console.log(greeting + recipient);
// Functions

29 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

function sayHello(name)
{
return "Hello, " + name;
}
console.log(sayHello("Alice"));

In this example, we declare variables using let and const, concatenate strings, use a basic
function, and output text to the console using console.log().

Getting Started:

To start working with JavaScript, all you need is a text editor and a web browser. You can
write JavaScript code directly within the <script> tags in an HTML file, or you can link
to external JavaScript files.

Here's a simple example of inline JavaScript in an HTML file:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Introduction</title>
</head>
<body>
<h1>JavaScript Example</h1>
<script>
let message = "Hello, JavaScript!";
console.log(message);
</script>

30 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

</body>
</html>
As you become more comfortable with JavaScript, you can explore its more advanced
features, such as working with the DOM, handling asynchronous operations, and using
libraries/frameworks to build complex applications.

Javascript Language:

JavaScript is a versatile and widely-used programming language that is primarily


associated with web development. It was created by Netscape in 1995 and has since
become one of the core technologies of the World Wide Web. JavaScript is often used to
enhance the interactivity and user experience of websites by enabling dynamic content and
real-time updates without the need for page reloads. It's important to note that JavaScript
should not be confused with Java – they are distinct programming languages with
different purposes and features.

Here are some key aspects of the JavaScript programming language:

1. Client-Side Scripting: JavaScript is primarily used for client-side scripting,


meaning that it's executed within a web browser. It enables developers to
manipulate the Document Object Model (DOM) of a web page, which allows for
dynamic and interactive user interfaces.

2. Syntax: JavaScript has C-like syntax with some influences from other
programming languages like Java and C++. It uses semicolons to terminate
statements, curly braces to define blocks of code, and variables are loosely typed
(you don't have to specify the type of a variable explicitly).

3. Data Types: JavaScript has a variety of built-in data types, including numbers,
strings, booleans, arrays, objects, and more. It's a dynamically typed language,
which means variable types can change during runtime.

4. Functions: Functions are a fundamental part of JavaScript. They can be defined


and invoked, and they can accept parameters and return values. Functions can also
be assigned to variables and passed as arguments.

31 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

5. Event Handling: JavaScript is commonly used to handle events such as user


interactions (clicks, key presses, etc.). Event listeners can be added to HTML
elements, allowing developers to respond to events and trigger specific actions.

6. DOM Manipulation: The Document Object Model (DOM) represents the structure
of an HTML document. JavaScript can be used to access and modify the DOM,
allowing for the creation, deletion, and manipulation of HTML elements and
attributes.

7. Asynchronous Programming: JavaScript supports asynchronous programming


through mechanisms like callbacks, promises, and async/await. This is crucial for
handling tasks such as making network requests without blocking the main thread.

8. Libraries and Frameworks: JavaScript has a rich ecosystem of libraries and


frameworks that streamline development and provide pre-built functionality. For
example, jQuery simplifies DOM manipulation, while React, Angular, and Vue.js
are popular front-end frameworks.

9. ECMAScript: JavaScript is standardized by the ECMAScript specification.


Different versions of JavaScript correspond to different ECMAScript versions.
Modern JavaScript development often follows ECMAScript 6 (ES6) and later
standards, which introduce features like arrow functions, classes, modules, and
more.

10. Server-Side JavaScript: While JavaScript's primary use is on the client side, it can
also be used for server-side programming through technologies like Node.js.
Node.js allows developers to build server applications using JavaScript.

JavaScript has evolved significantly since its inception and continues to grow in
importance as web development advances. It's a powerful tool for creating dynamic,
interactive, and engaging web applications, as well as for building a wide range of other
software solutions.

Declaring Variables:

In JavaScript, you can declare variables using the var, let, or const keywords. These
keywords allow you to define variables to store different types of data, such as numbers,
strings, objects, and more. The choice of which keyword to use depends on the scope and
mutability requirements of the variable. Here's an overview of each keyword:
32 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

1. var: The var keyword was historically used to declare variables in JavaScript.
However, it has some quirks and scope-related issues, which is why it's less
commonly used nowadays. Variables declared with var are function-scoped,
meaning they are accessible within the function where they are defined or in the
global scope if defined outside a function. Variables declared with var are also
subject to "hoisting," where variable declarations are moved to the top of their
scope during runtime.

var x = 10;

function example()

var y = 20;

2. let: The let keyword was introduced in ECMAScript 6 (ES6) and is now the
preferred way to declare variables. Variables declared with let are block-scoped,
meaning they are limited to the block of code (within curly braces) where they are
defined.
let age = 25;

if (age > 18)

let isAdult = true;

3.const: The const keyword is also introduced in ES6 and is used to declare variables
whose values should not be re-assigned after their initial assignment. Like let, variables
declared with const are block-scoped.

const pi = 3.14;

Examples:

Here are a few examples demonstrating variable declarations using different keywords:

33 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

// Using var (not recommended)


var name = "Alice";
var age = 30;
function example() {
var name = "Bob"; // This does not affect the outer "name" variable
console.log(name); // Outputs "Bob"
}
// Using let
let count = 5;
if (count > 0) {
let message = "Count is positive"; // Block-scoped variable
console.log(message); // Outputs "Count is positive"
}
// Using const
const maxAttempts = 3;
// maxAttempts = 5; // This would result in an error since const variables are not re-
assignable
In general, it's recommended to use let and const over var, as they provide better scoping
and more predictable behavior. Use let when you need to reassign a variable's value, and
use const when you want to ensure the value remains constant throughout the program.

Scope Of Variables

In JavaScript, the scope of a variable determines where that variable can be accessed and
manipulated within your code. There are two main types of variable scope: global scope
and local (or block) scope.

1. Global Scope: Variables declared outside of any function or block have global
scope. They can be accessed from anywhere in your code, both within functions and

34 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

outside them. However, defining too many global variables can lead to naming
conflicts and can make it difficult to manage your codebase.

var globalVar = "I'm global";

function example()

console.log(globalVar); // Accessible inside the function

console.log(globalVar); // Accessible outside the function

2. Local (Block) Scope: Variables declared within a function or a block of code (such
as within the curly braces of an if statement or a loop) have local scope. They are
only accessible within the function or block where they are defined. This helps
encapsulate variables and avoid naming conflicts.

function example()

var localVar = "I'm local"; // Local variable

console.log(localVar); // Accessible inside the function

console.log(localVar); // Error: localVar is not defined

if (true) {

var insideIf = "I'm inside if"; // Function-scoped in pre-ES6

let insideIfBlock = "I'm inside if block"; // Block-scoped

console.log(insideIf); // Accessible (but discouraged)

35 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

console.log(insideIfBlock); // Error: insideIfBlock is not defined

With the introduction of let and const in ECMAScript 6 (ES6), you also have block-
scoped variables that behave more intuitively within blocks of code, such as if statements
or loops.

function example()

if (true)

let blockScopedVar = "I'm block-scoped"; // Block-scoped variable

console.log(blockScopedVar); // Accessible within the block

console.log(blockScopedVar); // Error: blockScopedVar is not defined

It's important to note that variables declared with var are function-scoped, even if they
appear to be defined within a block. Variables declared with let and const are block-
scoped, meaning they are confined to the nearest pair of curly braces.

Understanding variable scope is essential for writing maintainable and bug-free code.
Using local (block) scope as much as possible and minimizing the use of global variables
can help prevent unexpected behaviors and conflicts in your JavaScript programs.

FUNCTIONS:

Functions in JavaScript are blocks of code that can be defined and invoked to perform a
specific task or return a value. They play a crucial role in structuring and organizing your
code, promoting reusability, and making your programs more modular. Functions can take
inputs (arguments) and produce outputs (return values), and they can be called multiple
times from different parts of your code.

36 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Here's how you define and use functions in JavaScript:

Function Declaration: You can declare a function using the function keyword, followed
by the function name, a list of parameters (enclosed in parentheses), and the function body
(enclosed in curly braces). The function body contains the code that will be executed
when the function is invoked.

// Function declaration

function greet(name)

console.log("Hello, " + name + "!");

// Invoking the function

greet("Alice"); // Outputs: "Hello, Alice!"

greet("Bob"); // Outputs: "Hello, Bob!"

Function Expression: You can also define functions using function expressions. In this
case, the function is assigned to a variable. This approach is useful for creating
anonymous functions or passing functions as arguments to other functions.

// Function expression

const add = function(x, y)

return x + y;

};

// Invoking the function

37 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

const result = add(3, 5); // result will be 8

Arrow Functions (ES6): Arrow functions are a concise way to define functions,
introduced in ES6. They have a shorter syntax and automatically capture the value of this
from their surrounding context.

// Arrow function

const multiply = (a, b) => a * b;

// Invoking the function

const product = multiply(4, 6); // product will be 24

Function Parameters and Return Values: Functions can accept one or more parameters
(inputs) and can return a value using the return keyword. If a function doesn't explicitly
return a value, it returns undefined by default.

function square(number)

return number * number;

const squaredValue = square(5); // squaredValue will be 25

Function Scope: Variables declared inside a function are considered local to that
function's scope and are not accessible from outside the function. Conversely, variables
declared outside a function (in the global scope) can be accessed from within functions.

Function Invocation: To call (invoke) a function, you simply use its name
followed by parentheses, passing any required arguments.

function say(message)

38 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

console.log(message);

say("Hello, world!"); // Outputs: "Hello, world!"

Functions are a fundamental building block in JavaScript programming. They allow


you to encapsulate logic, reduce redundancy, and create more organized and maintainable
code.

Event Handlers:

Event handlers in JavaScript allow you to respond to various interactions and events that
occur in a web page, such as user actions like clicks, keyboard input, mouse movements,
and more. They enable you to create dynamic and interactive web applications by defining
actions that should be executed when a specific event occurs.

Here's how event handlers work in JavaScript:

1. Event Types: Different types of events can occur in a web page, such as clicks, key
presses, form submissions, mouse movements, and more. Each event type
corresponds to a specific action that the user performs.

2. Event Listeners: An event listener is a function that "listens" for a particular event
on a specified HTML element. When the event occurs, the listener's function is
executed.

3. Attaching Event Listeners: You can attach event listeners to HTML elements
using JavaScript. This is commonly done by selecting the element using methods
like getElementById, querySelector, or querySelectorAll, and then calling the
addEventListener method on the selected element. The method takes two
arguments: the event type and the function to be executed when the event occurs.

Here's an example of attaching a click event listener to a button element:

<!DOCTYPE html>
<html>
<head>

39 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<title>Event Handlers Example</title>


</head>
<body>
<button id="myButton">Click me!</button>
<script>
// Get the button element by its id
const button = document.getElementById("myButton");
// Add a click event listener
button.addEventListener("click", function() {
alert("Button clicked!");
});
</script>
</body>
</html>
In this example, when the button is clicked, the anonymous function provided as the
second argument to addEventListener is executed, showing an alert with the message
"Button clicked!"

Common Event Types:

 click: Occurs when an element is clicked.

 keydown / keyup: Occurs when a key is pressed / released on the keyboard.

 mouseenter / mouseleave: Occurs when the mouse enters / leaves an element.

 submit: Occurs when a form is submitted.

 change: Occurs when the value of an input field changes.

 ...and many more.

40 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Event Object: When an event occurs, the browser creates an event object that
contains information about the event, such as the type of event, the target element, and any
relevant data. This event object is automatically passed to the event handler function as a
parameter. You can access its properties to get more information about the event.

button.addEventListener("click", function(event)

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

});

Using event handlers, you can make your web applications interactive and
responsive to user input, creating a more engaging user experience.

Onclick

onClick is an event attribute in HTML that allows you to specify JavaScript code to be
executed when an element is clicked. It's commonly used to attach a click event handler to
HTML elements, such as buttons, links, and images, so that a specific action is performed
when the user clicks on the element.

Here's how you can use the onClick attribute:

<!DOCTYPE html>

<html>

<head>

<title>onClick Example</title>

</head>

<body>

<button id="myButton" onClick="handleButtonClick()">Click me!</button>

<script>

function handleButtonClick()

41 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

alert("Button clicked!");

</script>

</body>

</html>

In this example, when the button with the id "myButton" is clicked, the
handleButtonClick() function is executed, showing an alert with the message "Button
clicked!"

However, while using the onClick attribute inline with HTML is straightforward, it's
generally recommended to separate your HTML and JavaScript code. Instead of using
onClick directly in the HTML, you can attach event listeners using JavaScript. This
approach keeps your code more organized and easier to maintain, especially for larger
projects.

Here's an example of attaching a click event listener using JavaScript:

<!DOCTYPE html>

<html>

<head>

<title>onClick Example</title>

</head>

<body>

<button id="myButton">Click me!</button>

<script>

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

42 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

button.addEventListener("click", function() {

alert("Button clicked!");

});

</script>

</body>

</html>

In this version, the event listener is added to the button element using
JavaScript. This practice separates the behavior from the HTML structure, making your
code more flexible and easier to maintain.

While onClick is a quick way to add interactivity to your web page, using JavaScript to
attach event listeners provides better control and separation of concerns in your code.

Document Object Model:

The Document Object Model (DOM) is a programming interface for web documents. It
represents the structure of an HTML or XML document as a tree-like structure, where
each node corresponds to a part of the document, such as elements, attributes, and text
content. The DOM allows scripts (usually written in languages like JavaScript) to interact
with and manipulate the content and structure of a web page in a dynamic and
programmatic way.

In simpler terms, the DOM is a way for scripts to access, modify, and manipulate the
elements and content of a web page in real-time.

Key concepts and components of the DOM include:

1. Nodes: Nodes are the fundamental building blocks of the DOM. Each element,
attribute, and text content in an HTML or XML document is represented as a node
within the DOM tree.

2. Elements: HTML elements like <div>, <p>, <img>, and so on, are represented as
element nodes in the DOM.

43 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

3. Attributes: Attributes of HTML elements, such as id, class, and src, are also
represented as nodes in the DOM.

4. Text Nodes: The actual text content within HTML elements is represented as text
nodes in the DOM.

5. Parent-Child Relationships: The hierarchical structure of HTML elements in a


document translates to parent-child relationships in the DOM tree. Elements
contained within other elements are considered children of those elements.

6. Siblings: Elements that share the same parent are referred to as siblings.

7. Methods and Properties: The DOM provides methods and properties that scripts
can use to interact with nodes. For example, you can use methods to change
element content, add or remove elements, change attributes, and more.

Here's a basic example of using JavaScript to access and manipulate the DOM:

<!DOCTYPE html>

<html>

<head>

<title>DOM Example</title>

</head>

<body>

<h1 id="myHeading">Hello, DOM!</h1>

<p id="myParagraph">This is a paragraph.</p>

<script>

// Accessing elements by their IDs

const headingElement = document.getElementById("myHeading");

const paragraphElement = document.getElementById("myParagraph");

// Modifying element content

44 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

headingElement.textContent = "Hello, Updated DOM!";

paragraphElement.style.color = "blue";

</script>

</body>

</html>

In this example, the JavaScript code uses getElementById to retrieve the <h1> and <p>
elements, then modifies their content and style properties using the DOM.

The DOM is a powerful concept that allows you to create dynamic and interactive web
pages by scripting the manipulation of elements and content. It's a key aspect of modern
web development and plays a vital role in building rich user experiences.

Form Validation:

Form validation is the process of ensuring that user input submitted through HTML forms
meets the specified requirements and constraints before it is processed by a server or used
in the application. Proper form validation helps ensure data accuracy, prevents errors, and
enhances user experience by providing immediate feedback to users when they enter
incorrect or incomplete information.

Here are some common techniques and practices for implementing form validation:

1. Client-Side Validation: Client-side validation occurs in the user's browser using


JavaScript. It provides instant feedback to users, reducing the chances of submitting
invalid data. Common validation checks include:

 Required fields: Ensuring that mandatory fields are filled out.

 Format validation: Verifying that input adheres to specific formats, such as


email addresses or phone numbers.

 Length validation: Checking if input length is within acceptable ranges.

 Numeric validation: Ensuring numeric values are within specific ranges.

 Regular expressions: Using patterns to validate complex input formats like


URLs or passwords.

45 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

2. HTML5 Input Types and Attributes: HTML5 introduced new input types and
attributes that assist with form validation. For example:

 required: Specifies that an input field must be filled out.

 type="email": Validates that the input is a valid email address.

 type="number": Validates that the input is a valid number.

3. Form Submission Handling: Before submitting the form data to the server, you
can use JavaScript to perform a final round of validation. This ensures that even if
the user bypasses client-side validation, the server receives valid data.

4. Feedback to Users: Providing clear and helpful error messages when validation
fails is crucial. This helps users understand what went wrong and how to correct it.

5. Server-Side Validation: Server-side validation is essential to prevent malicious or


incorrect data from being processed by your application. Never rely solely on
client-side validation, as it can be bypassed by users with malicious intent or those
who disable JavaScript.

6. Framework and Library Solutions: Many JavaScript frameworks and libraries


provide tools for simplifying form validation. For example, libraries like jQuery
Validation and validation libraries integrated into front-end frameworks like React
and Angular.

Here's a basic example of client-side form validation using HTML and JavaScript:

<!DOCTYPE html>

<html>

<head>

<title>Form Validation Example</title>

</head>

<body>

46 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<form id="myForm">

<label for="email">Email:</label>

<input type="email" id="email" required>

<br>

<button type="submit">Submit</button>

</form>

<script>

const form = document.getElementById("myForm");

form.addEventListener("submit", function(event)

const emailInput = document.getElementById("email");

if (!emailInput.checkValidity()) {

event.preventDefault();

alert("Please enter a valid email address.");

});

</script>

</body>

</html>

In this example, the form uses the required attribute and the type="email"
attribute to enable basic client-side validation. The JavaScript code adds a submit event
listener to the form, which checks the validity of the email input and prevents form
submission if the input is invalid.

47 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Remember that while client-side validation improves user experience, server-side


validation is essential for security and data integrity. Malicious users can bypass client-
side checks, so server-side validation ensures the data your application receives is safe and
accurate.

48 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Unit-5
Unit- V:
Introduction to PHP: Declaring variables, data types, arrays, strings, operators,
expressions, control structures, functions, reading data from web form controls like text
boxes, radio buttons, lists etc., Handling File Uploads. Connecting to database (MySQL as
reference), executing simple queries, handling results, Handling sessions and cookies File
Handling in PHP: File operations like opening, closing, reading, writing, appending,
deleting etc. on text and binary files, listing directories.

Introduction to PHP:

PHP (Hypertext Preprocessor) is a widely-used open-source scripting language designed


for web development. It's particularly well-suited for creating dynamic web pages and
web applications. PHP scripts are executed on the server, generating HTML that is then
sent to the client's browser, allowing you to build interactive and data-driven websites.

Key Features of PHP:

1. Server-Side Scripting: PHP is primarily used for server-side scripting. This means
that PHP code is executed on the web server before the HTML is sent to the client's
browser. This enables you to generate dynamic content and interact with databases,
files, and other server resources.

2. Ease of Use: PHP is known for its relatively simple and straightforward syntax,
making it accessible for beginners and experienced developers alike.

3. Integration: PHP can be embedded directly into HTML, allowing you to mix PHP
code with HTML markup. This makes it easy to create templates and dynamically
generate content.

4. Database Connectivity: PHP has extensive support for interacting with databases,
including MySQL, PostgreSQL, SQLite, and more. You can use PHP to retrieve,
insert, update, and delete data from databases.

5. Vast Community and Resources: PHP has a large and active developer
community, resulting in a wealth of online resources, tutorials, forums, and
libraries.

1|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

6. Cross-Platform: PHP is compatible with various operating systems, including


Windows, Linux, and macOS, making it versatile for different server environments.

7. Extensibility: PHP supports extensions and libraries that provide additional


functionality, allowing you to easily integrate third-party tools and technologies.

Example PHP Code:

Here's a simple example of PHP code embedded within HTML to display the current date
on a web page:

<!DOCTYPE html>

<html>

<head>

<title>PHP Example</title>

</head>

<body>

<h1>Welcome to My PHP Page</h1>

<p>Today's date is: <?php echo date("Y-m-d"); ?></p>

</body>

</html>

In this example, the PHP code <?php echo date("Y-m-d"); ?> generates the current date
and displays it within the paragraph element.

Getting Started with PHP:

To start using PHP, you need a web server that supports PHP processing. Common
options include Apache, Nginx, and XAMPP. PHP files have a .php extension, and the
PHP code is enclosed within <?php and ?> tags.

PHP can be used for various tasks, including generating dynamic web pages, handling
form submissions, interacting with databases, creating user authentication systems, and

2|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

more. As you become more familiar with PHP, you can explore its extensive features and
capabilities for web development.

Declaring variables:

In PHP, you can declare variables to store data values that you can use throughout your
script. PHP variables have a dollar sign ($) as a prefix, followed by the variable name.
Here's how you declare variables in PHP:

$variableName = value;

Here's a breakdown of the components:

 $: This dollar sign indicates that you are declaring a variable.

 variableName: Replace this with your desired variable name. Variable names are
case-sensitive and must start with a letter or underscore (_). They can contain
letters, numbers, and underscores.

 value: This is the value you want to assign to the variable.

Here are some examples of declaring variables in PHP:

$name = "Alice"; // String variable

$age = 30; // Integer variable

$height = 5.7; // Floating-point (decimal) variable

$isStudent = true; // Boolean variable

$colors = array("red", "green", "blue"); // Array variable (before PHP 5.4)

$fruits = ["apple", "banana", "orange"]; // Array variable (PHP 5.4 and later)

PHP is a loosely typed language, which means you don't need to declare the data type
explicitly when declaring a variable. PHP infers the data type based on the assigned value.
Additionally, PHP variables are dynamically typed, meaning you can change the type of
data a variable holds during runtime.

For example:

3|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$number = 5; // $number is an integer

$number = "five"; // $number is now a string

It's important to keep in mind that PHP variable names are case-sensitive ($variable and
$Variable are considered different variables), and they must start with a letter or
underscore.

Using meaningful variable names can make your code more readable and maintainable.
Additionally, adhering to consistent naming conventions, like camelCase or snake_case,
can help improve code clarity and collaboration.

Data Types:

PHP supports several data types that allow you to store and manipulate different types of
values. These data types include:

1. Integer: Represents whole numbers, both positive and negative.

$number = 42;

$negativeNumber = -10;

2. Float (Floating-Point): Represents decimal numbers (also known as floating-point


numbers or doubles).

$pi = 3.14;

$temperature = -12.5;

3. String: Represents sequences of characters, enclosed in single quotes ' or double


quotes ".

$name = "Alice";

$message = 'Hello, PHP!';

4. Boolean: Represents a true or false value.

$isStudent = true;

4|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$hasAccount = false;

5.Array: Represents an ordered collection of values, indexed by numerical or


associative keys.

$colors = array("red", "green", "blue");

$person = array("name" => "John", "age" => 28);

6. Object: Represents an instance of a class, containing properties (variables) and


methods (functions).

class Person

public $name;

public $age;

$person = new Person();

$person->name = "Alice";

$person->age = 30;

7. Null: Represents the absence of a value.

$emptyValue = null;

8. Resource: Represents a reference to an external resource, such as a database


connection or file handle.

$fileHandle = fopen("example.txt", "r");

5|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

9. Callable: Represents a callback function that can be called dynamically.

function sayHello($name)

echo "Hello, $name!";

$functionRef = 'sayHello';

$functionRef('Alice'); // Outputs: "Hello, Alice!"

10.Iterable (PHP 7.1+): Represents a data structure that can be looped through, such
as arrays and objects implementing the Traversable interface.

$fruits = array("apple", "banana", "orange");

foreach ($fruits as $fruit)

echo $fruit . " ";

These data types allow you to work with a wide range of values and perform various
operations in PHP. Additionally, PHP is a dynamically typed language, so you don't need
to declare the data type explicitly when declaring a variable; PHP infers it based on the
assigned value.

Arrays:

In PHP, an array is a versatile data structure that can hold multiple values under a single
variable name. Arrays are commonly used for storing and manipulating lists of related
data. PHP supports both indexed arrays (numeric indices) and associative arrays (string
indices).

Indexed Arrays:

6|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

An indexed array uses numeric indices to access its elements. The first element has an
index of 0, the second element has an index of 1, and so on.

$fruits = array("apple", "banana", "orange");

// or using short array syntax (PHP 5.4+)

$fruits = ["apple", "banana", "orange"];

echo $fruits[0]; // Outputs: "apple"

echo $fruits[1]; // Outputs: "banana"

echo $fruits[2]; // Outputs: "orange"

Associative Arrays:

An associative array uses string keys (also known as indices) instead of numeric
indices. Each key is associated with a value.

$person = array(

"name" => "Alice",

"age" => 30,

"city" => "New York"

);

// or using short array syntax (PHP 5.4+)

$person = [

"name" => "Alice",

"age" => 30,

"city" => "New York"

];

echo $person["name"]; // Outputs: "Alice"

echo $person["age"]; // Outputs: 30


7|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

echo $person["city"]; // Outputs: "New York"

Multidimensional Arrays:

Arrays can also be nested to create multidimensional arrays. A multidimensional


array is essentially an array of arrays.

$matrix = array(

array(1, 2, 3),

array(4, 5, 6),

array(7, 8, 9)

);

echo $matrix[0][0]; // Outputs: 1

echo $matrix[1][2]; // Outputs: 6

echo $matrix[2][1]; // Outputs: 8

Array Functions:

PHP provides a wide range of built-in functions for working with arrays. These functions
allow you to add elements, remove elements, sort arrays, merge arrays, and perform
various other operations.

Here are a few examples of array functions:

$numbers = [3, 1, 4, 1, 5, 9];

$length = count($numbers); // Get the number of elements in the array

$sum = array_sum($numbers); // Calculate the sum of array elements

$sortedNumbers = sort($numbers); // Sort the array in ascending order

8|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Strings:

In PHP, a string is a sequence of characters that represents text. Strings can include letters,
numbers, symbols, spaces, and special characters. PHP provides various functions and
features to work with strings, allowing you to manipulate, concatenate, format, and
perform other operations on text data.

Creating Strings:

You can create strings in PHP using single quotes (') or double quotes ("). Both single and
double quotes are used interchangeably, but there are a few differences:

$singleQuoted = 'This is a single-quoted string.';

$doubleQuoted = "This is a double-quoted string.";

// Embedding variables in double-quoted strings

$name = "Alice";

$greeting = "Hello, $name!";

String Concatenation:

You can concatenate (combine) strings using the . operator:

$firstName = "John";

$lastName = "Doe";

$fullName = $firstName . " " . $lastName; // Concatenates the strings

String Length:

You can find the length (number of characters) of a string using the strlen() function:

$phrase = "Hello, world!";

$length = strlen($phrase); // Returns the length of the string

Substring:

You can extract a portion of a string using the substr() function:

9|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$text = "The quick brown fox jumps over the lazy dog";

$substring = substr($text, 10, 5); // Extracts "brown"

String Functions:

PHP provides a rich set of functions for working with strings, such as:

 strtolower(): Converts a string to lowercase.

 strtoupper(): Converts a string to uppercase.

 trim(): Removes whitespace or specified characters from the beginning and end of
a string.

 str_replace(): Replaces occurrences of a substring with another substring.

 strpos(): Finds the position of the first occurrence of a substring in a string.

Here's an example of using some of these functions:

$text = " Hello, PHP! ";


$lowercase = strtolower($text); // " hello, php! "
$uppercase = strtoupper($text); // " HELLO, PHP! "
$trimmed = trim($text); // "Hello, PHP!"
$replaced = str_replace("PHP", "world", $text); // " Hello, world! "
$position = strpos($text, "PHP"); // Returns the position of "PHP"
Escape Sequences:

Escape sequences allow you to include special characters within strings:

 \": Double quote

 \': Single quote

 \\: Backslash

 \n: Newline

 \r: Carriage return

10 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 \t: Tab

$message = "She said, \"Hello!\"";

$newline = "Line 1\nLine 2";

Strings are a fundamental part of PHP programming, used for everything from basic text
output to complex text manipulation and processing. Understanding how to work with
strings effectively is crucial for building dynamic and interactive web applications

OPERATORS:

In PHP, operators are symbols or keywords that perform operations on values and
variables. They allow you to perform arithmetic, comparison, logical, and other types of
operations in your code. PHP supports a wide range of operators, each serving a specific
purpose. Let's explore some of the most common types of operators:

1. Arithmetic Operators:

Arithmetic operators perform basic mathematical operations.

 +: Addition

 -: Subtraction

 *: Multiplication

 /: Division

 %: Modulus (remainder)

 **: Exponentiation (PHP 5.6+)

Php:

$a = 10;

$b = 5;

$sum = $a + $b; // 15

$difference = $a - $b; // 5

$product = $a * $b; // 50

11 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$quotient = $a / $b; // 2

$remainder = $a % $b; // 0

$exponent = $a ** $b; // 100000

2. Assignment Operators:

Assignment operators are used to assign values to variables.

 =: Assign

 +=: Add and assign

 -=: Subtract and assign

 *=: Multiply and assign

 /=: Divide and assign

 %=: Modulus and assign

 **=: Exponentiation and assign (PHP 5.6+)

$x = 5;

$y = 3;

$x += $y; // $x is now 8

$x -= $y; // $x is now 5 again

$x *= $y; // $x is now 15

$x /= $y; // $x is now 5

$x %= $y; // $x is now 2

$x **= $y; // $x is now 8

3. Comparison Operators:

Comparison operators are used to compare values.

 ==: Equal to

12 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 != or <>: Not equal to

 ===: Identical (equal value and type)

 !==: Not identical

 <: Less than

 >: Greater than

 <=: Less than or equal to

 >=: Greater than or equal to

$a = 5;

$b = 3;

$result1 = $a == $b; // false

$result2 = $a > $b; // true

$result3 = $a !== $b; // true

4. Logical Operators:

Logical operators are used to combine or manipulate Boolean values.

 && or and: Logical AND

 || or or: Logical OR

 ! or not: Logical NOT

$condition1 = true;

$condition2 = false;

$result = $condition1 && $condition2; // false

$result = $condition1 || $condition2; // true

$result = !$condition1; // false

13 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

These are just a few examples of the many operators available in PHP. Operators are
fundamental to performing various tasks in your PHP scripts, from simple arithmetic
calculations to complex decision-making logic. Understanding how to use operators
effectively is essential for writing efficient and functional PHP code.

Expressions:

In programming, an expression is a combination of values, variables, operators, and


function calls that can be evaluated to produce a result. Expressions can be as simple as a
single value or as complex as a combination of values and operations. They are used
extensively in programming to compute values, make decisions, and perform various
tasks.

Here are a few examples of expressions in PHP:

1. Arithmetic Expression: An arithmetic expression involves mathematical


operations.

$result = (5 + 3) * 2; // Evaluates to 16

2. String Concatenation Expression: Combining strings using the concatenation


operator .

$greeting = "Hello, " . "world!";

3. Comparison Expression: Comparing values using comparison operators.

$isGreater = 10 > 5; // Evaluates to true

4. Function Call Expression: Calling a function and using its return value.

$length = strlen("Hello"); // Evaluates to 5

5. Logical Expression: Combining Boolean values using logical operators.

$result = ($a > 0) && ($b < 10); // Evaluates to true or false

6. Ternary Conditional Expression: Using the ternary conditional operator (? :) to


create a compact if-else expression.

14 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$result = ($a > $b) ? "Greater" : "Smaller";

7. Array Access Expression: Accessing elements within an array using indices.

$colors = ["red", "green", "blue"];

$selectedColor = $colors[1]; // Evaluates to "green"

8. Variable Expression: Using a variable's value.

$age = 25;

9. Complex Expression: Combining multiple expressions to achieve a more


complex result.

$totalPrice = $quantity * $unitPrice + ($quantity * $unitPrice * $taxRate);

Expressions are the building blocks of programs. They allow you to perform
calculations, make decisions, and manipulate data dynamically. Understanding how to
construct and evaluate expressions is crucial for effective programming in any language,
including PHP.

Control Structures:

Control structures in programming are constructs that enable you to control the flow of
execution within your code. They allow you to make decisions, repeat actions, and
execute different blocks of code based on conditions. PHP provides various control
structures that help you create logic and control the behavior of your scripts.

Here are some common control structures in PHP:

1. if Statement: The if statement allows you to execute a block of code if a certain


condition is true.

$age = 25;

if ($age >= 18)

echo "You are an adult.";

} else

15 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

echo "You are not an adult.";

2. elseif and else Statements: The elseif and else statements are used in combination
with if to create multiple conditional branches.

$score = 75;

if ($score >= 90)

echo "Excellent!";

} elseif ($score >= 70)

echo "Good!";

} else

echo "Needs improvement.";

3.switch Statement: The switch statement allows you to perform different actions based
on different values of a variable.

$dayOfWeek = "Wednesday";

switch ($dayOfWeek)

case "Monday":

case "Tuesday":

16 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

case "Wednesday":

case "Thursday":

case "Friday":

echo "It's a weekday.";

break;

case "Saturday":

case "Sunday":

echo "It's a weekend day.";

break;

default:

echo "Invalid day.";

3. for Loop: The for loop allows you to execute a block of code a specific number of
times.

for ($i = 1; $i <= 5; $i++)

echo "Iteration $i<br>";

4. while Loop: The while loop executes a block of code as long as a condition is true.

$counter = 0;

while ($counter < 3)

echo "Count: $counter<br>";

17 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$counter++;

5. do-while Loop: The do-while loop is similar to the while loop, but it guarantees
that the block of code is executed at least once.

$x = 1;

Do

echo "Value of x: $x<br>";

$x++;

} while ($x <= 5);

6. foreach Loop: The foreach loop is used to iterate through elements in an array or
other iterable objects

$fruits = ["apple", "banana", "orange"];

foreach ($fruits as $fruit)

echo "$fruit<br>";

Control structures provide the foundation for creating complex algorithms, making
decisions, and repeating actions in your PHP scripts. By mastering these structures, you
can create dynamic and responsive applications that cater to various scenarios and user
interactions.

18 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Functions:

In PHP, a function is a reusable block of code that performs a specific task. Functions are
used to organize code into manageable and modular pieces, making your code easier to
read, maintain, and debug. Functions encapsulate a set of instructions and can be called
from different parts of your program to execute the same logic.

Here's how you define and use functions in PHP:

Defining a Function:

To define a function, use the function keyword followed by the function name, a pair of
parentheses (), and a pair of curly braces {} containing the function's code.

function greet($name)

echo "Hello, $name!";

In this example, the function greet() takes a parameter $name and outputs a greeting
message with the provided name.

Calling a Function:

To call a function, simply write its name followed by parentheses containing any required
arguments.

greet("Alice"); // Outputs: "Hello, Alice!"

Returning Values:

Functions can also return values using the return keyword.

function add($a, $b)

return $a + $b;

19 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$result = add(5, 3); // $result is now 8

Function Parameters:

Functions can accept parameters (also known as arguments), which are values passed into
the function when it's called. These parameters can be used within the function's code.

function multiply($x, $y)

return $x * $y;

$product = multiply(4, 5); // $product is now 20

Default Values for Parameters:

You can provide default values for parameters. If a value is not provided when the
function is called, the default value will be used.

function power($base, $exponent = 2)

return $base ** $exponent;

$result1 = power(3); // Squares 3 (default exponent is 2)

$result2 = power(2, 4); // 2 raised to the power of 4

Scope:

Variables defined within a function have a local scope, meaning they are only accessible
within that function. Variables defined outside functions have a global scope and can be
accessed from any part of the script.

Built-in Functions:

20 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

PHP also provides a wide range of built-in functions that perform various tasks, such as
manipulating strings, working with arrays, interacting with databases, and more.

$length = strlen("Hello"); // Returns the length of the string

$uppercase = strtoupper("hello"); // Converts a string to uppercase

Creating and using functions is a fundamental concept in programming that promotes


code reusability, organization, and maintainability. By breaking down complex logic into
smaller functions, you can write more structured and efficient PHP applications.

Reading Data From Web Form Controls Like Text Boxes:

To read data from web form controls like text boxes in PHP, you need to retrieve the
values submitted by the user when the form is submitted. This involves using the $_POST
or $_GET superglobal arrays, depending on the form's method attribute (POST or GET).

Here's a step-by-step example of how to read data from text boxes in a web form using
PHP:

1. Create an HTML form with text boxes:

<!DOCTYPE html>

<html>

<head>

<title>Form Example</title>

</head>

<body>

<form method="post" action="process_form.php">

<label for="name">Name:</label>

<input type="text" id="name" name="name">

<br>

<label for="email">Email:</label>

21 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<input type="email" id="email" name="email">

<br>

<input type="submit" value="Submit">

</form>

</body>

</html>

In this example, the form submits data using the POST method to a file named
"process_form.php".

2. Create the PHP script to process the form data (process_form.php):

<!DOCTYPE html>

<html>

<head>

<title>Form Processing</title>

</head>

<body>

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = $_POST["name"]; // Retrieve the value of "name" field

$email = $_POST["email"]; // Retrieve the value of "email" field

echo "Name: $name<br>";

echo "Email: $email<br>";

} else

22 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

echo "Form not submitted.";

?>

</body>

</html>

In this script, we use the $_POST superglobal to access the values submitted through the
form. The $_POST array is associative, where the keys correspond to the name attributes
of the form controls.

When the user submits the form, the data entered into the text boxes will be displayed on
the "process_form.php" page.

Remember that user input should be validated and sanitized to ensure data security and
integrity. Additionally, you can use functions like isset() to check if a specific field has
been submitted and handle validation and error handling appropriately.

Note: If you used the GET method in your form (method="get"), you would use the
$_GET superglobal instead of $_POST to retrieve the form data.

Radio Buttons:

Radio buttons are a type of input control in HTML that allow users to select one option
from a group of choices. Radio buttons are often used when you want users to make a
single selection from a set of mutually exclusive options.

Here's how you can use radio buttons in an HTML form and process the selected value
using PHP:

1. Create an HTML form with radio buttons:

<!DOCTYPE html>

<html>

<head>

<title>Radio Button Example</title>

23 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

</head>

<body>

<form method="post" action="process_radio.php">

<p>Gender:</p>

<label>

<input type="radio" name="gender" value="male"> Male

</label>

<label>

<input type="radio" name="gender" value="female"> Female

</label>

<label>

<input type="radio" name="gender" value="other"> Other

</label>

<br>

<input type="submit" value="Submit">

</form>

</body>

</html>

In this example, the form contains a group of radio buttons with the same name attribute
("gender") but different value attributes.

2. Create the PHP script to process the selected radio button value
(process_radio.php):

<!DOCTYPE html>

<html>
24 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<head>

<title>Radio Button Processing</title>

</head>

<body>

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

if (isset($_POST["gender"])) {

$selectedGender = $_POST["gender"];

echo "Selected Gender: $selectedGender";

} else {

echo "No gender selected.";

} else {

echo "Form not submitted.";

?>

</body>

</html>

In this script, we use the $_POST superglobal to access the selected radio button value
based on its name attribute. We use the isset() function to check if the radio button was
selected before trying to access its value.

When the user submits the form, the selected gender option will be displayed on the
"process_radio.php" page.

25 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Radio buttons are commonly used for various user selections, such as gender, payment
methods, or preferences. Make sure to provide clear labels and meaningful values for
radio buttons to enhance the user experience. As with any form input, input validation and
sanitation are important considerations.

Lists:

In HTML, lists are used to group and present content in an organized manner. There are
three main types of lists: unordered lists (<ul>), ordered lists (<ol>), and definition lists
(<dl>). Lists are often used to display items, options, or definitions in a structured format.

Here's how you can use lists in HTML:

Unordered List (<ul>):

An unordered list is a list of items with bullet points. Each item is wrapped in an <li> (list
item) element.

<!DOCTYPE html>

<html>

<head>

<title>Unordered List Example</title>

</head>

<body>

<h2>Shopping List</h2>

<ul>

<li>Apples</li>

<li>Bananas</li>

<li>Oranges</li>

</ul>

26 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

</body>

</html>

Ordered List (<ol>):

An ordered list is a numbered list of items. Like unordered lists, each item is enclosed in
an <li> element.

<!DOCTYPE html>

<html>

<head>

<title>Ordered List Example</title>

</head>

<body>

<h2>Steps to Bake a Cake</h2>

<ol>

<li>Preheat the oven.</li>

<li>Mix the ingredients.</li>

<li>Pour the batter into a pan.</li>

<li>Bake for 30 minutes.</li>

</ol>

</body>

</html>

Definition List (<dl>):

A definition list is used to define terms and their corresponding definitions. It consists of
pairs of <dt> (definition term) and <dd> (definition description) elements.
27 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<!DOCTYPE html>

<html>

<head>

<title>Definition List Example</title>

</head>

<body>

<h2>Glossary</h2>

<dl>

<dt>HTML</dt>

<dd>Hypertext Markup Language</dd>

<dt>CSS</dt>

<dd>Cascading Style Sheets</dd>

</dl>

</body>

</html>

These are basic examples of how to use lists in HTML. Lists are versatile and can be
styled using CSS to enhance their appearance. They provide a clear and organized way to
present information on your web pages.

Handling File Uploads:

Handling file uploads in PHP involves receiving files that users submit through a form,
processing those files, and potentially storing them on the server. Here's a step-by-step
guide on how to handle file uploads using PHP:

1. Create an HTML Form:

Create an HTML form that includes an <input> element with type="file" to allow users
to choose and upload a file.

28 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<!DOCTYPE html>

<html>

<head>

<title>File Upload</title>

</head>

<body>

<form action="upload.php" method="post" enctype="multipart/form-data">

<input type="file" name="uploadedFile">

<input type="submit" value="Upload">

</form>

</body>

</html>

2. Process the Uploaded File in PHP:

Create a PHP script that handles the uploaded file. This script will be specified in the
action attribute of the form.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$targetDirectory = "uploads/"; // Directory where the uploaded files will be


stored

$targetFile = $targetDirectory .
basename($_FILES["uploadedFile"]["name"]);

$uploadSuccess =
move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $targetFile);

29 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

if ($uploadSuccess)

echo "File uploaded successfully.";

} else

echo "Error uploading file.";

?>

In this PHP script (upload.php), the following steps are performed:

 The target directory for storing uploaded files is specified.

 The $_FILES superglobal is used to access information about the uploaded file.

 The move_uploaded_file() function is used to move the uploaded file from the
temporary directory to the desired location.

3. Configure Server Settings:

Make sure that your server's PHP configuration allows file uploads. You may need to
adjust the values of the following PHP configuration directives in your php.ini file:

 file_uploads: Set to On to allow file uploads.

 upload_max_filesize: Specify the maximum size of uploaded files.

 post_max_size: Specify the maximum size of POST data (including uploaded


files).

4. Create the Upload Directory:

Create the directory where you want to store the uploaded files. In the example above, it's
the "uploads" directory. Ensure that the web server has appropriate write permissions to
this directory.

30 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

5. Security Considerations:

File uploads can be a security risk if not handled properly. Some security considerations
include:

 Validate file types and extensions to prevent users from uploading harmful files.

 Generate unique filenames for uploaded files to prevent overwriting.

 Store uploaded files outside of the web root directory to prevent direct access.

 Use input validation and sanitization to prevent malicious input.

Handling file uploads requires careful attention to security and proper error handling to
ensure that your application functions as expected and keeps user data safe.

Connecting To Database (Mysql As Reference):

To connect to a MySQL database from a PHP script, you'll need to use the MySQLi
(MySQL Improved) or PDO (PHP Data Objects) extension. These extensions provide an
interface for interacting with MySQL databases. Here, I'll show you how to use both
extensions to connect to a MySQL database in PHP.

Using MySQLi:

1. Create a Database Connection:

$servername = "localhost"; // Replace with your database server name

$username = "username"; // Replace with your MySQL username

$password = "password"; // Replace with your MySQL password

$database = "dbname"; // Replace with your database name

// Create a connection

$conn = new mysqli($servername, $username, $password, $database);

31 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

2. Perform Database Operations:

Once the connection is established, you can perform various database operations using the
$conn object.

$sql = "SELECT id, name, email FROM users";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

while ($row = $result->fetch_assoc()) {

echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";

} else {

echo "0 results";

// Close the connection

$conn->close();

Using PDO:

1. Create a Database Connection:

$servername = "localhost"; // Replace with your database server name


32 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$username = "username"; // Replace with your MySQL username

$password = "password"; // Replace with your MySQL password

$database = "dbname"; // Replace with your database name

try {

$conn = new PDO("mysql:host=$servername;dbname=$database", $username,


$password);

$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

echo "Connection failed: " . $e->getMessage();

2. Perform Database Operations:

You can perform database operations using the $conn object.

$sql = "SELECT id, name, email FROM users";

$result = $conn->query($sql);

foreach ($result as $row)

echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";

// Close the connection

$conn = null;

33 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Both MySQLi and PDO offer powerful features for connecting to databases, executing
queries, and fetching results. PDO is more versatile as it supports multiple database
systems, while MySQLi is tailored specifically for MySQL. It's important to properly
sanitize inputs and handle errors when interacting with databases to ensure data integrity
and security.

Executing Simple Queries

Executing simple queries in PHP involves using the database connection you've
established to send SQL queries to the database and retrieve results. Here are examples of
how to execute SELECT, INSERT, UPDATE, and DELETE queries using both MySQLi
and PDO extensions.

Using MySQLi:

1. SELECT Query:

php
$mysqli = new mysqli($servername, $username, $password, $database);
$query = "SELECT id, name, email FROM users";
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";
}
} else {
echo "0 results";
}

$mysqli->close();

34 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

INSERT Query:

$mysqli = new mysqli($servername, $username, $password, $database);

$name = "John Doe";

$email = "[email protected]";

$query = "INSERT INTO users (name, email) VALUES ('$name', '$email')";

if ($mysqli->query($query) === TRUE)

echo "New record created successfully";

} else

echo "Error: " . $mysqli->error;

$mysqli->close();

Using PDO:

1. SELECT Query:

try {

$pdo = new PDO("mysql:host=$servername;dbname=$database",


$username, $password);

$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

$query = "SELECT id, name, email FROM users";

$result = $pdo->query($query);

foreach ($result as $row) {

35 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";

$pdo = null;

} catch (PDOException $e) {

echo "Error: " . $e->getMessage();

INSERT Query:

try {

$pdo = new PDO("mysql:host=$servername;dbname=$database",


$username, $password);

$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

$name = "Jane Smith";

$email = "[email protected]";

$query = "INSERT INTO users (name, email) VALUES (:name, :email)";

$stmt = $pdo->prepare($query);

$stmt->bindParam(':name', $name);

$stmt->bindParam(':email', $email);

if ($stmt->execute()) {

echo "New record created successfully";

36 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

} else {

echo "Error: " . $stmt->errorInfo()[2];

$pdo = null;

} catch (PDOException $e) {

echo "Error: " . $e->getMessage();

These examples show how to execute simple queries using both MySQLi and PDO.
Remember to properly sanitize inputs and handle errors to ensure the security and
reliability of your database operations.

Handling Results:

When executing queries in PHP, you'll often need to handle and work with the results
returned from the database. The result of a query is typically a result set, which is a
collection of rows that match the query criteria. Here's how you can handle and process
query results using both MySQLi and PDO extensions.

Handling Results with MySQLi:

1. SELECT Query:

$mysqli = new mysqli($servername, $username, $password, $database);


$query = "SELECT id, name, email FROM users";
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";
}
37 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

} else {
echo "0 results";
}
$mysqli->close();
2. Working with Result Rows:

In the code above, the fetch_assoc() method retrieves the next row of the result set as an
associative array, where column names are used as keys. You can use other methods like
fetch_row() for indexed arrays or fetch_object() for objects.

Handling Results with PDO:

SELECT Query:
try {
$pdo = new PDO("mysql:host=$servername;dbname=$database", $username,
$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = "SELECT id, name, email FROM users";


$result = $pdo->query($query);

foreach ($result as $row)


{
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] .
"<br>";
}

$pdo = null;
} catch (PDOException $e)

38 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

{
echo "Error: " . $e->getMessage();
}

When executing queries in PHP, you'll often need to handle and work with the results
returned from the database. The result of a query is typically a result set, which is a
collection of rows that match the query criteria. Here's how you can handle and process
query results using both MySQLi and PDO extensions.

Handling Results with MySQLi:

1. SELECT Query:

phpCopy code

$mysqli = new mysqli($servername, $username, $password, $database); $query =


"SELECT id, name, email FROM users"; $result = $mysqli->query($query); if ($result-
>num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "ID: " . $row["id"] . " -
Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; } } else { echo "0 results";
} $mysqli->close();

2. Working with Result Rows:

In the code above, the fetch_assoc() method retrieves the next row of the result set as an
associative array, where column names are used as keys. You can use other methods like
fetch_row() for indexed arrays or fetch_object() for objects.

Handling Results with PDO:

1. SELECT Query:

phpCopy code

try { $pdo = new PDO("mysql:host=$servername;dbname=$database", $username,


$password); $pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION); $query = "SELECT id, name, email FROM users";
$result = $pdo->query($query); foreach ($result as $row) { echo "ID: " . $row["id"] . " -

39 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; } $pdo = null; } catch
(PDOException $e) { echo "Error: " . $e->getMessage(); }

Working with Result Rows:

In the PDO code above, the foreach loop iterates over the result set directly, treating each
row as an associative array by default.

When working with query results, consider the following points:

 Use the appropriate method (fetch_assoc(), fetch_row(), fetch_object(), etc.) to


retrieve rows in the format you need.

 Loop through the result set to process each row.

 Close or nullify the connection or statement when you're done to release resources.

Remember to sanitize and validate data retrieved from the database to ensure security and
integrity.

Handling Sessions And Cookies File Handling In PHP:

Handling sessions, cookies, and file handling are crucial aspects of web development.
Here's a brief overview of how to handle sessions, cookies, and file operations in PHP.

Handling Sessions:

Sessions allow you to maintain user data across multiple pages during a user's visit to your
website. PHP provides a way to manage sessions using the $_SESSION superglobal.

1. Start a session:

session_start();

2. Store data in session:


$_SESSION['username'] = 'user123';

3. Retrieve session data:

$username = $_SESSION['username'];

4. Destroy a session:

40 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

session_destroy();

Handling Cookies:

Cookies are small pieces of data stored on the user's computer. PHP provides a way to set
and retrieve cookies using the setcookie() function and the $_COOKIE superglobal.

1. Set a cookie:

setcookie('username', 'user123', time() + 3600, '/');

2. Retrieve a cookie:

$username = $_COOKIE['username'];

3. Delete a cookie:

setcookie('username', '', time() - 3600, '/');

File Handling in PHP:

File handling involves reading, writing, and manipulating files on the server. PHP
provides a variety of functions for file operations.
1. Reading a file:

$contents = file_get_contents('file.txt');

2. Writing to a file:

$data = "Hello, world!";

file_put_contents('file.txt', $data);

3. Appending to a file:

$data = "New data to append";

file_put_contents('file.txt', $data, FILE_APPEND);

4. Checking if a file exists:

if (file_exists('file.txt'))

41 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

// File exists

5. Deleting a file:

unlink('file.txt');

Uploading a file (handling file uploads):

$targetDirectory = 'uploads/';

$targetFile = $targetDirectory . basename($_FILES["uploadedFile"]["name"]);

move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $targetFile);

Remember to handle errors, sanitize user input, and secure your file operations to
ensure data integrity and prevent security vulnerabilities.

File Operations Like Opening:

In PHP, you can perform various file operations like opening, reading, writing, and
closing files. Here's a step-by-step guide on how to perform these operations:

Opening Files:

To open a file, you can use the fopen() function. This function returns a file handle that
you can use for subsequent file operations.

$filename = "example.txt";

$mode = "r"; // "r" for read mode

$fileHandle = fopen($filename, $mode);

if ($fileHandle)

echo "File opened successfully.";

42 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

// Perform other operations here

fclose($fileHandle); // Close the file when done

} else

echo "Error opening the file.";

The $mode parameter specifies the mode in which the file should be opened:

 "r": Read mode (file must exist)

 "w": Write mode (creates a new file or truncates an existing file)

 "a": Append mode (creates a new file or appends to an existing file)

 "x": Exclusive create mode (creates a new file, fails if it already exists)

Reading Files:

To read the contents of a file, you can use functions like fread() or fgets().

$filename = "example.txt";

$mode = "r";

$fileHandle = fopen($filename, $mode);

if ($fileHandle)

while (!feof($fileHandle))

$line = fgets($fileHandle);

echo $line;

43 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

fclose($fileHandle);

} else

echo "Error opening the file.";

Make sure to close the file using fclose() when you're done with it to free up system
resources.

Appending to Files:

To append data to an existing file, you can use append mode "a".

$filename = "example.txt";

$mode = "a"; // Append mode

$fileHandle = fopen($filename, $mode);

if ($fileHandle)

$data = "Appended content!";

fwrite($fileHandle, $data);

fclose($fileHandle);

echo "Data appended successfully.";

} else

echo "Error opening the file.";

44 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

These are the basic file operations in PHP. Remember to handle errors gracefully and to
properly validate and sanitize user inputs to ensure the security and integrity of your file
handling operations.

Closing, Reading, Writing, Appending, Deleting Etc. On Text And Binary Files :

Opening and Closing Files:

Opening and closing files are common operations before and after working with file
contents.

// Opening a file in read mode (text)

$fileHandle = fopen("text_file.txt", "r");

// Opening a file in binary mode

$binaryFileHandle = fopen("binary_file.bin", "rb");

// Remember to close the file handles when done

fclose($fileHandle);

fclose($binaryFileHandle);

Reading from Text Files:

Reading text from a file can be done using functions like fread() or fgets().

$fileHandle = fopen("text_file.txt", "r");

while (!feof($fileHandle))

$line = fgets($fileHandle);

echo $line;

} fclose($fileHandle);

45 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Reading from Text Files:

Reading text from a file can be done using functions like fread() or fgets().

$fileHandle = fopen("text_file.txt", "r");

while (!feof($fileHandle))

$line = fgets($fileHandle);

echo $line;

fclose($fileHandle);

Writing to Text Files:

Writing text to a file can be done using functions like fwrite().

$fileHandle = fopen("text_file.txt", "w");

$data = "Hello, world!\n";

fwrite($fileHandle, $data);

fclose($fileHandle);

Appending to Text Files:

Appending text to a file can be done using append mode "a".

$fileHandle = fopen("text_file.txt", "a");

$data = "Appended content!\n";

fwrite($fileHandle, $data);

fclose($fileHandle);

46 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Reading from Binary Files:

Reading binary data from a file can be done using functions like fread().

$binaryFileHandle = fopen("binary_file.bin", "rb");

$data = fread($binaryFileHandle, filesize("binary_file.bin"));

fclose($binaryFileHandle);

Writing to Binary Files:

Writing binary data to a file can be done using functions like fwrite().

$binaryFileHandle = fopen("binary_file.bin", "wb");

$data = pack("C*", 65, 66, 67); // Write binary data

fwrite($binaryFileHandle, $data);

fclose($binaryFileHandle);

Deleting Files:

Deleting files can be done using the unlink() function.

if (unlink("file_to_delete.txt"))

echo "File deleted successfully.";

} else

echo "Error deleting the file.";

These examples demonstrate how to perform various file operations on both text
and binary files in PHP. Make sure to handle errors, close file handles, and
validate/sanitize user inputs to ensure proper functionality and security.
47 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Listing Directories.

To list directories and their contents in PHP, you can use the scandir() function. This
function returns an array of file and directory names within the specified directory.

Here's how you can use scandir() to list directories and their contents:

$directory = "path/to/directory"; // Replace with the actual directory path

$contents = scandir($directory);

foreach ($contents as $item)

if ($item != "." && $item != "..")

echo $item . "<br>";

In this example, scandir() retrieves the list of items in the specified directory, including .
(current directory) and .. (parent directory). The loop then iterates through the array and
prints each item's name, excluding . and ...

If you want to filter the results to only display directories, you can use the is_dir()
function:

$directory = "path/to/directory"; // Replace with the actual directory path

$contents = scandir($directory);

foreach ($contents as $item) {

if ($item != "." && $item != ".." && is_dir($directory . "/" . $item)) {

echo $item . "<br>";

}}

48 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

In this modified example, the is_dir() function is used to check if each item is a directory
before printing it.

Remember to replace "path/to/directory" with the actual path to the directory you want to
list. Additionally, ensure that you have the necessary file system permissions to access the
directory and its contents.

@@@@@@@@@@@@@@@ALL THE BEST@@@@@@@@@@@@@@@@

49 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT

You might also like