WT Unit-1 To 5
WT Unit-1 To 5
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.
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.
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.
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.
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.
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.
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.
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:
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.
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:
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.
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.
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.
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.
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.
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.
They enable users to navigate the web, interact with content, and access online
services.
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:
click on or enter into your web browser's address bar to access websites and online
content.
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
https://www.example.com/blog/article?id=123#section2
Protocol: "https"
Subdomain: "www"
Domain: "example.com"
Path: "/blog/article"
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:
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.
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).
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.
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.
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:
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
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.
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.
1. User Interaction: Users interact with a browser by entering URLs, clicking links,
and using various browser features.
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.
5. Content Interaction: Users can interact with content on web pages through
clicking links, filling out forms, watching videos, and using various interactive
elements.
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.
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.
Basic Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Welcome to My Webpage</h1>
</body>
</html>
In this example:
<!DOCTYPE html> defines the document type and version of HTML being used.
<head> contains meta information about the document, like the title that appears in
the browser's tab.
<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, 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 brought improvements over its predecessor, including support for inline
images and form elements.
Tables allowed for better layout control, while frames enabled the creation of multi-
pane web layouts.
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 was designed to be more strict in its syntax, making it more compatible
with XML tools and parsers.
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 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.
<!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:
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.
<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>
</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:
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:
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:
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:
5. Horizontal Rule (<hr>): The <hr> element creates a horizontal rule, which is a
visible line that can be used to separate content.
Example:
<hr>
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:
7. Whitespace: HTML generally treats consecutive spaces and line breaks as a single
space. To create significant whitespace, you can use the HTML entity
(non-breaking space) or CSS properties.
Example:
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.
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:
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.
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:
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.
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:
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:
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.
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:
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.
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.
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:
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.
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.
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>
<section>
<h2>Welcome to Our Website!</h2>
<p>This is the main content section of our webpage.</p>
</section>
</main>
<footer>
<p>© 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;
}
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;
}
section {
border: 1px solid #ddd;
padding: 1rem;
}
In this example:
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 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:
<!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>
<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.
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 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:
<!DOCTYPE html>
<html>
<head>
<title>Frames Example</title>
</head>
<frameset cols="25%,75%">
</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."
<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:
CSS Grid: A powerful two-dimensional layout system that allows you to create
complex grid-based layouts with ease.
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.
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.
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.
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 */
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>
<title>My Website</title>
</head>
<body>
<h1>Welcome to My Website</h1>
</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.
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.
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:
Box Model: Added features like box-sizing and border-radius for more flexible
layout and design.
Text Effects: Added properties for text shadows, multi-column layouts, and text
wrapping.
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.
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:
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.
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.
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.
<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.
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.
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.
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
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.
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 <>.
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.
<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:
<name> and </name> define the start and end tags of the "name" element.
<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.
<elementName attributeName="attributeValue">
<book ISBN="123456789">
<title>XML Basics</title>
<author>Jane Smith</author>
</book>
In this example:
The <title> and <author> elements are nested within the <book> element.
</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.
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.
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.
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.
<!DOCTYPE catalog [
]>
In this example:
<!DOCTYPE catalog [...]> declares the document type and the internal DTD subset.
Attributes in DTD:
Attributes can also be defined in a DTD using the <!ATTLIST> declaration. For instance:
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.
While DTDs are a standardized way to define XML document structures, they have some
limitations:
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:
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.
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.
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.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="book">
<xs:complexType>
<xs:sequence>
</xs:sequence>
</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.
Precise Validation: XML Schemas provide more detailed and accurate validation of
XML documents, including data types and constraints.
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.
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.
2. Element: Elements correspond to HTML or XML tags. They can contain other
elements, attributes, and text nodes.
4. Text Node: Text nodes contain the actual text content within elements.
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.
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>
In this example:
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 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:
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.
<!DOCTYPE html>
<html>
<head>
<title>XHTML Parsing Example</title>
<script>
window.onload = function() {
// Access the <p> element by ID
var paragraphElement = document.getElementById("myParagraph");
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 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.
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:
<!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
The DOMParser object is used to parse the XML string and create a Document
Object Model (DOM) representation.
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:
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).
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
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
<script>
window.onload = function() {
// Access an element by its ID
var myElement = document.getElementById("myDiv");
</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.
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.
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;
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.
import org.xml.sax.helpers.DefaultHandler;
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;
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
@Override
@Override
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.
DOM (Document Object Model) and SAX (Simple API for XML) are two different
approaches to parsing and processing XML documents in programming. They have
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.
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.
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.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
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.
After the servlet is instantiated, the container calls the init method on the
servlet.
The init method is called only once during the servlet's lifetime.
The servlet container calls the appropriate service method (e.g., doGet,
doPost, etc.) based on the type of request received.
Each specific HTTP method (GET, POST, PUT, DELETE, etc.) has a
corresponding method in the servlet class (e.g., doGet, doPost, doPut,
doDelete, etc.).
These methods can be called multiple times during the servlet's life cycle,
depending on the number of requests received.
When the servlet container decides to remove the servlet instance (usually
during web application shutdown or redeployment), it calls the destroy
method.
Like the init method, the destroy method is called only once during the
servlet's lifetime.
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.
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.
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
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:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
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:
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.
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 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.
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.
2. Servlet Lifecycle:
Developers can override methods like init, service, and destroy to execute
custom code at specific stages of the servlet's lifecycle.
3. javax.servlet.http Package:
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:
7. Annotations:
8. Exception Handling:
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.
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.
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:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
response.setContentType("text/html");
out.println("<html><body>");
if (param2Values != null) {
out.println("<p>Param 2 Values:</p>");
out.println("<ul>");
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.
The getParameter method retrieves the value of a single parameter based on its
name.
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.
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>
<param-value>paramValue</param-value>
</init-param>
</servlet>
</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 = {
// ...
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.*;
super.init(config);
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 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:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
The doGet and doPost methods are overridden to handle HTTP GET and POST
requests, respectively.
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.
Accessing Servlets:
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.
Handling HTTP requests in servlets allows you to create dynamic and interactive web
applications that respond to user actions and input.
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:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
response.setContentType("text/html");
out.println("<html><body>");
out.println("</body></html>");
response.setContentType("text/plain");
In this example:
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.
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.).
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.*;
// Create a cookie
Cookie userNameCookie = new Cookie("username", "john_doe");
Cookie languageCookie = new Cookie("language", "en_US");
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>");
}
}
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.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
if (cookies != null) {
out.println("<p>Read Cookies:</p>");
out.println("<ul>");
{
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.
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.
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.*;
session.setAttribute("username", "john_doe");
response.setContentType("text/html");
out.println("<html><body>");
out.println("</body></html>");
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.*;
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.*;
session.invalidate();
response.setContentType("text/html");
out.println("<html><body>");
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.
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.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
Try
// Create a statement
statement = connection.createStatement();
// Execute a query
response.setContentType("text/html");
out.println("<html><body>");
out.println("<h1>User List</h1>");
while (resultSet.next())
out.println("</body></html>");
} catch (SQLException e)
e.printStackTrace();
} finally
// Close resources
try {
if (statement != null)
statement.close();
if (connection != null)
connection.close();
} catch (SQLException e)
e.printStackTrace();
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.
UNIT-4
UNIT IV:
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.
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.
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.
Here's a simple example of a JSP page that displays a message using embedded Java code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</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
towards using template engines, front-end frameworks, and APIs for building more
complex and responsive web applications.
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:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<%
counter++;
%>
<%-- This page directive sets the content type of the response --%>
<p>Counter: ${counter}</p>
</body>
</html>
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.
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.
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.
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.
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.
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.
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:
<!DOCTYPE html>
<html>
<head>
<title>Declarations in JSP</title>
</head>
<body>
<%!
int count = 0;
void incrementCounter() {
count++;
%>
</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.
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:
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.
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.
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.
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.
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>
</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.
Expressions are evaluated and their results are automatically escaped to prevent
cross-site scripting (XSS) vulnerabilities.
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.
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.
<!DOCTYPE html>
<html>
<head>
<title>Display Variable</title>
</head>
<body>
</body>
</html>
You can use JSTL (JavaServer Pages Standard Tag Library) to loop through a list and
display its elements.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul>
<li>${item}</li>
</c:forEach>
</ul>
</body>
</html>
Conditional Statements:
<!DOCTYPE html>
<html>
<head>
<title>Conditional Statement</title>
</head>
<body>
<c:choose>
<p>Welcome, Admin!</p>
</c:when>
<c:otherwise>
<p>Welcome, Guest!</p>
</c:otherwise>
</c:choose>
</body>
</html>
You can use the <jsp:include> tag to include content from another JSP file.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Main Page</h1>
<jsp:include page="included.jsp"/>
</body>
</html>
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:
<%
%>
2)Response:
<%
response.setContentType("text/html");
out.println("Hello, world!");
%>
3)Out:
<%
%>
4)Session:
<%
session.setAttribute("username", "john");
%>
5)Application:
<%
%>
6)Pagecontext:
Provides access to various objects and information about the JSP page.
<%
%>
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 (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:
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.
{
this.age = age;
}
}
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
person.setName("Alice");
person.setAge(25);
request.setAttribute("person", person);
request.getRequestDispatcher("example.jsp").forward(request, response);
jsp
<%
%>
<h1>Person Details</h1>
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).
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
response.addCookie(usernameCookie);
Accessing Cookies:
// In a servlet or JSP
if (cookies != null) {
if (cookie.getName().equals("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
// In a servlet or JSP
session.setAttribute("username", "john_doe");
java
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
Invalidating Sessions:
// In a servlet or JSP
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 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
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):
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;
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;
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.
<!DOCTYPE html>
<html>
<head>
<title>User List</title>
</head>
<body>
<h1>User List</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
<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.
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.
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.
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.
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.
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.
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.
Basic Syntax:
javascript
/* This is a
multi-line comment */
// Variables
let greeting = "Hello, ";
const recipient = "World";
// Output
console.log(greeting + recipient);
// Functions
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.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Introduction</title>
</head>
<body>
<h1>JavaScript Example</h1>
<script>
let message = "Hello, JavaScript!";
console.log(message);
</script>
</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:
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.
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.
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;
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:
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
outside them. However, defining too many global variables can lead to naming
conflicts and can make it difficult to manage your codebase.
function example()
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()
if (true) {
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)
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.
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)
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
return x + y;
};
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
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)
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)
console.log(message);
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.
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.
<!DOCTYPE html>
<html>
<head>
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)
});
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.
<!DOCTYPE html>
<html>
<head>
<title>onClick Example</title>
</head>
<body>
<script>
function handleButtonClick()
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.
<!DOCTYPE html>
<html>
<head>
<title>onClick Example</title>
</head>
<body>
<script>
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.
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.
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.
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.
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>
<script>
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:
2. HTML5 Input Types and Attributes: HTML5 introduced new input types and
attributes that assist with form validation. For example:
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.
Here's a basic example of client-side form validation using HTML and JavaScript:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="myForm">
<label for="email">Email:</label>
<br>
<button type="submit">Submit</button>
</form>
<script>
form.addEventListener("submit", function(event)
if (!emailInput.checkValidity()) {
event.preventDefault();
});
</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.
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:
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.
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>
</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.
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
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;
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.
$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:
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:
$number = 42;
$negativeNumber = -10;
$pi = 3.14;
$temperature = -12.5;
$name = "Alice";
$isStudent = true;
$hasAccount = false;
class Person
public $name;
public $age;
$person->name = "Alice";
$person->age = 30;
$emptyValue = null;
function sayHello($name)
$functionRef = 'sayHello';
10.Iterable (PHP 7.1+): Represents a data structure that can be looped through, such
as arrays and objects implementing the Traversable interface.
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:
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.
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(
);
$person = [
];
Multidimensional Arrays:
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
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.
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:
$name = "Alice";
String Concatenation:
$firstName = "John";
$lastName = "Doe";
String Length:
You can find the length (number of characters) of a string using the strlen() function:
Substring:
$text = "The quick brown fox jumps over the lazy dog";
String Functions:
PHP provides a rich set of functions for working with strings, such as:
trim(): Removes whitespace or specified characters from the beginning and end of
a string.
\\: Backslash
\n: Newline
\t: Tab
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:
+: Addition
-: Subtraction
*: Multiplication
/: Division
%: Modulus (remainder)
Php:
$a = 10;
$b = 5;
$sum = $a + $b; // 15
$difference = $a - $b; // 5
$product = $a * $b; // 50
$quotient = $a / $b; // 2
$remainder = $a % $b; // 0
2. Assignment Operators:
=: Assign
$x = 5;
$y = 3;
$x += $y; // $x is now 8
$x *= $y; // $x is now 15
$x /= $y; // $x is now 5
$x %= $y; // $x is now 2
3. Comparison Operators:
==: Equal to
$a = 5;
$b = 3;
4. Logical Operators:
|| or or: Logical OR
$condition1 = true;
$condition2 = false;
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:
$result = (5 + 3) * 2; // Evaluates to 16
4. Function Call Expression: Calling a function and using its return value.
$result = ($a > 0) && ($b < 10); // Evaluates to true or false
$age = 25;
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.
$age = 25;
} else
2. elseif and else Statements: The elseif and else statements are used in combination
with if to create multiple conditional branches.
$score = 75;
echo "Excellent!";
echo "Good!";
} else
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":
case "Wednesday":
case "Thursday":
case "Friday":
break;
case "Saturday":
case "Sunday":
break;
default:
3. for Loop: The for loop allows you to execute a block of code a specific number of
times.
4. while Loop: The while loop executes a block of code as long as a condition is true.
$counter = 0;
$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
$x++;
6. foreach Loop: The foreach loop is used to iterate through elements in an array or
other iterable objects
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.
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.
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)
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.
Returning Values:
return $a + $b;
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.
return $x * $y;
You can provide default values for parameters. If a value is not provided when the
function is called, the default value will be used.
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:
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.
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:
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<label for="name">Name:</label>
<br>
<label for="email">Email:</label>
<br>
</form>
</body>
</html>
In this example, the form submits data using the POST method to a file named
"process_form.php".
<!DOCTYPE html>
<html>
<head>
<title>Form Processing</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
} else
?>
</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:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Gender:</p>
<label>
</label>
<label>
</label>
<label>
</label>
<br>
</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>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["gender"])) {
$selectedGender = $_POST["gender"];
} else {
} else {
?>
</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.
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.
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>
</head>
<body>
<h2>Shopping List</h2>
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Oranges</li>
</ul>
</body>
</html>
An ordered list is a numbered list of items. Like unordered lists, each item is enclosed in
an <li> element.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ol>
</ol>
</body>
</html>
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>
</head>
<body>
<h2>Glossary</h2>
<dl>
<dt>HTML</dt>
<dt>CSS</dt>
</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 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:
Create an HTML form that includes an <input> element with type="file" to allow users
to choose and upload a file.
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
</form>
</body>
</html>
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") {
$targetFile = $targetDirectory .
basename($_FILES["uploadedFile"]["name"]);
$uploadSuccess =
move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $targetFile);
if ($uploadSuccess)
} else
?>
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.
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:
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.
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.
Store uploaded files outside of the web root directory to prevent direct access.
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.
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:
// Create a connection
// Check connection
if ($conn->connect_error) {
Once the connection is established, you can perform various database operations using the
$conn object.
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";
} else {
$conn->close();
Using PDO:
try {
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$result = $conn->query($sql);
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";
$conn = null;
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 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();
INSERT Query:
$email = "[email protected]";
} else
$mysqli->close();
Using PDO:
1. SELECT Query:
try {
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$result = $pdo->query($query);
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";
$pdo = null;
INSERT Query:
try {
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$email = "[email protected]";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
if ($stmt->execute()) {
} else {
$pdo = null;
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.
1. SELECT Query:
} 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.
SELECT Query:
try {
$pdo = new PDO("mysql:host=$servername;dbname=$database", $username,
$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo = null;
} catch (PDOException $e)
{
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.
1. SELECT Query:
phpCopy code
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.
1. SELECT Query:
phpCopy code
Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; } $pdo = null; } catch
(PDOException $e) { echo "Error: " . $e->getMessage(); }
In the PDO code above, the foreach loop iterates over the result set directly, treating each
row as an associative array by default.
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, 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();
$username = $_SESSION['username'];
4. Destroy a session:
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:
2. Retrieve a cookie:
$username = $_COOKIE['username'];
3. Delete a cookie:
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:
file_put_contents('file.txt', $data);
3. Appending to a file:
if (file_exists('file.txt'))
// File exists
5. Deleting a file:
unlink('file.txt');
$targetDirectory = 'uploads/';
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.
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";
if ($fileHandle)
} else
The $mode parameter specifies the mode in which the file should be opened:
"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";
if ($fileHandle)
while (!feof($fileHandle))
$line = fgets($fileHandle);
echo $line;
fclose($fileHandle);
} else
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";
if ($fileHandle)
fwrite($fileHandle, $data);
fclose($fileHandle);
} else
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 are common operations before and after working with file
contents.
fclose($fileHandle);
fclose($binaryFileHandle);
Reading text from a file can be done using functions like fread() or fgets().
while (!feof($fileHandle))
$line = fgets($fileHandle);
echo $line;
} fclose($fileHandle);
Reading text from a file can be done using functions like fread() or fgets().
while (!feof($fileHandle))
$line = fgets($fileHandle);
echo $line;
fclose($fileHandle);
fwrite($fileHandle, $data);
fclose($fileHandle);
fwrite($fileHandle, $data);
fclose($fileHandle);
Reading binary data from a file can be done using functions like fread().
fclose($binaryFileHandle);
Writing binary data to a file can be done using functions like fwrite().
fwrite($binaryFileHandle, $data);
fclose($binaryFileHandle);
Deleting Files:
if (unlink("file_to_delete.txt"))
} else
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:
$contents = scandir($directory);
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:
$contents = scandir($directory);
}}
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.