1 To 5 Unit
1 To 5 Unit
Browser Fundamentals
1. What is a Browser?
○ A web browser is software that retrieves, displays, and navigates web
content. Examples include Chrome, Firefox, Safari, and Edge.
2. Main Components of a Browser
○ User Interface (UI): Address bar, navigation buttons, bookmarks, etc.
○ Rendering Engine: Parses HTML, CSS, and JavaScript to render web pages
(e.g., Blink for Chrome, WebKit for Safari).
○ Networking: Handles communication with servers using HTTP/HTTPS.
○ JavaScript Engine: Executes JavaScript code (e.g., V8 in Chrome).
○ Storage: Manages cookies, local storage, and cache for faster access.
3. Browser Rendering Process
○ Parse HTML to create a Document Object Model (DOM).
○ Parse CSS to create a CSS Object Model (CSSOM).
○ Combine DOM and CSSOM into a render tree.
2
○ Layout the render tree and paint it on the screen.
4. Browser Caching
○ Browsers store copies of frequently accessed resources (e.g., images,
scripts) to reduce loading time and server load.
5. Developer Tools
○ Inspect and debug HTML, CSS, and JavaScript.
○ Analyze performance and optimize website speed.
Client-Server Communication
Client-server communication is a model where a client (typically a browser or an
application) sends a request to a server, and the server processes it to send a
response. This interaction forms the foundation of most web and networked
applications.
Client:
Server:
Client-Side Components
○ User Interface (UI): Frontend design and functionality (e.g., HTML, CSS,
JavaScript).
○ Communication Module: Handles data exchange with the server (e.g.,
AJAX, Fetch API).
○ Storage: Local storage, cookies, or session storage for caching data.
● Server-Side Components
○ Web Server: Receives and processes client requests (e.g., Apache, Nginx).
3
○ Application Server: Handles business logic and connects with databases
(e.g., Node.js, Flask, Spring).
○ Database: Stores and retrieves data (e.g., MySQL, MongoDB).
● Protocols
○ HTTP/HTTPS: Hypertext Transfer Protocol for communication.
○ WebSocket: For real-time, full-duplex communication.
○ REST or GraphQL: API paradigms for structured data exchange.
● Security
○ Authentication: Ensures the user is who they claim to be (e.g., OAuth,
JWT).
○ Encryption: Protects data using HTTPS and SSL/TLS.
○ Authorization: Determines access rights to resources.
Client-Server Architecture
1. Two-Tier Architecture:
4
2. Three-Tier Architecture:
● Role: This is the front-end layer where users interact with the application.
It is responsible for presenting data to the user and interpreting user inputs.
● Components:
5
○ Web browsers, desktop applications, or mobile apps that communicate with
the other tiers.
● Technologies:
○ HTML, CSS, JavaScript for web applications.
○ Frameworks like Angular, React, Vue.js for dynamic web interfaces.
● Role: This middle layer handles the core functionality of the application,
such as processing business logic, making decisions, and managing data between
the other two tiers.
● Components:
○ Application server, middleware, APIs.
○ Handles business rules, calculations, and data processing.
● Technologies:
○ Server-side programming languages: Java, Python, Ruby, PHP, C#, Node.js.
○ Frameworks: Spring, Django, Flask, ASP.NET.
● Role: The data tier stores, retrieves, and manages application data. It is
responsible for database operations like storing records, querying, updating, and
deleting data.
● Components:
○ Database servers like MySQL, PostgreSQL, Oracle, SQL Server, MongoDB.
● Technologies:
○ Relational databases (RDBMS) or NoSQL databases.
● Extends the three-tier model by adding layers such as caching servers, load
balancers, or microservices.
● Use Case: Large-scale distributed systems.
6
Multi-tier architecture and N-tier architecture are software design patterns
that help organize and structure the different components of an application. Both
are used to separate concerns, improve scalability, maintainability, and facilitate
better management of large systems. While the two terms are often used
interchangeably, there are slight differences based on the number of layers or
tiers involved.
Multi-Tier Architecture
● Presentation Tier: The user interface layer. It’s responsible for displaying
the data to the user and collecting user inputs. This could be a web interface or a
client-side application.
● Business Logic Tier (Application Tier): The business layer or logic layer,
which handles data processing and decision-making. It processes requests from
the presentation tier and sends them to the data tier.
● Data Tier: The data storage layer, typically a database, where the
application stores and retrieves data.
Key Features:
7
● Separation of concerns: Different layers are responsible for different parts of
the system, which improves maintainability.
● Scalability: Each layer can be scaled independently.
● Improved security: Sensitive data can be isolated in the data tier.
2. N-Tier Architecture
Key Features:
Comparison:
8
Logic, Data) Caching, Security, etc.)
The basic internet protocols are essential rules and standards that govern the
communication and functioning of the internet. These protocols allow devices to
9
communicate with each other, transfer data, and enable web services. Here's a
breakdown of some of the core internet protocols:
Variants:
● IPv4: The most widely used version, which uses 32-bit addresses.
● IPv6: The newer version with 128-bit addresses, designed to address the
limitations of IPv4, including address exhaustion.
● Purpose: HTTP is used for transmitting hypertext (web pages) over the
internet.
● Key Features:
○ A stateless protocol, meaning each request from a client to a server is
treated as independent.
○ It operates at the application layer, enabling browsers to fetch web pages
and other resources.
● Use: It is the foundational protocol for web browsing, allowing users to
access websites using URLs (Uniform Resource Locators).
10
Secure version:
● Purpose: FTP is used for transferring files between a client and a server
over the internet or a local network.
● Key Features:
○ Allows users to upload, download, and manage files on remote servers.
○ Supports both anonymous and authenticated access.
● Use: Commonly used for website management, software distribution, and
file sharing.
Variants:
● SFTP (Secure FTP): FTP over a secure connection using SSH (Secure Shell).
● FTPS: FTP with SSL/TLS encryption.
● Purpose: IMAP is another email retrieval protocol that allows email clients
to access and manage messages stored on a mail server.
11
● Key Features:
○ Keeps email messages on the server, allowing synchronization across
multiple devices.
○ Supports folders and more advanced email management features.
● Use: IMAP is used for users who need to access their email from multiple
devices or locations.
12
Protoc Purpose Primary Use
ol
13
S transfer
1. Web Browsers:
○ A web browser is a software application used to access and navigate the
World Wide Web. Examples include Google Chrome, Mozilla Firefox, Microsoft
Edge, and Safari.
○ Web browsers render HTML content (web pages), display images, run
scripts, and handle other web technologies to provide an interactive experience.
2. Web Servers:
○ A web server is a computer system that hosts web content and serves it to
users upon request.
○ Web servers respond to HTTP requests from browsers, sending back the
requested web pages (HTML documents, images, videos, etc.).
3. Web Pages:
○ A web page is a document that can be viewed in a browser. It is typically
written in HTML (Hypertext Markup Language) and may include other
technologies like CSS (Cascading Style Sheets) for design and JavaScript for
interactivity.
○ Web pages are linked together by hyperlinks, which are clickable
references to other pages or resources.
4. URLs (Uniform Resource Locators):
○ A URL is the address used to access resources on the web. It specifies the
protocol (HTTP/HTTPS), the domain name (e.g., www.example.com), and the
path to the specific resource (e.g., /about-us).
○ A typical URL looks like: https://www.example.com/page1.html.
5. Hyperlinks:
14
○ Hyperlinks are clickable elements in web pages that allow users to
navigate from one page to another. They are usually text or images that, when
clicked, take the user to a different web address (URL).
6. HTML (Hypertext Markup Language):
○ HTML is the foundational language for creating web pages. It structures
content with elements like headings, paragraphs, links, and images.
○ It forms the basic skeleton of a web page.
7. CSS (Cascading Style Sheets):
○ CSS is used to control the layout, design, and presentation of web pages. It
defines how HTML elements should be displayed (e.g., font style, colors, spacing,
etc.).
8. JavaScript:
○ JavaScript is a programming language that adds interactivity and dynamic
behavior to web pages. It is commonly used for features like form validation,
animations, and real-time updates.
1. Request-Response Model:
○ When a user enters a URL into their browser or clicks a link, a request is
sent over the internet to the corresponding web server.
○ The web server processes the request and sends back the requested data,
typically an HTML page along with other resources (images, videos, CSS files,
etc.).
○ The browser then processes the received data and displays the page to the
user.
2. Client-Server Interaction:
○ The client (user's browser) sends a request for a specific web page to the
server, which hosts the web content.
○ The server processes the request, retrieves the requested data (such as
HTML documents, images, etc.), and sends it back to the client.
3. Protocols:
○ The Web relies on HTTP (Hypertext Transfer Protocol) or its secure version,
HTTPS (HTTP Secure), to facilitate communication between browsers (clients)
and web servers.
○ When a user navigates to a URL starting with "https://", the connection is
encrypted using SSL/TLS for security.
4. Rendering:
○ Once the browser receives the HTML document and associated resources, it
uses its rendering engine to display the page. It interprets the HTML, applies
styles from CSS, and executes JavaScript to create the interactive experience.
HTML
What is HTML?
16
● HTML elements label pieces of content such as "this is a heading", "this is a
paragraph", "this is a link", etc.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
Example Explained
An HTML element is defined by a start tag, some content, and an end tag:
The HTML element is everything from the start tag to the end tag:
17
Start tag Element content End tag
It must only appear once, at the top of the page (before any HTML tags).
<!DOCTYPE html>
HTML Headings
HTML headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least important
heading:
Example
18
<h1>This is heading 1</h1>
HTML Paragraphs
HTML paragraphs are defined with the <p> tag:
Example
<p>This is a paragraph.</p>
HTML Links
HTML links are defined with the <a> tag:
Example
HTML Images
19
HTML images are defined with the <img> tag.
The source file (src), alternative text (alt), width, and height are provided as
attributes:
Example
HTML Elements
The HTML element is everything from the start tag to the end tag:
Note: Some HTML elements have no content (like the <br> element). These elements
are called empty elements. Empty elements do not have an end tag!
20
Nested HTML Elements
HTML elements can be nested (this means that elements can contain other
elements).
The following example contains four HTML elements (<html>, <body>, <h1> and
<p>):
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
Example
<html>
<body>
<p>This is a paragraph
<p>This is a paragraph
</body>
</html>
The <br> tag defines a line break, and is an empty element without a closing tag:
HTML Attributes
● All HTML elements can have attributes
● Attributes provide additional information about elements
● Attributes are always specified in the start tag
● Attributes usually come in name/value pairs like: name="value"
Example
There are two ways to specify the URL in the src attribute:
2. Relative URL - Links to an image that is hosted within the website. Here, the
URL does not include the domain name. If the URL begins without a slash, it will
be relative to the current page. Example: src="img_girl.jpg". If the URL begins
with a slash, it will be relative to the domain. Example:
src="/images/img_girl.jpg".
Tip: It is almost always best to use relative URLs. They will not break if you
change domain.
See what happens if we try to display an image that does not exist: <img
src="img_typo.jpg" alt="Girl with a jacket">
23
The style attribute is used to add styles to an element, such as color, font, size,
and more.
The <hr> element is used to separate content (or define a change) in an HTML
page:
Example
24
My Bonnie lies over the sea.
The HTML <strong> element defines text with strong importance. The content
inside is typically displayed in bold.
Tip: The <i> tag is often used to indicate a technical term, a phrase from another
language, a thought, a ship name, etc.
The HTML <em> element defines emphasized text. The content inside is typically
displayed in italic.
Tip: A screen reader will pronounce the words in <em> with an emphasis, using
verbal stress.
Tag Description
28
<del> Defines deleted text
You can add comments to your HTML source by using the following syntax:
<!-- Write your comments here -->
Notice that there is an exclamation point (!) in the start tag, but not in the end
tag.
Note: Comments are not displayed by the browser, but they can help document your
HTML source code.
Add Comments
With comments you can place notifications and reminders in your HTML code:
Example
Hide Content
Comments can be used to hide content.
This can be helpful if you hide content temporarily:
Example
<p>This is a paragraph.</p>
29
<!-- <p>This is another paragraph </p> -->
When you move the mouse over a link, the mouse arrow will turn into a little hand.
Note: A link does not have to be text. A link can be an image or any other HTML
element!
A local link (a link to a page within the same website) is specified with a relative
URL (without the "https://www" part):
Example
<h2>Absolute URLs</h2>
<p><a href="https://www.w3.org/">W3C</a></p>
<p><a href="https://www.google.com/">Google</a></p>
<h2>Relative URLs</h2>
<p><a href="html_images.asp">HTML Images</a></p>
<p><a href="/css/default.asp">CSS Tutorial</a></p>
Example
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;">
</a>
Button as a Link
To use an HTML button as a link, you have to add some JavaScript code.
JavaScript allows you to specify what happens at certain events, such as a click of
a button:
Example
<button onclick="document.location='default.asp'">HTML Tutorial</button>
32
HTML Tables
A table in HTML consists of table cells inside rows and columns.
Example
A simple HTML table:
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
Table Cells
Each table cell is defined by a <td> and a </td> tag.
td stands for table data.
33
Everything between <td> and </td> are the content of the table cell.
Example
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>
Table Rows
Each table row starts with a <tr> and ends with a </tr> tag.
tr stands for table row.
Example
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
Table Headers
Sometimes you want your cells to be table header cells. In those cases use the <th>
tag instead of the <td> tag:
th stands for table header.
34
Example
Let the first row be table header cells:
<table>
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>
35
<caption> Defines a table caption
Example
table, th, td {
border: 1px solid black;
}
The following values are allowed:
● dotted
● dashed
● solid
36
● double
● groove
● ridge
● inset
● outset
● none
● hidden
h h h
e e e
l l l
l l l
o o o
h h h
e e e
l l l
l l l
o o o
h h h
e e e
l l l
l l l
o o o
37
hello hello hello
Example
th, td {
padding: 15px;
}
To add padding only above the content, use the padding-top property.
And the others sides with the padding-bottom, padding-left, and padding-right
properties:
Example
th, td {
padding-top: 10px;
padding-bottom: 20px;
padding-left: 30px;
padding-right: 40px;
}
Example
38
table {
border-spacing: 30px;
}
NAME
APRIL
2022
39
FIESTA
Example
<table>
<tr>
<th colspan="2">Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>43</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>57</td>
</tr>
</table>
Example
<table>
40
<tr>
<th>Name</th>
<td>Jill</td>
</tr>
<tr>
<th rowspan="2">Phone</th>
<td>555-1234</td>
</tr>
<tr>
<td>555-8745</td>
</tr>
</table>
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
The <colgroup> element should be used as a container for the column specifications.
Each group is specified with a <col> element.
The span attribute specifies how many columns that get the style.
The style attribute specifies the style to give the columns.
Example
41
<table>
<colgroup>
<col span="2" style="background-color: #D6EEEE">
</colgroup>
<tr>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
...
HTML Lists
HTML lists allow web developers to group a set of related items in lists.
Example
An unordered HTML list:
● Item
● Item
● Item
● Item
An ordered HTML list:
1. First item
2. Second item
3. Third item
4. Fourth item
42
Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
43
Unordered HTML List - Choose List Item
Marker
The CSS list-style-type property is used to define the style of the list item marker. It
can have one of the following values:
Value Description
Disc
Example - Disc
<ul style="list-style-type:disc;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example
<ul>
<li>Coffee</li>
<li>Tea
44
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>
Example
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333333;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
45
padding: 16px;
text-decoration: none;
}
li a:hover {
background-color: #111111;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</body>
</html>
Type Description
type="I" The list items will be numbered with uppercase roman numbers
46
type="i" The list items will be numbered with lowercase roman numbers
Numbers
Numbers:
<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
HTML Iframes
An HTML iframe is used to display a web page within a web page.
Syntax
<iframe src="url" title="description"></iframe>
Tip: It is a good practice to always include a title attribute for the <iframe>. This is
used by screen readers to read out what the content of the iframe is.
Example
47
<iframe src="demo_iframe.htm" height="200" width="300" title="Iframe
Example"></iframe>
Or you can add the style attribute and use the CSS height and width properties:
Example
<iframe src="demo_iframe.htm" style="height:200px;width:300px;" title="Iframe
Example"></iframe>
Example
<iframe src="demo_iframe.htm" style="border:none;" title="Iframe
Example"></iframe>
Example
<iframe src="demo_iframe.htm" name="iframe_a" title="Iframe Example"></iframe>
<p><a href="https://www.w3schools.com"
target="iframe_a">W3Schools.com</a></p>
HTML Forms
An HTML form is used to collect user input. The user input is most often sent to a
server for processing.
Example
First name:
48
Last name:
Type Description
Text Fields
49
The <input type="text"> defines a single-line input field for text input.
Example
A form with input fields for text:
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
Radio Buttons
The <input type="radio"> defines a radio button.
Radio buttons let a user select ONE of a limited number of choices.
Example
A form with radio buttons:
<p>Choose your favorite Web language:</p>
<form>
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
</form>
Checkboxes
The <input type="checkbox"> defines a checkbox.
Checkboxes let a user select ZERO or MORE options of a limited number of choices.
Example
A form with checkboxes:
50
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>
51
191CAC602J - Web Technology
CSS Introduction
The main advantages are separation of content (in HTML) and styling (in
CSS) and the same CSS rules can be used across all pages and not have
to be rewritten.
Why CSS?
Saves Time: Write CSS once and reuse it across multiple HTML pages.
CSS Syntax
CSS consists of style rules that are interpreted by the browser and applied to the
corresponding elements. A style rule set includes a selector and a declaration
block.
The selector points to the HTML element that you want to style.
1. Selectors: Selectors are used to “select” the HTML element you want to
style. It can be an element type (e.g., h1), a class (e.g., .class-name), an
ID (e.g., #id-name), or a combination of these.
2. Properties: Properties are the aspects of the selected elements you want
to style (like color, width, height, etc.).
5. padding: Defines the space between the element’s content and its
border.
3. Values: Values define the specifics of the property you want to apply,
such as a color name, a number (e.g., 16px), or percentages (e.g., 50%).
Cascading Order:
The Cascading Order in CSS is a set of rules that determine which style will be
applied to an element when multiple styles are conflicting. These rules can be
used to achieve a desired layout or design, but understanding how they work is
crucial to effectively use CSS. In this article, we will explore the different
cascading methods that can be used inside the cascading order. First, let’s
understand the basic concept of cascading. The term “cascading” refers to the
way that styles are inherited and applied to elements in a web page. The
cascading order is the order in which styles are applied, with more specific styles
taking precedence over more general styles.
Specificity
Inheritance
Order of declaration
Specificity:
This method determines which style should be applied based on the specificity of
the CSS selectors used. More specific selectors (such as using an ID instead of a
class) will take precedence over less specific selectors. This method compares
the specificity of selectors to determine which rule should take precedence. The
more specific a selector is, the higher its specificity value and the more likely it is
to override other styles. The higher the specificity, the higher the priority of the
style. For example, an ID selector (#id) has a higher specificity than a class
selector (.class) or an element selector (element).
Inheritance:
This method determines which style should be applied based on the parent-child
relationship between elements. Styles applied to a parent element will be
inherited by its child elements unless overridden by a more specific style. This
method uses the !important keyword to indicate that a rule should take
precedence over all others. However, it is generally considered best practice to
avoid using !important unless absolutely necessary. Inheritance is the
mechanism by which styles are passed from a parent element to its children’s
elements. The child element inherits the styles of its parent element unless the
styles are explicitly overridden.
Syntax:
/* Parent selector */
body {
/* Styles */
/* Child selector */
p{
/* Styles */
Order of declaration:
This method determines which style should be applied based on the order in
which styles are declared. Styles declared later in the stylesheet will take
precedence over styles declared earlier unless they are overridden by a more
specific style. This method uses the order in which styles are declared to
determine precedence. Styles declared later in the document will override those
declared earlier.
Syntax:
.class {
/* Styles */
.class {
/* Styles */
Using CSS
CSS can be added to HTML documents in 3 ways:
The most common way to add CSS, is to keep the styles in external CSS files.
However, in this tutorial we will use inline and internal styles, because this is
easier to demonstrate, and easier for you to try it yourself.
Inline CSS
Internal CSS
External CSS
An external style sheet is used to define the style for many HTML pages.
To use an external style sheet, add a link to it in the <head> section of each
HTML page.
Inheritance
In CSS, inheritance controls what happens when no value is specified for a
property on an element.
Refer to any CSS property definition to see whether a specific property inherits
by default ("Inherited: yes") or not ("Inherited: no").
Inherited properties
When no value for an inherited property has been specified on an element, the
element gets the computed value of that property on its parent element. Only
the root element of the document gets the initial value given in the property's
summary.
Non-inherited properties
You can control inheritance for all properties at once using the all shorthand
property, which applies its value to all properties.
CSS Selectors
CSS selectors target the HTML elements on your pages, allowing you to add
styles based on their ID, class, type, attribute, and more. This guide will help
you to understand the intricacies of CSS selectors and their important role in
enhancing the user experience of your web pages. Understanding these
selectors—such as the universal selector, attribute selector, pseudo-class selector,
and combinator selectors—enables more efficient and dynamic web design.
CSS Properties
In this example, two CSS properties are applied to the div element: The border
and the font-size properties.
1. property-name: property-value
If you specify more than one CSS property, each name-value pair is separated
by a semicolon like this:
1. property1 : property-value1;
2. property2 : property-value2;
The last property declaration does not have to end with a semicolon, but it
makes it easier to add more CSS properties without forgetting to put in that
extra semicolon.
Benefits of CSS Properties
CSS properties have several benefits for web development, such as:
o Separation of concerns
o Responsive design
o Ease of maintenance
o Accessibility
o Performance optimization
o Browser compatibility
o Print-friendly styling
o Accessibility enhancements
Browser
Browser-specific CSS refers to CSS styles that are written or applied to target
specific web browsers or browser versions, due to the fact that different
browsers may interpret and render CSS rules differently.
However, with modern browsers and CSS standards evolving, much of the need
for browser-specific CSS has diminished, but it still exists in certain cases.
Browser-specific CSS rules are usually implemented using vendor prefixes or
specific CSS hacks, allowing developers to apply styles that are only recognized
by particular browsers.
Here are the key reasons to apply browser-specific CSS in 1-liner pointers:
The DOM is not a binary description, as it does not define any binary
source code in its interfaces.
Levels of DOM
DOM consisted of multiple levels, each representing different aspect of the
document.
Level 1: DOM level 1 can be described in two parts: CORE and HTML.
o LOAD and SAVE: This allows the program to dynamically load the
content of the XML document into the DOM document and save the
DOM Document into an XML document by serialization.
Using DOM and Events: Suppose we want to make changes in the document
or stylesheet on a certain event. The event can be the loading of a web page,
selection of any specific element or a form is submitted, etc.
Window Event Attributes: These events are triggered for the window
object.
Mouse Events: These are the most common events with basic interaction
of user through the mouse.
KeyBoard Events:
Intrinsic Events
An intrinsic event determines when an associated script will run. However, not
every intrinsic event works with every (X)HTML element. This table illustrates
which events and tags work together.
onfocus
below)
html
css
.save {
background: blue;
color: white;
font-size: 1.2rem;
font-family: sans-serif;
.btn {
padding: 0.2rem;
background: black;
color: white;
js
Looking at the HTML, CSS, and JS above, we can see that the <button> element
has two classes applied to it: .btn and .save. These two classes define several
properties for the visual presentation of the button. In the JavaScript part of the
example, we select the saveButton using a
standard document.querySelector() call. Once we have selected the button
element we can access the element.style attribute to read and print the CSS
properties applied to this element.
saveButton.style.background = "red";
saveButton.style.color = "yellow";
These two lines of JavaScript would alter the background and text color of the
button. We could set these style properties to any valid CSS value and they
would override the existing style in the browser.
1. EventTypes
Common events include:
2. Event Listeners
button.addEventListener("click", () => {
alert("Button clicked!");
});
3. Event Propagation
o Capturing: Events are captured from the root down to the target
element.
4. Event Object
Example:
o Some events have default actions, like following a link when clicked.
event.preventDefault();
});
});
Introduction to JavaScript
Client-Side Scripting:
JavaScript runs in the browser, enabling faster responses to user
actions like clicks or form inputs without server communication.
Versatility:
JavaScript supports a wide range of applications, from simple tasks
like form validation to complex tasks like server management.
Event-Driven Programming:
JavaScript can react to user actions in real-time, such as updating
the page when a button is clicked.
Asynchronous Capabilities:
JavaScript can perform tasks (e.g., fetching data) in the background
without interrupting the user experience, thanks to techniques like
Promise and async/await.
Rich Ecosystem:
Libraries and frameworks like React, Angular, and Vue.js enhance
development efficiency and speed by offering pre-built tools and
components.
Imperative Programming:
o Focuses on controlling how tasks are performed, including
procedural and object-oriented approaches.
o For example, using for loops to iterate through data or
async/await to manage asynchronous operations.
Declarative Programming:
o Focuses on what should be done without detailing how.
o For example, using arrow functions or higher-order functions
like .map() and .filter().
Applications of JavaScript
Web Development:
o JavaScript brings interactivity and dynamic behavior to static
webpages. Frameworks like AngularJS enhance this process.
Web Applications:
o JavaScript powers modern web applications with dynamic
features, often using APIs and libraries like React.
Server Applications:
o Using Node.js, JavaScript enables server-side scripting and
full-stack development.
Game Development:
o With HTML5 and libraries like EaseJS, JavaScript allows the
creation of browser-based games.
Smartwatches:
o PebbleJS enables JavaScript applications on smartwatches,
particularly those requiring internet access.
Limitations of JavaScript
1. Security Risks:
o Vulnerable to attacks like Cross-Site Scripting (XSS), where
malicious scripts exploit website elements like <img> or
<script> tags to steal data.
2. Performance:
o JavaScript is slower than traditional compiled languages for
complex operations. However, for simple tasks in the browser,
performance is usually sufficient.
3. Complexity:
o Writing advanced JavaScript requires understanding
programming concepts and both client-side and server-side
scripting, which can be challenging.
4. Weak Error Handling and Type Checking:
o JavaScript is loosely typed, meaning variables don’t have fixed
types. This flexibility can lead to errors that are harder to
debug due to weak enforcement of type checking.
JavaScript Statements
In JavaScript, a statement is like a complete instruction that tells the
computer to do something. These statements are made up of different
parts: Values, Operators, Keywords, Expressions, and Comments.
Each statement is executed by the browser in the order it appears, line by
line.
Examples:
Semicolons
Semicolons are used to separate JavaScript statements. They mark
the end of a statement.
You can put multiple statements on one line if you separate them
with semicolons.
let a, b, c;
a = 2;
b = 3;
c = a + b;
console.log("The value of c is " + c + ".");
Code Blocks
A code block is a group of statements that are enclosed within curly
brackets {}. This allows multiple statements to be executed together.
function myFunction() {
console.log("Hello");
console.log("How are you?");
}
myFunction()
White Space
JavaScript ignores extra spaces in your code. This means you can use
spaces to make your code more readable without affecting how it works.
console.log(10*2);
console.log(10 * 2);
Keywords
Keywords are reserved words and cannot be used as a variable name. A
JavaScript keyword tells about what kind of operation it will perform.
Keyword Description
JavaScript Operators
Operators in JavaScript are symbols or keywords used to perform
operations on values, variables, or expressions. They form the backbone
of calculations, comparisons, and logical operations in JavaScript.
1. Arithmetic Operators
These operators are used to perform basic mathematical calculations.
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
% Modulus (Remainder) 5 % 3 2
** Exponentiation 5 ** 3 125
2. Assignment Operators
These operators assign values to variables.
3. Comparison Operators
Used to compare two values and return a Boolean (true or false).
4. Logical Operators
Used to perform logical operations and combine conditions.
` ` Logical OR
` ` OR `5
^ XOR 5^1 4
~ NOT ~5 -6
6. Ternary Operator
The ternary operator is a shorthand for if-else conditions.
Syntax: condition ? value_if_true : value_if_false
Example:
let age = 18;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"
7. String Operators
Used for concatenating strings.
9. Unary Operators
Operate on a single operand.
2. Object Types
Object types are collections of key-value pairs and can hold complex data.
Objects:
Objects are containers for storing related data and functions.
let person = { name: "Alice", age: 25, greet: function()
{ console.log("Hi!"); } };
Arrays:
Special objects that store ordered, index-based collections of values.
let colors = ["red", "green", "blue"];
Functions:
JavaScript treats functions as first-class objects.
function greet() { console.log("Hello"); }
Dates:
Represents dates and times.
let today = new Date();
Regular Expressions:
Patterns used for matching character combinations.
let regex = /ab+c/;
Other Object Types:
Map: Stores key-value pairs with unique keys.
Set: Stores unique values.
WeakMap: Like Map but keys must be objects, and they are
weakly referenced.
WeakSet: Like Set but with weak references.
Dynamic Typing
Variables in JavaScript can change their data type at runtime.
let value = 42; // number
value = "Hello, world!"; // string
value = true; // boolean
Type Conversion
Implicit Conversion (Type Coercion):
JavaScript automatically converts one data type to another.
console.log("5" + 2); // "52" (string concatenation)
console.log("5" - 2); // 3 (string converted to number)
Explicit Conversion:
Developers can convert types manually using functions like
Number(), String(), or Boolean().
let num = Number("42"); // Converts string to number
let str = String(42); // Converts number to string
let bool = Boolean(1); // Converts number to boolean (true)
JavaScript Functions
Functions in JavaScript are reusable blocks of code designed to perform a
specific task. They allow developers to structure, reuse, and manage their
code effectively.
Types of Functions
1. Function Declaration
A named function defined using the function keyword.
Can be called before its definition due to hoisting.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!
2. Function Expression
A function assigned to a variable.
Not hoisted, so it must be defined before use.
const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet("Bob")); // Output: Hello, Bob!
3. Arrow Functions
A concise syntax introduced in ES6.
Does not have its own this context, making it ideal for callbacks.
const greet = (name) => `Hello, ${name}!`;
console.log(greet("Charlie")); // Output: Hello, Charlie!
4. Anonymous Functions
Functions without a name.
Commonly used as arguments to other functions.
setTimeout(function() {
console.log("This is an anonymous function.");
}, 1000);
6. Constructor Functions
Used to create objects, often with the new keyword.
function Person(name, age) {
this.name = name;
this.age = age;
}
const person1 = new Person("Dave", 30);
console.log(person1.name); // Output: Dave
7. Async Functions
Introduced in ES8 for handling asynchronous code.
Use the async keyword and can await promises.
async function fetchData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
}
fetchData();
Function Parameters
Default Parameters
Provide default values for parameters if no value is passed.
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
console.log(greet()); // Output: Hello, Guest!
Rest Parameters
Allow a function to accept an indefinite number of arguments as an
array.
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
Higher-Order Functions
Functions that take other functions as arguments or return them as
results.
function greetUser(callback) {
callback("Eve");
}
greetUser((name) => console.log(`Hello, ${name}!`)); // Output: Hello,
Eve!
Closures
A closure is a function that remembers its outer scope even after the
outer function has executed.
function counter() {
let count = 0;
return function() {
count++;
return count;
};
}
const increment = counter();
console.log(increment()); // Output: 1
console.log(increment()); // Output: 2
Recursive Functions
A function that calls itself to solve a problem.
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120
AngularJS Basics
Core Concepts
1. Modules
Modules group together related components, directives, services, filters,
and configuration settings in an AngularJS application.
var app = angular.module('myApp', []);
2. Directives
Directives are markers on DOM elements (e.g., attributes, elements, or
classes) that tell AngularJS to attach specified behaviors.
Directive Description
Example:
<div ng-app="myApp" ng-controller="myCtrl">
<p ng-bind="message"></p>
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
</div>
3. Controllers
Controllers manage application logic and interact with the model and view.
app.controller('myCtrl', function($scope) {
$scope.message = "Hello, AngularJS!";
$scope.items = ["Item 1", "Item 2", "Item 3"];
});
4. Scope
The $scope object acts as the glue between the controller and the view. It
contains data and functions used in the application.
5. Filters
Filters transform data in the view. Built-in filters include:
currency: Formats numbers as currency.
date: Formats dates.
uppercase / lowercase: Converts text case.
filter: Filters an array.
Example:
<p>{{ price | currency }}</p>
<p>{{ date | date:'fullDate' }}</p>
6. Services
Services are reusable components that encapsulate business logic or data
sharing.
Example of creating a service:
app.service('myService', function() {
this.getMessage = function() {
return "Service Message";
};
});
Routing in AngularJS
AngularJS uses the $routeProvider service for configuring routes in SPAs.
Example:
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
});
});
Advantages of AngularJS
1. Declarative UI: HTML-based templates make the application more
intuitive.
2. Less Code: Directives and two-way data binding reduce the
amount of JavaScript needed.
3. Easy Testing: Supports unit and end-to-end testing.
4. Modular Architecture: Simplifies code organization and reuse.
Limitations of AngularJS
1. Performance Issues: Can become slow with large applications
due to two-way data binding.
2. Complex Debugging: Debugging AngularJS applications can be
challenging for beginners.
3. Outdated: AngularJS is an older framework, and newer versions
(Angular 2+ or React) are often preferred.
Introduction to React
Developed by Facebook, React focuses on building reusable UI
components.
React is declarative, component-based, and supports building
single-page applications (SPAs).
React efficiently updates and renders components when data
changes.
function Greeting() {
const name = "Kitty";
return <h1>Hello, {name}!</h1>;
}
Benefits of JSX
Improved Readability: Combines HTML and JavaScript in one
place.
Type Safety: Errors in JSX are caught during compilation.
Rich Syntax: Enables embedding JavaScript logic easily.
Reactivity: React efficiently updates the UI when data changes.
Virtual DOM
What is the Virtual DOM?
The Virtual DOM is a lightweight, in-memory representation of the actual
DOM. It’s an abstraction layer that React uses to optimize UI updates.
How it Works
1. When the state or props of a component changes, React creates a
Virtual DOM tree to represent the updated UI.
2. React compares the new Virtual DOM with the previous one using a
process called reconciliation.
3. Only the differences (diffs) are identified, and the real DOM is
updated selectively, minimizing performance overhead.
rendering components.
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Current Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
2. Install create-react-app
create-react-app is an official tool from React to set up a new React
project easily.
To install it globally, use npm:
npm install -g create-react-app
React applications are built using components, which are reusable pieces
of code that represent UI elements.
Example: Simple Counter App
1. App Component: Create a simple React component that displays a
counter and a button to increment it.
Inside the src folder, open App.js and replace its content with the
following code:
import React, { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default App;
This is a functional component using the useState hook to
manage the state (count).
The onClick event of the button increments the counter.
2. Run the app:
o If the server isn't running already, run npm start again, and
open the app in a browser.
function Form() {
const [name, setName] = useState('');
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
<button type="submit">Submit</button>
</form>
);
}
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
seconds: this.state.seconds + 1,
});
}
render() {
return <h1>Timer: {this.state.seconds}s</h1>;
}
}
Explanation:
componentDidMount is called after the component is added to the
DOM, where we set up the timer.
componentWillUnmount is called before the component is
removed from the DOM, which cleans up the interval.
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const timerID = setInterval(() => setSeconds(prevSeconds =>
prevSeconds + 1), 1000);
Explanation:
The useEffect hook runs once when the component mounts and sets
up the interval to increment the seconds.
The cleanup function inside useEffect is called when the component
unmounts, which clears the interval.
Conclusion
React provides an efficient way to build interactive user interfaces
using components.
JSX allows you to write HTML-like syntax within JavaScript, making
the development process more intuitive.
React's component life cycle is essential for managing side effects
and cleaning up resources.
Using functional components and hooks is the modern approach
for managing component state and life cycle in React applications.
191CAC602J - Web Technology
1
191CAC602J - Web Technology
2
▪ Servlet Lifecycle Management: Handles initialization,
execution, and destruction of servlets.
3
1. Client Request:
o A user interacts with a web browser (client) and sends an
HTTP request to a web server.
o Example: A user logs in by submitting their username and
password through a web form.
2. Request Forwarding:
o The web server receives the request and forwards it to the
servlet container.
3. Servlet Execution:
o The servlet container identifies the appropriate servlet to
handle the request.
4
● Platform-Independent: Runs on any platform with a Java-
enabled server.
5
2.Servlet Configuration (web.xml): The Servlet needs to be
configured in the web.xml file of the web application to map it to a
specific URL pattern.
PROGRAM:
3.Deploy the Web Application: After writing the servlet class and
configuration, you need to compile the servlet class and deploy it in a web
container like Apache Tomcat. Place the
6
● Request Handling: The doGet() or doPost() methods handle
incoming HTTP requests.
● Performance: Servlets are loaded once and then reused for each
request, making them more efficient compared to CGI (Common
Gateway Interface).
7
191CAC602J - Web Technology
creating a Servlet object, let’s first understand the life cycle of the Servlet
object which is actually understanding how the Servlet container manages
the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes
through four stages,
● Loading a Servlet.
● Request handling.
8
191CAC602J - Web Technology
9
the ServletRequest and ServletResponse objects
respectively.
● init()
● service()
● destroy()
10
Let’s look at each of these methods in details:
1. init() method: The Servlet.init() method is called by the Servlet
container to indicate that this Servlet instance is instantiated
successfully and is about to put into service.
11
3.destroy() method: The destroy() method runs only once during the
lifetime of a Servlet and signals the end of the Servlet instance.
Advantages:
1. Efficient Resource Management: Servlets are initialized once
and can handle multiple requests, reducing overhead.
2. Multi-Request Handling: One instance handles many requests,
improving performance.
3. Custom Request Processing: Allows flexible handling of different
HTTP methods (GET, POST, etc.).
Disadvantages:
1. Complex Session Management: Managing user sessions across
requests can be tricky.
2. Resource Leaks: Improper cleanup can lead to resource
management issues.
3. Scalability Challenges: Handling high traffic with a single servlet
instance can be difficult without proper scaling techniques.
Parameter Data Sessions
Parameter Data and Sessions in web applications are crucial for
managing data across different user interactions and requests. Here's a
brief explanation of each:
1. Parameter Data:
12
191CAC602J - Web Technology
● Examples:
o URL parameters: http://example.com?name=John&age=25
o Form parameters: Submitted via a form <input type="text"
name="username" />
o HTTP headers: Custom data passed along with the request
headers.
Usage in Servlets:
● Example:
String name = request.getParameter("name");
String age =
request.getParameter("age");
2. Sessions:
13
191CAC602J - Web Technology
Program:
String username = (String) session.getAttribute("username");
14
● No Recompilation/ Redeployment: Changes in JSP pages don't
require recompilation or redeployment.
Architecture of JSP
The JSP (Jakarta Server Pages) architecture defines the process of how a
JSP file is requested, processed, and returned to the client. JSP is a
server-side technology that simplifies web development by embedding
Java code within HTML pages. Its architecture is built on top of the
15
Servlet API and follows the Model-View-Controller (MVC) design
pattern.
1. Client (Browser):
16
oThe servlet container manages the lifecycle of servlets
generated from JSP files. It handles the translation,
compilation, and execution of servlets and provides HTTP
request/response handling.
5. Database/Backend (Optional):
o In most cases, JSP applications interact with databases to
retrieve or store data. JDBC (Java Database Connectivity) is
commonly used for database interaction in JSP applications.
1. Client Request:
o A client sends an HTTP request to the web server for a .jsp file.
2. JSP File Processing:
o The web server forwards the request to the JSP engine, which
handles the following:
▪ Translation: Converts the JSP file into a servlet.
▪ Compilation: Compiles the servlet into bytecode.
3. Servlet Execution:
o The servlet processes the request, executes any embedded
Java code, and generates a response (usually HTML).
4. Response to Client:
o The generated HTML or other web content is sent back to the
client.
17
● Complex Debugging: Debugging is challenging due to the mix of
Java code and HTML, making errors harder to isolate.
● First-Time Access Delay: Initial access requires compilation into a
servlet, causing latency.
● Outdated Technology: Modern frameworks like Spring, React, and
Angular offer better features and support, making JSP less preferred.
18
4. Configure the web.xml File (Deployment Descriptor):
● Place this file in the WEB-INF folder to map URLs to JSP files or
servlets.
Example
19
● Open a web browser and access your application by navigating to
the URL:
In JSP, certain classes are used for core functionalities. These are derived
from the Java Servlet API and enable dynamic web content generation.
20
1. javax.servlet.jsp.JspPage:
o An interface that all JSP pages must implement.
o Includes lifecycle methods like:
▪ jspInit(): Invoked during the initialization of the JSP
page.
▪ jspDestroy(): Invoked when the JSP page is destroyed.
2. javax.servlet.jsp.HttpJspPage:
o A subinterface of JspPage specifically for HTTP-based JSPs.
o Includes the service(HttpServletRequest req,
HttpServletResponse res) method, used to handle client
requests.
3. javax.servlet.jsp.JspWriter:
o Used to write content to the response stream.
o Provides methods like:
▪ print()
▪ println()
▪ clear()
▪ flush()
4. javax.servlet.jsp.PageContext:
o Provides access to various JSP scopes (page, request, session,
application).
o Manages shared resources like attributes and beans.
5. javax.servlet.jsp.tagext.Tag:
o Represents custom tags in JSP.
o Classes implementing this interface can define reusable tag
behaviors.
JSP tags enable embedding Java code within HTML for creating
dynamic web pages. These tags fall into three categories: Scripting
Elements, Directive Tags, and Action Tags.
1. Scripting Elements
21
191CAC602J - Web Technology
2. Directive Tags
22
3. Action Tags
● <jsp:useBean>:
o Creates or accesses a JavaBean object.
o Example:
● <jsp:setProperty>:
● Sets properties of a bean.
● Example:
● <jsp:getProperty>:
● <jsp:include>:
● <jsp:forward>:
23
● <jsp:param>:
24
4. Displaying Data on JSP: Using JSP tags or scriptlets to
dynamically insert the retrieved data into HTML.
● Execute SQL queries to fetch the required data from the database.
For example:
25
Step 4: Pass Data to JSP Page
● You can pass the fetched data from the Servlet to the JSP page via
request attributes:
26
● Integration with Java Technologies: JSP integrates well with
other Java-based technologies like Servlets, EJB, and JDBC for
database interaction.
Servlet JSP
27
191CAC602J - Web Technology
What is XML?
Extensible Markup Language (XML) is a markup language designed to
store, organize, and transfer data in a structured format that is both
machine-readable and human-readable. XML is widely used across web
applications, APIs, and data storage systems due to its flexibility and
simplicity.
Key Features of XML
1. Structured Data Representation: Data is organized hierarchically
using tags.
2. Human-Readable: The plain-text format makes it easy to read
and debug.
3. Platform Independent: Works across different programming
languages and operating systems.
4. Extensibility: Developers can define their own tags to suit their
data needs.
5. Self-Descriptive: Tags and attributes clearly describe the data
they enclose.
XML Documents
1
● XML documents are both machine-readable and human-
readable.
Structure of an XML Document
1. XML Declaration:
o Appears at the top of the file and specifies the XML version
and encoding.
o Example: <?xml version="1.0" encoding="UTF-8"?>
2. Root Element:
o
2
6. Comments:
o Used to add notes or explanations.
o Example:
<!-- This is a comment -->
3
o Can be used on any operating system and programming
language.
3. Self-Descriptive:
o Tags are user-defined, making the data easily understandable.
4. Supports Metadata:
o Attributes provide additional details about data.
5. Flexible and Extensible:
o Custom tags can be created to suit application needs.
Types of XML Documents
1. Well-Formed XML:
o Follows XML syntax rules.
4
o XML is widely used in applications for storing configuration
details (e.g., Android Manifest files).
Advantages of XML Documents
1. Interoperability:
o Standardized format ensures compatibility across systems.
2. Ease of Use:
o Simple syntax makes it easy to learn and implement.
3. Customizable:
o Tags and attributes can be tailored to specific applications.
4. Readable by Humans and Machines:
o Ensures clarity for developers and systems alike.
● The most common version is 1.0, but there's also 1.1, although it's
less commonly used.
5
● version="1.0": Specifies the version of XML. Currently, the most
widely used version is 1.0, but version 1.1 also exists, though it's
not commonly used.
● encoding="UTF-8": Specifies the character encoding used in the
document. UTF-8 is a common encoding because it supports a wide
range of characters from different languages.
● standalone="yes" or "no" (optional): Specifies whether the
document is self-contained or needs external resources (such as
DTD).
o standalone="yes" means the document doesn't
require a DTD to be valid.
o standalone="no" means the document depends on
a DTD.
XML Namespaces
XML namespaces prevent naming conflicts between elements and
attributes in XML documents, especially when various XML vocabularies
are joined or elements with the same name come from different sources.
Table of Content
6
Example: To demonstrate the XML library catalog file structure in XML.
<?xml version="1.0" encoding="UTF-8"?>
<library output:
xmlns="http://example.com/library">
<book>
<title>XML Basics</title>
<author>John Doe</author>
</book>
<book>
<title>Advanced XML</title>
<author>Jane Smith</author>
</book>
</library>
Prefixed Namespace Declaration
In XML namespaces, the Prefixed Namespace Declaration method assigns
a prefix to a namespace URI. This allows elements and attributes from
that namespace to be identified with the specified prefix. Prefixed
namespaces are especially beneficial when items from different
namespaces appear in the same XML document.
7
<catalog output:
xmlns:bk="http://example.com/books"
xmlns:auth="http://example.com/authors">
<bk:book>
<bk:title>XML Basics</bk:title>
<auth:author>John Doe</auth:author>
</bk:book>
<bk:book>
<bk:title>Advanced XML</bk:title>
<auth:author>Jane Smith</auth:author>
</bk:book>
</catalog>
Advantages of Using Namespaces in XML
1. Avoid Naming Conflicts: Ensures that elements with the same
name in different documents or vocabularies don't clash.
2. Organized and Structured Data: Helps in managing complex
data models with multiple domains.
3. Extensibility: Allows you to combine multiple XML formats and
vocabularies without conflicts.
Transforming XML Documents
Transforming XML documents refers to the process of converting XML
data from one format to another. This can be useful when you want to
present or manipulate the XML data differently
8
The most common methods for transforming XML documents are XSLT
(Extensible Stylesheet Language Transformations) and XPath. Here are
the key concepts:
1. XSLT (Extensible Stylesheet Language Transformations)
XSLT is a language used for transforming XML documents into different
formats such as HTML, plain text, or even other XML formats. It is the
primary method for transforming XML in web applications.
● XSLT Stylesheet: This defines the rules for transforming the XML
document.
9
191CAC602J - Web Technology
XSLT Stylesheet:
Output (HTML):
10
191CAC602J - Web Technology
Example of XPath:
1. Select the title element of the first book:
/books/book[1]/title
2. Select all title elements under book:
/books/book/title
Selecting XML Data with XPath
XPath (XML Path Language) is a language used to navigate through and
select specific parts of an XML document. XPath is integral to XSLT for
extracting and manipulating XML data.
Key Features of XPath:
11
2. Select the title element of the first book:
/books/book[1]/title
12
To enhance the visual representation of XML, XSLT stylesheets can be
applied. The XSLT defines how the XML data should be transformed and
displayed, typically as HTML.
Steps to Display Styled XML in Browsers:
1. Create an XML file containing the data.
2. Write an XSLT stylesheet to define how the data should appear
(e.g., as HTML).
3. Link the XSLT to the XML document using the <?xml-
stylesheet?> processing instruction.
13
Output in Browser:
When you open books.xml in a browser, the XSLT transforms the XML
data into an HTML table:
Book List
Yea
Title Author
r
Jane 202
Advanced XML
Java Web Services: Smith 3
14
platforms and programming languages, making them highly
interoperable.
@WebService
15
String sayHello(String name);
● Create a Java class that implements the methods defined in the SEI.
● Example:
@WebService(endpointInterface = "com.example.HelloWorld")
@WebService
@WebMethod
16
4. Publish the Web Service:
Endpoint.publish("http://localhost:8080/hello", new
HelloWorldImpl());
Once the web service is created and deployed, you can write a Java Web
Service Client to consume the service. A client typically sends requests
to the web service and handles the responses.
17
2. Create a Client Class:
o Use the generated classes to interact with the web
service.
o Example:
● Execute the client application to see the response from the web
service.
● WSDL Structure:
o <types>: Defines the data types used in the service.
o
18
191CAC602J - Web Technology
WSDL Example:
19
o Header: Contains metadata about the message, such as
authentication or transaction information.
o Body: Contains the actual message or request/response data.
20
21