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

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

UNIT 5: Internet and Web Technology


I. Web Fundamentals

A. Internet vs World Wide Web (WWW)

  • Internet: A global network of interconnected computer networks using standardized protocols (like TCP/IP) to exchange data.

  • World Wide Web (WWW): An information-sharing model built on top of the Internet. It uses the HTTP protocol to access interlinked hypertext documents (web pages) hosted on web servers.

  • Relationship: The Internet is the infrastructure (roads), while the Web is a service that runs on it (mail delivery system).

[!TIP] Exam Focus: A very common 7-mark question. Clearly distinguish the two with the "infrastructure vs. service" analogy.

B. Web 2.0: Design Principles and Key Features

  • Design Philosophy: Shift from static, read-only content to dynamic, user-participatory platforms.

  • Key Features:

    • User-Generated Content: Wikis, blogs, social media.

    • Rich User Experience: AJAX for asynchronous updates (no full page reload).

    • Social Networking & Collaboration: APIs for mashups, tagging,folksonomies.

    • Scalability & Long Tail: Serving niche audiences cost-effectively.

C. HTTP Protocol (HyperText Transfer Protocol)

  • Primary Function: Application-layer protocol for fetching resources (HTML, images, etc.) on the Web.

  • Request-Response Model:

    1. Client (Browser) → Server: Sends an HTTP Request (method, URL, headers).

    2. Server → Client: Sends an HTTP Response (status code, headers, message body).

  • Common Methods:

    | Method | Purpose | Idempotent? | | :--- | :--- | :--- | | GET | Retrieve data from server. Parameters in URL. | Yes | | POST | Submit data to server (e.g., form). Parameters in body. | No | | PUT | Update a resource. | Yes | | DELETE | Remove a resource. | Yes |

  • Status Codes (First digit indicates class):

    • 1xx (Informational): 100 Continue

    • 2xx (Success): \boxed{200 OK}, 201 Created

    • 3xx (Redirection): 301 Moved Permanently, 304 Not Modified

    • 4xx (Client Error): \boxed{404 Not Found}, 403 Forbidden

    • 5xx (Server Error): 500 Internal Server Error

[!TIP] Common Pitfall: GET is for safe, read-only operations; POST is for actions that change state. GET parameters are visible in the URL.

D. Web Publishing Process

  1. Planning: Define purpose, audience, content structure.

  2. Design: Create wireframes, mockups; choose color schemes, layout.

  3. Development: Write HTML/CSS/JavaScript code; create assets (images).

  4. Testing: Check browser compatibility, validate code (W3C), test links/forms.

  5. Deployment: Upload files to a web server via FTP/SSH; configure domain/DNS.

  6. Maintenance: Update content, monitor traffic, fix bugs.

E. Web Browsers and Web Servers

Component Role Key Function
Web Browser (Client) Interpreter & Renderer Requests pages via HTTP, parses HTML/CSS/JS, renders the visual page.
Web Server Resource Host & Responder Listens for HTTP requests, locates requested files (or executes scripts like PHP), sends back HTTP responses.

Interaction: Browser sends GET /index.html HTTP/1.1 → Server finds index.html → Server responds with HTTP/1.1 200 OK + HTML content → Browser renders it.

F. Web Design Issues

Issue Challenge Mitigation Strategies
Browser Compatibility Different browsers (Chrome, Firefox, IE) render HTML/CSS/JS differently. Use web standards (W3C), CSS resets, progressive enhancement, cross-browser testing.
Bandwidth Constraints Slow connections lead to poor user experience. Optimize images (compress, use sprites), minify CSS/JS, use lazy loading.
Caching Mechanisms Browsers cache static resources to reduce load times and server requests. Set appropriate Cache-Control headers, use versioned filenames for assets (style.v2.css).
Display Resolution Variations Varying screen sizes (desktop, tablet, mobile). Responsive Web Design using fluid grids, flexible images, CSS media queries.

II. HTML (HyperText Markup Language)

A. Document Structure


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

<html> <!-- Root element -->

<head>

    <meta charset="UTF-8">

    <title>Page Title</title>

    <!-- Metadata, CSS links, scripts go here -->

</head>

<body>

    <!-- Visible page content goes here -->

</body>

</html>

B. Lists

  1. Ordered List (<ol>): Numbered items.

    
    <ol type="1" start="3">
    
        <li>First item</li>
    
        <li>Second item</li>
    
    </ol>
    
    
  2. Unordered List (<ul>): Bulleted items.

    
    <ul type="disc">
    
        <li>Apples</li>
    
        <li>Oranges</li>
    
    </ul>
    
    
  3. Definition List (<dl>): Terms and descriptions.

    
    <dl>
    
        <dt>HTML</dt>
    
        <dd>HyperText Markup Language</dd>
    
        <dt>CSS</dt>
    
        <dd>Cascading Style Sheets</dd>
    
    </dl>
    
    

C. Images

  • Tag: <img>

  • Key Attributes:

    • src="url": Required. Path to image file.

    • alt="text": Required. Alternative text for accessibility/SEO.

    • width="px/%", height="px/%": Dimensions (specify one to maintain aspect ratio).

    
    <img src="logo.png" alt="Company Logo" width="200">
    
    

D. Forms and Form Controls

  • <form> Element: Container for all controls.

    • action="url": URL of server-side script to process data.

    • method="GET|POST": HTTP method for submission.

  • Input Types (<input>):

    • type="text": Single-line text.

    • type="password": Masked text.

    • type="checkbox": Multiple selections allowed.

    • type="radio": Single selection from a group (same name attribute).

    • type="submit": Sends form data.

    • type="reset": Clears form fields.

  • Grouping:

    • Checkboxes: Independent; multiple can be selected. name can be same or different.

    • Radio Buttons: Mutually exclusive within a group; must share the same name.

  • Other Controls:

    • <textarea rows="" cols="">: Multi-line text.

    • <select>: Dropdown list.

      
      <select name="city">
      
          <option value="delhi">Delhi</option>
      
          <option value="mumbai" selected>Mumbai</option>
      
      </select>
      
      
  • Form Control Tags (Short Note): Tags that allow user input: <input>, <select>, <textarea>, <button>.

[!TIP] Exam Focus: "Difference between checkbox and radio groups" and "form attributes (action, method)" are frequent short notes.

E. Frames

  • Purpose: Divide browser window into multiple independent scrolling regions.

  • <frameset> & <frame>:

    
    <frameset rows="25%,50%,25%"> <!-- Divide vertically -->
    
        <frame src="header.html" name="top">
    
        <frame src="content.html" name="main">
    
        <frame src="footer.html" name="bottom">
    
    </frameset>
    
    
    • rows/cols: Specify sizes (pixels, %, or * for remaining space).

    • src: URL of the HTML document to load in the frame.

  • Four Equal Parts:

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

[!WARNING] Frames are obsolete in HTML5. Use <iframe> for embedding external content or CSS Grid/Flexbox for layout.

F. Text Formatting

  • Anchors (<a>):

    
    <a href="https://www.example.com" target="_blank">Link Text</a>
    
    <!-- href: destination URL. target="_blank" opens in new tab. -->
    
    
  • Headings (<h1> to <h6>): Define hierarchical section headings. <h1> is most important.

G. HTML vs XHTML

Feature HTML (4/5) XHTML (1.0/1.1)
Syntax Looser, forgiving. Strict XML syntax.
Case Sensitivity Tags/attributes case-insensitive. Case-sensitive (must be lowercase).
Closing Tags Optional for some elements (e.g., <p>). Required for all elements (e.g., <br />).
Attribute Quotes Optional (but recommended). Required (double or single quotes).
Nesting Some elements can be improperly nested. Must be properly nested.
Document Type <!DOCTYPE html> (HTML5). <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ...>

H. HTML5 New Features (Short Note)

  • Semantic Elements: <header>, <footer>, <nav>, <article>, <section> for better structure/SEO.

  • Multimedia: Native <audio> and <video> tags (no plugins needed).

  • Graphics: <canvas> for dynamic 2D/3D drawing; <svg> for scalable vector graphics.

  • Form Enhancements: New input types (email, date, range), placeholder, required attribute.

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

I. Page Layout and Linking (Short Note)

  • Page Layout: Structuring a webpage using semantic HTML5 tags (<div> with id/class, <header>, <main>, <aside>, <footer>) and CSS for positioning (Flexbox, Grid).

  • Linking:

    • Internal Links: Anchor to a section on same page (<a href="#section1">).

    • External Links: Link to another page/website (<a href="page.html"> or <a href="https://...">).

    • Email Links: mailto: protocol (<a href="mailto:[email protected]">).


III. Cascading Style Sheets (CSS)

A. Introduction

  • Purpose: Language used to describe the presentation (layout, colors, fonts) of a document written in HTML or XML.

  • Core Principle: Separation of Content and Presentation. HTML defines structure/content; CSS defines style.

B. Including CSS

  1. Inline Styles: Directly in an element's style attribute.

    
    <p style="color: blue; font-size: 14px;">Text</p>
    
    
    • Highest specificity, least reusable.
  2. Internal Stylesheet: Inside <style> tags in the <head>.

    
    <head>
    
        <style>
    
            p { color: red; }
    
        </style>
    
    </head>
    
    
    • Applies to the whole document.
  3. External Stylesheet: Linked via <link> tag in <head>.

    
    <head>
    
        <link rel="stylesheet" href="styles.css">
    
    </head>
    
    
    • Best practice: reusable across multiple pages.

C. Color Specification

Method Syntax Example
Color Names color: red; lightblue, darkgreen (140+ standard names).
Hexadecimal color: #RRGGBB; #FF0000 (Red), #00FF00 (Green), #0000FF (Blue).
RGB color: rgb(R, G, B); rgb(255, 0, 0). Values 0-255 or percentages.
HSL color: hsl(H, S%, L%); hsl(120, 100%, 50%) (Pure green). Hue (0-360°), Saturation/Lightness (0-100%).

D. CSS Properties for Presentation Enhancement

  • Fonts: font-family, font-size, font-weight, font-style.

  • Text: color, text-align, text-decoration, line-height.

  • Box Model:

    • margin: Space outside border.

    • border: Line surrounding padding/content.

    • padding: Space between border and content.

  • Background: background-color, background-image, background-repeat.

  • Layout: display (block, inline, flex, grid), position (static, relative, absolute, fixed).


IV. JavaScript

A. Client-Side vs Server-Side Scripting

Aspect Client-Side (JavaScript) Server-Side (PHP, JSP)
Execution Location User's web browser. Web server.
Primary Use UI interactivity, form validation, dynamic page updates (DHTML). Dynamic content generation, database access, business logic.
Security Code is visible to user (view source). Code is hidden on server; only output is sent.
Access Limited to user's browser/resources. Full access to server resources (file system, DB).

B. Document Object Model (DOM)

  • Tree Structure: HTML document represented as a hierarchical tree of nodes (elements, attributes, text).

    
    Document
    
    ├── html
    
    │   ├── head
    
    │   │   └── title
    
    │   └── body
    
    │       ├── h1
    
    │       └── p
    
    
  • Accessing Elements:

    
    document.getElementById("myId"); // By ID
    
    document.getElementsByClassName("myClass"); // By class (HTMLCollection)
    
    document.getElementsByTagName("p"); // By tag name (HTMLCollection)
    
    document.querySelector(".myClass"); // First match CSS selector
    
    document.querySelectorAll("div > p"); // All matches (NodeList)
    
    
  • Modifying Elements:

    
    element.innerHTML = "<b>New content</b>"; // Change HTML inside
    
    element.textContent = "Plain text"; // Change text only
    
    element.setAttribute("class", "newClass"); // Change attribute
    
    element.style.color = "red"; // Change inline style
    
    
  • Events & Event Handling: React to user actions (click, load, submit).

    
    // Method 1: HTML attribute (not recommended)
    
    <button onclick="myFunction()">Click</button>
    
    // Method 2: DOM property
    
    document.getElementById("btn").onclick = function() { ... };
    
    // Method 3: addEventListener (best practice)
    
    element.addEventListener("click", function(event) { ... });
    
    

C. Form Validation with Regular Expressions

  • Regular Expressions (Regex): Patterns for matching character combinations in strings.

    • ^ : Start of string.

    • $ : End of string.

    • \d : Digit (0-9).

    • \w : Alphanumeric/underscore.

    • [a-zA-Z] : Range of characters.

    • + : One or more.

    • * : Zero or more.

    • {n} : Exactly n times.

  • Login Form Validation Example:

    
    function validateLogin() {
    
        let email = document.getElementById("email").value;
    
        let password = document.getElementById("password").value;
    
        let emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    
        let passRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/; // Min 8 chars, 1 letter, 1 number
    
        if (!emailRegex.test(email)) {
    
            alert("Invalid email format.");
    
            return false;
    
        }
    
        if (!passRegex.test(password)) {
    
            alert("Password must be min 8 chars with letter and number.");
    
            return false;
    
        }
    
        return true; // Allows form submission
    
    }
    
    // In HTML: <form onsubmit="return validateLogin()">
    
    

D. Dynamic HTML (DHTML) - Short Note

  • Definition: Combination of HTML, CSS, and JavaScript to create interactive, animated web pages without server reloads.

  • Key Techniques:

    • DOM Manipulation: Changing content, style, structure dynamically.

    • CSS Positioning: Using position: absolute/relative for movable elements.

    • Event Handling: Responding to mouse/keyboard events.

    • JavaScript Timers: setTimeout(), setInterval() for animations.

  • Example: Dropdown menus, image sliders, drag-and-drop interfaces.


V. XML (eXtensible Markup Language)

A. Purpose

  • Data Storage & Configuration: Store structured data (e.g., application settings, documents).

  • Data Exchange: Platform-independent format for sharing data between systems (web services, APIs).

  • Not for Display: Unlike HTML, XML focuses on what data is, not how it looks.

B. Syntax Rules

  • Elements: <book>...</book> (must have closing tag or be self-closing <br/>).

  • Attributes: <book id="101"> (name="value" in quotes).

  • Nesting: Elements must be properly nested (no overlapping).

    
    <!-- Correct -->
    
    <b><i>Text</i></b>
    
    <!-- Wrong -->
    
    <b><i>Text</b></i>
    
    
  • Well-Formedness: An XML document must follow all syntax rules (single root element, proper nesting, quoted attributes, case-sensitive).

C. Document Type Definition (DTD) - Short Note

  • Purpose: Defines the legal structure, elements, and attributes of an XML document. Used for validation.

  • Types:

    • Internal DTD: Declared within the XML file (<!DOCTYPE ... [ ... ]>).

    • External DTD: In a separate .dtd file, referenced (<!DOCTYPE root SYSTEM "file.dtd">).

  • Element Declaration: <!ELEMENT element-name (child1, child2?)> (, = sequence, | = choice, ? = optional, * = zero or more, + = one or more).

  • Limitation: DTDs support only basic data types (string, ID, IDREF). No support for namespaces or complex data types.

D. XML Schema (XSD)

  • Structure & Components:

    • Written in XML itself.

    • Defines elements, attributes, data types (xs:string, xs:integer, xs:date), complex types (elements with children/attributes), simple types (restrictions like xs:integer with minInclusive).

    • Supports namespaces (xs: prefix for schema elements).

  • Advantages over DTD:

    | Feature | DTD | XML Schema | | :--- | :--- | :--- | | Data Types | Limited (string, ID). | Rich (numeric, date, boolean, custom). | | Namespaces | Poor support. | Full support. | | Validation | Basic structure. | Complex constraints (key/keyref, uniqueness). | | Syntax | Non-XML syntax. | XML-based (easier to parse/process). |

E. Parsing XML

  • DOM Parser (Tree-based):

    • Loads entire XML document into memory, builds a tree structure.

    • Pros: Easy navigation/modification (random access).

    • Cons: Memory-intensive for large files.

    • Example (JavaScript - Browser):

      
      let parser = new DOMParser();
      
      let xmlDoc = parser.parseFromString(xmlString, "text/xml");
      
      let title = xmlDoc.getElementsByTagName("title")[0].textContent;
      
      
  • SAX Parser (Event-driven, Streaming):

    • Reads XML sequentially, fires events (startElement, characters, endElement).

    • Pros: Low memory footprint, fast for large files.

    • Cons: No random access; state must be managed manually.

    • Example (Java):

      
      SAXParserFactory factory = SAXParserFactory.newInstance();
      
      SAXParser saxParser = factory.newSAXParser();
      
      saxParser.parse(new File("file.xml"), new DefaultHandler() {
      
          public void startElement(String uri, String localName, String qName, Attributes attributes) {
      
              // Handle start of element
      
          }
      
          public void characters(char ch[], int start, int length) {
      
              // Handle text content
      
          }
      
      });
      
      
    • Python (using xml.sax): Similar event-handler pattern.


VI. PHP (Hypertext Preprocessor)

A. Role in Web Development

  • Server-Side Scripting Language: Code executes on the web server.

  • Primary Use: Generate dynamic HTML content, interact with databases, handle form data, manage sessions/cookies.

  • Workflow: Client requests .php file → Server executes PHP code → Server sends resulting HTML to client.

B. Basics

  • Variable Declaration: Starts with $ (dollar sign). Case-sensitive ($name ≠ $Name).

    
    $name = "Alice"; // String
    
    $age = 25;       // Integer
    
    $price = 19.99;  // Float
    
    $isValid = true; // Boolean
    
    
  • Data Types:

    • Scalar: integer, float (double), string, boolean.

    • Compound: array (indexed/associative), object.

    • Special: NULL, resource.

  • Types of PHP Interpreters:

    • CGI: Standalone process per request (slower, high overhead).

    • Module (e.g., mod_php for Apache): Integrated into web server (faster, common).

    • FastCGI: Persistent process pool (better performance than CGI, works with multiple servers).

C. Functions

  • Built-in Functions: Pre-defined (e.g., strlen($$\displaystyle str)`, `array_merge( $$a,$b), date()).

  • User-Defined Functions:

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

D. Object-Oriented Programming (OOP)

  • Class: Blueprint for objects.

    
    class User {
    
        // Properties (variables)
    
        public $name;
    
        private $email;
    
        // Method (function)
    
        public function setEmail($email) {
    
            $$\displaystyle this->email = $$email; // $this refers to current object
    
        }
    
    }
    
    
  • Object: Instance of a class.

    
    $user1 = new User();
    
    $user1->name = "Bob";
    
    $user1->setEmail("[email protected]");
    
    
  • Inheritance: class Admin extends User { ... } (Admin inherits User's properties/methods).

  • Encapsulation: Controlling access via public, private, protected.

E. String Manipulation Examples

  • strlen($str): Returns string length.

  • substr($str, start, length): Extracts part of a string.

    
    $text = "Hello World";
    
    echo substr($text, 6, 5); // Output: "World"
    
    
  • strpos($str, search): Finds position of first occurrence.

  • strtolower(), strtoupper(), trim().

F. Form Handling

  • Accessing Form Data:

    • $_GET['fieldname']: Data from URL query string (method="GET").

    • $_POST['fieldname']: Data from request body (method="POST").

  • Login Page Example:

    
    <!-- login.html -->
    
    <form action="login.php" method="POST">
    
        Username: <input type="text" name="username"><br>
    
        Password: <input type="password" name="password"><br>
    
        <input type="submit">
    
    </form>
    
    
    
    <?php // login.php
    
    $$\displaystyle user = $$_POST['username'];
    
    $$\displaystyle pass = $$_POST['password'];
    
    // Validate against database (see section H)
    
    if ($$\displaystyle user == "admin" && $$pass == "12345") {
    
        echo "Login successful!";
    
    } else {
    
        echo "Invalid credentials.";
    
    }
    
    ?>
    
    
  • Simple Calculator:

    
    <?php
    
    $result = "";
    
    if (isset($$\displaystyle _POST['num1']) && isset( $$_POST['num2']) && isset($_POST['op'])) {
    
        $$\displaystyle n1 = $$_POST['num1'];
    
        $$\displaystyle n2 = $$_POST['num2'];
    
        $$\displaystyle op = $$_POST['op'];
    
        switch($op) {
    
            case '+': $$\displaystyle result = $$n1 + $n2; break;
    
            case '-': $$\displaystyle result = $$n1 - $n2; break;
    
            case '*': $$\displaystyle result = $$n1 * $n2; break;
    
            case '/': $$\displaystyle result = ( $$n2 != 0) ? $n1/$n2 : "Error"; break;
    
        }
    
    }
    
    ?>
    
    <form method="POST">
    
        <input type="number" name="num1" required>
    
        <select name="op">
    
            <option>+</option><option>-</option><option>*</option><option>/</option>
    
        </select>
    
        <input type="number" name="num2" required>
    
        <input type="submit" value="Calculate">
    
    </form>
    
    Result: <?php echo $result; ?>
    
    

G. Database Connectivity with MySQL

  • MySQLi (MySQL Improved):

    • Procedural: mysqli_connect($host, $user, $pass, $db), mysqli_query($conn, $sql).

    • Object-Oriented: $$\displaystyle conn = new mysqli(...)`, ` $$conn->query($sql).

  • PDO (PHP Data Objects):

    • Database-agnostic (works with MySQL, PostgreSQL, SQLite).

    • Uses prepared statements (prevents SQL injection).

    
    // PDO Connection
    
    try {
    
        $pdo = new PDO("mysql:host=localhost;dbname=test", "user", "pass");
    
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    } catch(PDOException $e) {
    
        echo "Connection failed: " . $e->getMessage();
    
    }
    
    

H. MySQL Operations

  • Creating Database: CREATE DATABASE dbname;

  • Selecting Database: USE dbname; or in connection string.

  • Deleting Database: DROP DATABASE dbname;

  • Table Operations:

    • INSERT INTO table (col1, col2) VALUES ('val1', 'val2');

    • SELECT * FROM table WHERE condition;

    • DELETE FROM table WHERE condition;

  • Adding User to Login Table Example (using MySQLi procedural):

    
    <?php
    
    $conn = mysqli_connect("localhost", "root", "", "mydb");
    
    if (!$conn) die("Connection failed: " . mysqli_connect_error());
    
    $username = "john";
    
    $password = password_hash("mypass", PASSWORD_DEFAULT); // Always hash passwords!
    
    $$\displaystyle sql = "INSERT INTO users (username, password) VALUES (' $$username', '$password')";
    
    if (mysqli_query($conn, $sql)) {
    
        echo "User added successfully.";
    
    } else {
    
        echo "Error: " . $$\displaystyle sql . "<br>" . mysqli_error( $$conn);
    
    }
    
    mysqli_close($conn);
    
    ?>
    
    

    [!WARNING] Security: Use prepared statements (mysqli_prepare) to prevent SQL injection. Never store plain-text passwords; use password_hash() and password_verify().

I. Cookies

  • Purpose: Small text files stored on client's browser for state management (e.g., remembering login, shopping cart, user preferences) across sessions. HTTP is stateless.

  • Setting Cookie: setcookie(name, value, expire, path, domain, secure, httponly);

    
    setcookie("user", "Alice", time() + 3600, "/"); // Expires in 1 hour
    
    
  • Retrieving Cookie: $_COOKIE['user'];

  • Session Tracking Alternative: $_SESSION (data stored on server, only session ID in cookie).

J. Advantages of PHP (Short Note)

  • Open Source & Free: No licensing cost.

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

  • Easy to Learn & Deploy: C-like syntax, embedded in HTML.

  • Large Community & Extensive Libraries: Huge ecosystem (Laravel, WordPress).

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

  • Fast Execution (especially with OPcache).


VII. Java Server Pages (JSP)

A. JavaBeans

  • Purpose: Reusable, platform-independent software components that encapsulate data (properties) and behavior (methods). Follows conventions: private properties, public getter/setter methods.

  • Creating a Bean:

    
    // UserBean.java
    
    public class UserBean {
    
        private String username;
    
        private int age;
    
        public String getUsername() { return username; }
    
        public void setUsername(String username) { this.username = username; }
    
        public int getAge() { return age; }
    
        public void setAge(int age) { this.age = age; }
    
    }
    
    
  • Using in JSP:

    
    <%@ page import="com.example.UserBean" %>
    
    <!-- 1. Instantiate or find bean in scope -->
    
    <jsp:useBean id="user" class="com.example.UserBean" scope="session" />
    
    <!-- 2. Set properties (from request parameters) -->
    
    <jsp:setProperty name="user" property="*" /> <!-- Sets all matching params -->
    
    <!-- or -->
    
    <jsp:setProperty name="user" property="username" value="Alice" />
    
    <!-- 3. Get properties -->
    
    <p>Username: <jsp:getProperty name="user" property="username" /></p>
    
    

B. Session Tracking

  • Using Cookies in JSP:

    
    // In a servlet/JSP scriptlet (not recommended in JSP, better in servlet)
    
    Cookie cookie = new Cookie("user", "Alice");
    
    cookie.setMaxAge(3600); // 1 hour
    
    response.addCookie(cookie); // Send to client
    
    // Reading
    
    Cookie[] cookies = request.getCookies();
    
    for (Cookie c : cookies) {
    
        if (c.getName().equals("user")) {
    
            String user = c.getValue();
    
        }
    
    }
    
    
  • HttpSession Object (Preferred):

    • Server-side storage associated with a client via a session ID (usually in a cookie).

    • Creating/Using:

      
      // In servlet/JSP
      
      HttpSession session = request.getSession(); // Creates if doesn't exist
      
      session.setAttribute("user", userObject); // Store object
      
      User u = (User) session.getAttribute("user"); // Retrieve
      
      session.invalidate(); // Destroy session on logout
      
      
    • Advantage over Cookies: Stores more data securely on server; client only has session ID.

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