Skip to content
AL-703 (D) · Internet and Web Technology/Quick Revision Short Notes

Internet and Web Technology (AL-703 (D)) - Unit 4 Short Notes

UNIT 4: Internet and Web Technology

1. Web Fundamentals & Architecture

Internet vs World Wide Web (WWW)

Aspect Internet World Wide Web (WWW)
Definition Global network of interconnected computers using TCP/IP. Information space on the Internet containing interlinked hypertext documents.
Core Function Provides infrastructure for data communication (email, file transfer, etc.). A service that runs on the Internet, accessed via web browsers.
Protocols Uses multiple protocols (TCP/IP, SMTP, FTP). Primarily uses HTTP/HTTPS for communication.
Relationship The Internet is the highway; the WWW is a type of traffic (web pages) that uses it.

[!TIP] Common Exam Pitfall: Students often confuse the two. Remember: The WWW cannot exist without the Internet, but the Internet existed before the WWW (e.g., for FTP, email).

Hypertext Transfer Protocol (HTTP)

Definition: An application-layer protocol for distributed, collaborative, hypermedia information systems. It follows a stateless request-response model.

Request-Response Cycle:

  1. Client (Browser) sends an HTTP Request: Includes method (GET, POST), URL, headers (User-Agent, Accept), and optional body.

  2. Server receives request and processes it (may query a database, run a script).

  3. Server sends an HTTP Response: Includes status code (200 OK, 404 Not Found), headers (Content-Type, Cache-Control), and response body (HTML, JSON).

  4. Client renders the response.

Key HTTP Methods:

  • GET: Retrieve data. Parameters in URL. Idempotent & safe.

  • POST: Submit data to be processed. Parameters in request body. Not idempotent.

  • PUT: Update a resource.

  • DELETE: Remove a resource.

  • HEAD: Same as GET but without response body.

[!TIP] Exam Focus: Be ready to draw the request-response sequence diagram. Know the difference between GET (visible params, cacheable) and POST (hidden params, not cacheable).

Web 2.0 Concepts

Definition: A shift from static, read-only web pages (Web 1.0) to dynamic, user-participatory, and social web applications.

Key Features:

  • User-Generated Content: Blogs, wikis, social media posts.

  • Rich User Experience (UX): AJAX for partial page updates, intuitive interfaces.

  • Social Networking & Collaboration: Sharing, commenting, tagging, folksonomies.

  • Long Tail: Niche content aggregated by platforms (e.g., YouTube, Amazon).

  • Mashups: Combining data/services from multiple sources (e.g., Google Maps + real estate listings).

  • Software as a Service (SaaS): Web-based applications (Gmail, Google Docs).

Web Publishing Process

  1. Planning: Define purpose, audience, sitemap, wireframes.

  2. Content Creation: Write text, create images/media, develop code (HTML, CSS, JS).

  3. Design & Development: Apply CSS, add interactivity (JS), implement server-side logic (PHP, JSP).

  4. Testing: Cross-browser compatibility, functionality, performance, validation (W3C).

  5. Deployment: Upload files to a web server (Apache, IIS, Nginx) via FTP or control panel.

  6. Maintenance & Promotion: Update content, monitor traffic (analytics), SEO.

Web Browsers and Web Servers

Component Primary Function Examples Interaction Model
Web Browser (Client) Renders HTML/CSS, executes JS, sends HTTP requests. Chrome, Firefox, Safari, Edge Initiates connection to server on port 80 (HTTP) or 443 (HTTPS).
Web Server Listens for requests, serves static files, executes server-side scripts (PHP, JSP), returns responses. Apache, IIS, Nginx, Tomcat (for JSP) Processes request, generates response (static file or dynamic output), sends back to client.

[!DIAGRAM: CANVAS: A simple client-server diagram: User's Computer (Browser) --HTTP Request--> Web Server (Apache/PHP) --HTTP Response--> User's Computer (Browser displays page).]

Web Design Challenges & Mitigation

Challenge Description Mitigation Strategies
Browser Compatibility Different browsers (and versions) render HTML/CSS/JS differently. Use standard-compliant code, test on major browsers, use CSS resets, feature detection (Modernizr).
Bandwidth Constraints Slow connections lead to long load times. Optimize images (compress, use correct format: JPEG, PNG, WebP), minify CSS/JS, use lazy loading, leverage caching.
Caching Mechanisms Browsers/proxies store copies of resources to reduce requests. Set appropriate Cache-Control and Expires headers. Use versioning in filenames (style.v2.css) to force cache refresh on updates.
Display Resolution Variations Varying screen sizes (desktop, tablet, mobile) and resolutions. Implement Responsive Web Design (RWD) using fluid grids, flexible images, and CSS media queries.

2. Client-Side Web Development

2.1 HTML (HyperText Markup Language)

HTML Document Structure


<!DOCTYPE html> <!-- Declares HTML5 document type -->

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Page Title</title>

    <!-- Metadata, CSS links, JS scripts -->

</head>

<body>

    <!-- Visible page content -->

</body>

</html>

  • <!DOCTYPE html>: Mandatory declaration; triggers standards mode in browsers.

  • <html>: Root element.

  • <head>: Contains metadata (charset, viewport), title, links to external resources.

  • <body>: Contains all visible content.

HTML Lists

List Type Tag Description Example
Ordered List <ol> Numbered or lettered sequence. <ol><li>First</li><li>Second</li></ol>
Unordered List <ul> Bulleted list. <ul><li>Item A</li><li>Item B</li></ul>
Definition List <dl> List of terms and definitions. <dl><dt>Term</dt><dd>Definition</dd></dl>
  • <li>: List item (used in <ol>, <ul>).

  • <dt>: Definition term.

  • <dd>: Definition description.

Images in HTML


<img src="image.jpg" alt="Description of image" width="300" height="200" border="1">

  • src (Source): Required. URL of the image file.

  • alt (Alternate Text): Required for accessibility. Displayed if image fails to load; read by screen readers.

  • width, height: Dimensions in pixels (prevents layout shift during load). Specify one to maintain aspect ratio.

  • border: Deprecated in HTML5. Use CSS (border: 1px solid black;).

  • Common Formats: JPEG (photos, lossy), PNG (graphics, transparency, lossless), GIF (simple animations, limited colors), SVG (vector, scalable, modern).

HTML Forms and Form Controls


<form action="process.php" method="POST">

    <label for="username">Username:</label>

    <input type="text" id="username" name="username" required>

    <label for="pwd">Password:</label>

    <input type="password" id="pwd" name="pwd" minlength="8">

    <input type="checkbox" name="hobby" value="reading"> Reading

    <input type="checkbox" name="hobby" value="sports"> Sports

    <input type="radio" name="gender" value="male"> Male

    <input type="radio" name="gender" value="female"> Female

    <select name="country" id="country">

        <option value="">Select...</option>

        <option value="in" selected>India</option>

        <option value="us">USA</option>

    </select>

    <textarea name="bio" rows="4" cols="50"></textarea>

    <input type="submit" value="Register">

    <input type="reset" value="Clear">

    <input type="hidden" name="token" value="abc123">

</form>

  • <form> Attributes:

    • action: URL of the server-side script to process the form.

    • method: GET (params in URL) or POST (params in body).

  • Input Types: text, password, checkbox, radio, submit, reset, hidden, email, number, date (HTML5).

  • Grouping:

    • Checkbox Group: Multiple selections allowed. All share the same name attribute.

    • Radio Button Group: Only one selection allowed. All share the same name attribute.

  • <select> & <option>: Dropdown list. selected attribute pre-selects an option.

  • <textarea>: Multi-line text input.

  • HTML5 Validation: required, minlength, maxlength, pattern (regex), type="email".

Frames in HTML (Deprecated in HTML5, but exam-relevant)


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

    <frame src="left.html" name="leftFrame">

    <frame src="center.html" name="mainFrame">

    <frame src="right.html" name="rightFrame">

</frameset>

  • <frameset>: Replaces the <body> tag. Defines layout using cols (vertical) or rows (horizontal).

  • <frame>: Defines individual frames within the frameset.

    • src: URL of the HTML document to load.

    • name: Target name for links (target="leftFrame").

    • frameborder: 0 (no border) or 1 (border).

  • Four Equal Parts Example:

    
    <frameset rows="50%,50%" cols="50%,50%">
    
        <frame src="page1.html">
    
        <frame src="page2.html">
    
        <frame src="page3.html">
    
        <frame src="page4.html">
    
    </frameset>
    
    

    [!WARNING] Frames cause usability/SEO issues. Use <iframe> for embedding external content instead.

Semantic HTML Elements (HTML5)

Element Purpose Example
<a> (Anchor) Hyperlink. <a href="https://example.com" target="_blank">Link</a>
href: Destination URL. target: _blank (new tab), _self (same). name: Fragment identifier (deprecated, use id).
<h1> to <h6> Headings, define document hierarchy. <h1> is most important. <h1>Main Title</h1><h2>Section</h2>

HTML vs XHTML

Feature HTML XHTML
Syntax Looser, forgiving. Strict XML syntax.
Case Sensitivity Tag/attribute names not case-sensitive. Case-sensitive (must be lowercase).
Closing Tags Optional for some elements (<p>, <li>). All elements must be closed (<br />, <img />).
Quotes Attribute values can be unquoted in some cases. Attribute values must be in quotes (" or ').
Nesting Can be improper (e.g., <p><b>text</p></b>). Must be properly nested.
DTD Has its own DTDs. Based on XML 1.0, uses DTDs to define structure.
DTD Types N/A Strict (clean), Transitional (allows presentational tags), Frameset (for frames).

HTML5 Features

  • New Semantic Elements: <article>, <section>, <nav>, <header>, <footer>, <aside>, <main>.

  • New Form Input Types: email, url, tel, number, range, date, color, search.

  • New Form Attributes: placeholder, required, autofocus, multiple, pattern.

  • Multimedia: <video> and <audio> tags with native playback support (no plugins).

  • Graphics: <canvas> (raster, scriptable) and inline SVG (vector) support.

  • APIs: Geolocation, Drag & Drop, Web Storage (localStorage, sessionStorage), Web Workers.

2.2 CSS (Cascading Style Sheets)

Introduction

Purpose: Separation of content (HTML) and presentation (CSS).

  • Benefits: Centralized style control (maintainability), consistent look & feel, improved accessibility, faster page loads (caching CSS files).

CSS Syntax & Application Methods

Syntax: selector { property: value; property: value; }

  • Selector: Targets HTML element(s) (p, .class, #id).

  • Declaration Block: { color: blue; font-size: 16px; }

Application Methods (Cascading Order - highest to lowest priority):

  1. Inline Styles: style attribute on element. Highest specificity.

    
    <p style="color: red;">Text</p>
    
    
  2. Internal/Embedded Styles: <style> block in <head>.

    
    <style>
    
        p { color: blue; }
    
    </style>
    
    
  3. External Stylesheet: Best practice. Linked via <link> in <head>.

    
    <link rel="stylesheet" href="styles.css">
    
    

Color Specification in CSS

Method Syntax Example
Color Names red, blue, darkgreen color: tomato;
Hexadecimal #RRGGBB or #RGB (shorthand) #FF0000 (red), #F00 (red)
RGB/RGBA rgb(255, 0, 0), rgba(255, 0, 0, 0.5) rgba(0,0,255,0.3) (semi-transparent blue)
HSL/HSLA hsl(120, 100%, 50%), hsla(120, 100%, 50%, 0.5) Hue (0-360°), Saturation (%), Lightness (%), Alpha (0-1).

Cascading, Specificity, and Inheritance

Cascading: When multiple rules apply to an element, the browser resolves conflicts based on:

  1. Importance: !important rule overrides others (use sparingly).

  2. Specificity: More specific selector wins.

  3. Source Order: Later rule in the same stylesheet wins if specificity is equal.

Specificity Calculation (Weight System):

Selector Type Specificity Weight Example
Inline style (style=) 1000 <p style="...">
ID selector (#id) 100 #header
Class (.class), attribute ([type="text"]), pseudo-class (:hover) 10 .active, input[type="text"]
Element (div), pseudo-element (::before) 1 p, a::after

Example: nav ul li.active a:hover has specificity: 0-0-2-3 (0 IDs, 0 classes? Wait: .active is class (10), :hover is pseudo-class (10), nav, ul, li, a are elements (1 each). So 0-0-2-4? Let's recalc: nav (1), ul (1), li (1), .active (10), a (1), :hover (10) = 1+1+1+10+1+10 = 24 (0-0-2-4). Better to show as sum.

Inheritance: Some properties (e.g., color, font-family) are inherited by default from parent to child. Non-inherited properties (e.g., border, margin, padding) must be set explicitly.

2.3 JavaScript

Client-Side vs Server-Side Scripting

Aspect Client-Side (JS) Server-Side (PHP, JSP)
Execution In the user's browser. On the web server.
Primary Use UI interactivity, form validation, dynamic content updates (AJAX). Process forms, access databases, generate dynamic HTML.
Visibility Code is visible to user (View Source). Code is hidden on server; only output (HTML) is sent.
Resources Uses client's CPU/memory. Uses server's CPU/memory.
Security Less secure (cannot protect sensitive logic). More secure (database credentials hidden).

Document Object Model (DOM)

Definition: A programming interface (API) for HTML and XML documents. It represents the page as a tree of nodes (objects) that can be manipulated with a language like JavaScript.

DOM Tree Structure:


document (Node)

├── <html> (Element)

│   ├── <head> (Element)

│   │   └── <title> (Element) → "My Page" (Text Node)

│   └── <body> (Element)

│       ├── <h1> (Element) → "Hello" (Text Node)

│       └── <p> (Element) → "World" (Text Node)

Accessing & Manipulating DOM with JavaScript:


// 1. Accessing Elements

const heading = document.getElementById('mainHeading'); // By ID

const paragraphs = document.getElementsByClassName('text'); // By Class (HTMLCollection)

const firstLink = document.querySelector('a'); // First matching CSS selector

const allButtons = document.querySelectorAll('button'); // NodeList of all matches

// 2. Changing Content

heading.textContent = 'New Title'; // Safe, no HTML parsing

heading.innerHTML = '<em>New</em> Title'; // Parses HTML (risk of XSS)

// 3. Changing Styles

heading.style.color = 'blue';

heading.style.fontSize = '24px';

// 4. Changing Structure

const newPara = document.createElement('p');

newPara.textContent = 'Added paragraph';

document.body.appendChild(newPara); // Add to end of body

const oldElement = document.getElementById('old');

oldElement.remove(); // Remove element

Form Validation with Regular Expressions


function validateEmail(email) {

    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // Simple email pattern

    return regex.test(email);

}

function validatePassword(pwd) {

    // At least 8 chars, one uppercase, one number

    const regex = /^(?=.*[A-Z])(?=.*\d).{8,}$/;

    return regex.test(pwd);

}

document.getElementById('loginForm').addEventListener('submit', function(event) {

    const email = document.getElementById('email').value;

    const pwd = document.getElementById('pwd').value;

    if (!validateEmail(email)) {

        alert('Invalid email format');

        event.preventDefault(); // Stop form submission

        return;

    }

    if (!validatePassword(pwd)) {

        alert('Password must be 8+ chars with 1 uppercase and 1 number');

        event.preventDefault();

    }

});

[!TIP] RegExp object: const pattern = new RegExp('pattern'); or literal /pattern/. Use test() for boolean check, exec() for match details.

2.4 Dynamic HTML (DHTML)

Concept: Not a single technology, but the combination of HTML, CSS, and JavaScript to create interactive, animated web pages that update dynamically without reloading the entire page.

Components:

  • HTML: Structure (DOM).

  • CSS: Presentation (styles, positioning).

  • JavaScript: Logic (manipulate DOM/CSS).

Common DHTML Techniques:

  • Show/Hide Elements: Change display (none/block) or visibility property.

  • Animations & Transitions: Use JavaScript to change CSS properties over time (setInterval, requestAnimationFrame) or CSS transitions/animations.

  • Interactive Menus: Dropdowns, flyouts that appear on mouseover/click.

  • Dynamic Content Loading: AJAX (Asynchronous JavaScript and XML) to fetch data from server and update part of the page.

3. Server-Side Web Development

3.1 PHP (Hypertext Preprocessor)

Introduction and Role

  • Server-side scripting language embedded in HTML (<?php ... ?>).

  • Process: PHP code is executed on the server; output (usually HTML) is sent to the client's browser.

  • Open-source, cross-platform. Major advantage: vast library of built-in functions.

PHP Interpreters

  1. Command Line Interface (CLI): Run PHP scripts from terminal/command prompt. For system tasks, cron jobs.

  2. Common Gateway Interface (CGI): Standalone interpreter that communicates with web server via CGI. Slower, less common.

  3. Module (Apache module / mod_php): PHP runs as an Apache module. Most common in traditional LAMP stacks. Tight integration, good performance.

PHP Variables and Naming Rules

  • Declaration: Prefix with $. $varName = value; (no need to declare type).

  • Naming Rules:

    • Starts with a letter or underscore (_).

    • Followed by any number of letters, numbers, underscores.

    • Case-sensitive ($name ≠ $Name).

    • Use camelCase or snake_case for readability.

  • Data Types:

    • Scalar: int, float (double), string, bool.

    • Compound: array, object, callable, iterable.

    • Special: resource, NULL, false.

PHP Functions

  • Built-in Functions: Thousands available (e.g., strlen(), array_merge(), date()).

  • User-Defined Functions:

    
    function add($a, $b) {
    
        $$\displaystyle sum = $$a + $b;
    
        return $sum;
    
    }
    
    $$\displaystyle result = add(5, 3); // $$result = 8
    
    
  • Variable Scope:

    • Local: Inside function; not accessible outside.

    • Global: Outside functions; use global $var; inside function to access.

    • Static: static $count = 0; inside function retains value between calls.

Object-Oriented Programming in PHP


class User {

    // Properties (attributes)

    public $name;

    private $email; // Encapsulation

    protected $id;

    // Constructor

    public function __construct($name, $email) {

        $$\displaystyle this->name = $$name;

        $$\displaystyle this->email = $$email;

    }

    // Method (behavior)

    public function getInfo() {

        return "Name: $$\displaystyle this->name, Email: $$this->email";

    }

}

// Inheritance

class Admin extends User {

    public $level = 'super';

    public function getRole() {

        return "Admin Level: $this->level";

    }

}

$user = new User("Alice", "[email protected]");

echo $user->getInfo(); // Output: Name: Alice, Email: [email protected]

  • class: Blueprint.

  • $this: Reference to current object.

  • Visibility: public (anywhere), protected (class & children), private (only class).

Database Connectivity with MySQL

MySQLi (MySQL Improved) vs PDO:

Feature MySQLi PDO (PHP Data Objects)
Database Support MySQL only. Multiple databases (MySQL, PostgreSQL, SQLite, etc.).
API Style Procedural & OOP. Pure OOP.
Prepared Statements Supported. Supported (more consistent API).
Recommendation Legacy MySQL projects. New projects (portability, modern).

Connection Example (MySQLi OOP):

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

// Create connection
$$\displaystyle conn = new mysqli( $$servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}
echo "Connected successfully";

CRUD Operations (using Prepared Statements for Security):


// 1. CREATE (Insert)
$$\displaystyle stmt = $$conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$$\displaystyle stmt->bind_param("ss", $$name, $email); // "ss" = two strings
$$\displaystyle name = "Bob"; $$email = "[email protected]";
$stmt->execute();

// 2. READ (Select)
$$\displaystyle result = $$conn->query("SELECT * FROM users WHERE id = 1");
$$\displaystyle row = $$result->fetch_assoc(); // Fetch as associative array

// 3. UPDATE
$$\displaystyle stmt = $$conn->prepare("UPDATE users SET name = ? WHERE id = ?");
$$\displaystyle stmt->bind_param("si", $$newName, $id);

// 4. DELETE
$$\displaystyle stmt = $$conn->prepare("DELETE FROM users WHERE id = ?");
$$\displaystyle stmt->bind_param("i", $$id);

Building a Login Page (Key Steps)

  1. HTML Form: action="login.php" method="POST" with username and password fields.

  2. PHP Processing (login.php):

    
    session_start(); // Start session to store login state
    
    $$\displaystyle username = $$_POST['username'];
    
    $$\displaystyle password = $$_POST['password'];
    
    // 1. Sanitize/Validate input
    
    $$\displaystyle username = filter_var( $$username, FILTER_SANITIZE_STRING);
    
    // 2. Query database (use prepared statement!)
    
    $$\displaystyle stmt = $$conn->prepare("SELECT id, password_hash FROM users WHERE username = ?");
    
    $$\displaystyle stmt->bind_param("s", $$username);
    
    $stmt->execute();
    
    $$\displaystyle result = $$stmt->get_result();
    
    $$\displaystyle user = $$result->fetch_assoc();
    
    // 3. Verify password (password_verify() if using password_hash())
    
    if ($$\displaystyle user && password_verify( $$password, $user['password_hash'])) {
    
        // 4. Set session variables
    
        $$\displaystyle _SESSION['user_id'] = $$user['id'];
    
        $$\displaystyle _SESSION['username'] = $$username;
    
        header("Location: dashboard.php"); // Redirect
    
        exit();
    
    } else {
    
        echo "Invalid credentials";
    
    }
    
    
  3. Protect Pages: On dashboard.php, check if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }.

3.2 JSP (JavaServer Pages)

Introduction to JSP

  • Java-based server-side technology for creating dynamic web content.

  • Lifecycle: JSP file (.jsp) is translated into a Servlet (_jspService() method), then compiled and executed on the server.

  • Scripting Elements (use sparingly, prefer JSTL/EL):

    • <% ... %> Scriptlet (Java code).

    • <%= ... %> Expression (outputs value).

    • <%! ... %> Declaration (class-level members).

Using JavaBeans in JSP

JavaBean: A reusable Java class with:

  • No-arg constructor.

  • Private properties with public getXxx()/setXxx() methods.

  • Implements Serializable.

JSP Tags:


<jsp:useBean id="user" class="com.example.User" scope="session" />

<jsp:setProperty name="user" property="*" /> <!-- Populates from request params -->

<jsp:setProperty name="user" property="name" value="Alice" />

<jsp:getProperty name="user" property="name" />

  • <jsp:useBean>: Instantiates or retrieves bean from specified scope (page, request, session, application).

  • <jsp:setProperty>: Sets bean properties.

  • <jsp:getProperty>: Gets and prints property value.

Session Tracking with Cookies in JSP


// In a JSP or Servlet

// 1. Create Cookie

Cookie userCookie = new Cookie("username", "Alice");

userCookie.setMaxAge(60 * 60 * 24); // 1 day in seconds

userCookie.setPath("/"); // Available to entire app

response.addCookie(userCookie); // Send to client

// 2. Read Cookie

Cookie[] cookies = request.getCookies();

if (cookies != null) {

    for (Cookie c : cookies) {

        if (c.getName().equals("username")) {

            String username = c.getValue();

        }

    }

}
  • Cookies: Small text files stored on client's browser. Limited size (~4KB). Can be disabled by user.

  • Session Tracking: Cookies can store a session ID (JSESSIONID in JSP). Server uses this ID to retrieve session data stored on server (more secure, unlimited storage).

3.3 XML (eXtensible Markup Language)

Purpose and Advantages

  • Purpose: Platform-independent, self-descriptive data storage and exchange format.

  • Advantages:

    • Separates content from presentation (unlike HTML).

    • Extensible: Users define their own tags.

    • Text-based: Human-readable, software-independent.

    • Unicode support: International character sets.

    • Foundation for many technologies (SVG, XHTML, SOAP, RSS).

XML Document Structure


<?xml version="1.0" encoding="UTF-8"?> <!-- Prolog (optional but recommended) -->

<note> <!-- Root Element (one per document) -->

    <to>Alice</to>

    <from>Bob</from>

    <heading>Reminder</heading>

    <body>Don't forget the meeting!</body>

    <metadata author="Bob" date="2023-10-01"/> <!-- Element with attributes -->

</note>

  • Prolog: <?xml ...?> declaration. Optional but good practice.

  • Root Element: Single element that contains all other elements.

  • Elements: <to>, <from>, etc. Can contain text, other elements, or be empty (<empty/>).

  • Attributes: Name-value pairs inside start tag (author="Bob"). Prefer elements for complex data.

  • Well-Formedness Rules (MANDATORY):

    1. Exactly one root element.

    2. All tags properly nested and closed (<a><b></b></a>, not <a><b></a></b>).

    3. Case-sensitive (<Note> ≠ <note>).

    4. Attribute values in quotes (" or ').

    5. Special characters (<, >, &, ', ") must be escaped (&lt;, &gt;, &amp;, &apos;, &quot;).

  • Validity: Document is valid if it conforms to a DTD or XML Schema (XSD).

Document Type Definition (DTD)

  • Purpose: Defines the legal structure (elements, attributes, order) of an XML document.

  • Internal DTD: Inside XML prolog.

    
    <!DOCTYPE note [
    
        <!ELEMENT note (to, from, heading, body)>
    
        <!ELEMENT to (#PCDATA)>
    
        <!ELEMENT from (#PCDATA)>
    
        <!ELEMENT heading (#PCDATA)>
    
        <!ELEMENT body (#PCDATA)>
    
    ]>
    
    
  • External DTD: Separate .dtd file referenced as <!DOCTYPE note SYSTEM "note.dtd">.

  • Limitations: No data types (everything is string), limited constraints, no namespace support.

XML Schema (XSD)

  • Purpose: More powerful, XML-based alternative to DTD for defining structure and data types.

  • Advantages over DTD:

    • Rich Data Types: xs:string, xs:integer, xs:date, xs:boolean, etc.

    • Uses XML Syntax: Easier to learn/modify.

    • Supports Namespaces: Crucial for combining schemas.

    • More Constraints: minOccurs, maxOccurs, pattern restrictions.

  • Basic Structure:

    
    <?xml version="1.0"?>
    
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    
        <xs:element name="note">
    
            <xs:complexType>
    
                <xs:sequence>
    
                    <xs:element name="to" type="xs:string"/>
    
                    <xs:element name="from" type="xs:string"/>
    
                    <xs:element name="heading" type="xs:string"/>
    
                    <xs:element name="body" type="xs:string"/>
    
                </xs:sequence>
    
            </xs:complexType>
    
        </xs:element>
    
    </xs:schema>
    
    

XML Parsing Techniques

Parser Model Memory Speed Use Case
DOM (Document Object Model) Loads entire XML into memory as a tree of nodes. High (entire doc in memory). Slower for large files. Need random access and modification of document.
SAX (Simple API for XML) Event-driven, sequential parsing. Calls methods (startElement, characters, endElement) as it reads. Low (streaming). Fast, memory-efficient. Large files, read-only processing, filtering.

Example SAX in Java:


SAXParserFactory factory = SAXParserFactory.newInstance();

SAXParser saxParser = factory.newSAXParser();

DefaultHandler handler = new DefaultHandler() {

    public void startElement(String uri, String localName, String qName, Attributes attributes) {

        System.out.println("Start: " + qName);

    }

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

        System.out.println("Text: " + new String(ch, start, length));

    }

};

saxParser.parse("file.xml", handler);

XML Naming Rules

  • Can contain letters, numbers, hyphens (-), underscores (_), periods (.).

  • Cannot start with a number, hyphen, or period.

  • Cannot contain spaces.

  • Case-sensitive.

  • Avoid colon (:) for custom names (reserved for namespaces).

  • Examples: <first-name>, <_price>, <book_title> are valid. <1st-place>, <my tag> are invalid.

4. Data Management & Interoperability

XML Schema vs DTD – Detailed Comparison

Feature DTD XML Schema (XSD)
Syntax Non-XML, custom syntax. XML-based (uses XML tags).
Data Types None (all text). Rich built-in & custom data types (integer, date, pattern).
Namespaces Not supported. Full namespace support (essential for complex docs).
Constraints Basic (#PCDATA, ?, *, +). Advanced (minOccurs, maxOccurs, pattern, enumeration).
Extensibility Limited. Supports extension and restriction of types.
Learning Curve Simpler for basic structures. More complex but more powerful.
Validation Validates structure only. Validates structure + data content.

PHP-MySQL Integration Best Practices

  1. Use Prepared Statements (Parameterized Queries): MOST IMPORTANT to prevent SQL Injection.

    
    $$\displaystyle stmt = $$conn->prepare("SELECT * FROM users WHERE email = ?");
    
    $$\displaystyle stmt->bind_param("s", $$email); // "s" = string type
    
    
  2. Validate & Sanitize Input: Use filter_var(), htmlspecialchars() for output.

  3. Use MySQLi or PDO: Both support prepared statements. Avoid mysql_* functions (deprecated).

  4. Error Handling: Use try-catch (PDO) or check $stmt->error. Never display raw DB errors to users. Log them.

  5. Close Resources: $$\displaystyle stmt->close(); $$conn->close();.

  6. Use HTTPS: Encrypt data in transit.

Cookies and Session Management

Aspect Cookies Sessions
Storage Location Client's browser (text file). Server's memory/file/database (only session ID stored on client).
Storage Limit ~4KB per cookie, limited cookies per domain. Much larger (server resources limit).
Security Less secure (user can view/edit, susceptible to theft (XSS)). More secure (data stays on server). Use HTTPS to protect session ID cookie.
Lifetime Can be persistent (set expires) or session-only (deleted on browser close). Typically ends when browser closes (session cookie) or after server-defined timeout.
Purpose Tracking (analytics, preferences), personalization, storing non-sensitive data. Authentication state, shopping cart, user-specific data.
PHP Functions setcookie(name, value, expire, path, domain, secure, httponly)<br>$$\displaystyle _COOKIE` superglobal. | `session_start()`<br>` $$_SESSION superglobal.

Session Tracking in JSP using Cookies:


// On login success:

HttpSession session = request.getSession(); // Creates or retrieves session

session.setAttribute("user", userObject); // Store object in session

// JSP automatically sends JSESSIONID cookie.

// On subsequent requests, container uses JSESSIONID cookie to retrieve session.

5. Web 2.0 and Advanced Topics

Web 2.0 Design Principles

  1. Rich User Experience: AJAX for seamless updates, intuitive drag-and-drop, real-time feedback.

  2. User as Contributor: Platforms enabling user-generated content (blogs, wikis, social media, reviews).

  3. Collaboration & Social Networking: Sharing, commenting, tagging, community building (Facebook, Twitter).

  4. Long Tail: Serving niche markets efficiently via digital distribution (Netflix, Amazon).

  5. Mashups: Combining data/services from multiple sources via APIs (e.g., Housing maps with crime data).

  6. Simplicity & Minimalism: Clean interfaces, focus on core functionality.

  7. Trust & Transparency: User reviews, ratings, open APIs.

Page Layout and Linking Strategies

  • Navigation Design:

    • Global Navigation: Consistent across site (top menu, sidebar).

    • Local Navigation: Context-specific (sub-menu).

    • Breadcrumbs: Show path (Home > Products > Laptops).

    • Footer Links: Legal, contact, sitemap.

  • Responsive & Adaptive Layouts:

    • Responsive: Single fluid layout that adapts to screen size using CSS media queries and flexible units (%, vw, vh, rem).

    • Adaptive: Multiple fixed layouts for specific breakpoints (server-side or client-side detection).

  • Linking Best Practices:

    • Internal Links: Use descriptive anchor text (<a href="/products">View our Products</a>). Avoid "click here".

    • External Links: Open in new tab (target="_blank" with rel="noopener noreferrer" for security).

    • Link Validation: Regularly check for broken links (404 errors).

    • SEO: Use meaningful href paths, title attributes, logical site hierarchy.


Integrated Short Note Topics (From Past Papers)

Advantages of PHP

  • Open-source & Free: No licensing cost.

  • Cross-platform: Runs on Windows, Linux, macOS.

  • Easy to Learn: Syntax similar to C/Java, embedded in HTML.

  • Huge Community & Documentation: Extensive resources, frameworks (Laravel, Symfony).

  • Large Built-in Function Library: For strings, arrays, dates, files, databases.

  • Fast Execution: Especially with OPcache.

  • Good Database Support: Native drivers for MySQL, PostgreSQL, etc.

  • Supports Major Web Servers: Apache, IIS, Nginx.

Functions in PHP

  • Definition: Reusable block of code that performs a specific task.

  • Built-in: strlen(), array_push(), date(), mysqli_connect().

  • User-Defined:

    
    function functionName($param1, $param2 = "default") {
    
        // Code
    
        return $result; // Optional
    
    }
    
    
  • Variable Scope: global keyword to access global variables inside function. static variables retain value between calls.

  • Pass by Value vs by Reference: By default, pass by value (copy). Use & to pass by reference (function add(&$a)).

Naming Rules in XML

  • Can contain letters, numbers, hyphens (-), underscores (_), periods (.).

  • Cannot start with a number, hyphen, or period.

  • Cannot contain spaces.

  • Case-sensitive.

  • Avoid colon (:) except for namespaces.

Features of XHTML

  • Strict XML Syntax: All tags must be closed (<br />, <img />), properly nested, attributes in quotes.

  • Case Sensitivity: All tags and attributes must be lowercase.

  • Well-Formedness Mandatory: Browser will not render malformed XHTML.

  • DTD Based: Requires a valid Document Type Definition (Strict, Transitional, Frameset).

  • Better Compatibility: Designed for future XML tools and stricter parsers.

  • Deprecated Presentational Elements: <font>, <center> removed in Strict DTD; use CSS instead.

Purpose of Cookies

  • Session Management: Track user login state (store session ID).

  • Personalization: Store user preferences (theme, language).

  • Tracking & Analytics: Track user behavior across pages/sessions (Google Analytics).

  • Shopping Carts: Store cart items between visits (though server-side session is better for security).

  • Remember Me: Auto-fill login credentials (store token, not password).

  • Security Note: Never store sensitive data (passwords, credit card numbers) in plain text cookies. Use HttpOnly and Secure flags.

Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in