Web Programming Fundamentals
Review
This document contains code examples and explanations for Modules 1 through 6, covering
💻
XML, JavaScript, React, [Link], and [Link].
Module 1 — Web Programming Fundamentals
(Code questions)
M1 — Q7. Write an XML file [Link] representing your
semester mark sheet. How to prove it is well-formed and valid?
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<!-- Linking to the [Link] for validation -->
<Marksheet roll="BECT2022001" semester="5"
xmlns:xsi="[[Link]
rg/2001/XMLSchema-instance)"
xsi:noNamespaceSchemaLocation="[Link]">
<Student>
<Name>Mahir Abdul Majeed Lokare</Name>
<Program>B.E. Computer Engineering</Program>
</Student>
<Subjects>
<Subject code="WC">
<Title>Web Computing</Title>
<MarksObtained>82</MarksObtained>
<MaxMarks>100</MaxMarks>
</Subject>
<Subject code="CN">
<Title>Computer Networks</Title>
<MarksObtained>75</MarksObtained>
<MaxMarks>100</MaxMarks>
</Subject>
</Subjects>
<Total>157</Total>
<Percentage>78.5</Percentage>
</Marksheet>
Prove Well-Formed:
A document is well-formed if it adheres to the basic syntax rules of XML: it has exactly one root
element, matching opening/closing tags, proper nesting, and quoted attribute values.
Verification Method: Use an XML parser or a command-line tool like xmllint.
# Command to check if [Link] is well-formed
xmllint --noout [Link]
Prove Valid (against a schema):
A document is valid if it is well-formed AND it conforms to a specified schema (DTD or XSD).
Verification Method: Create an XSD file and validate the XML against it using an XML validator
or xmllint.
Example XSD ([Link])
<xs:schema
xmlns:xs="[[Link]
LSchema)">
<xs:element name="Marksheet">
<xs:complexType>
<xs:sequence>
<xs:element name="Student" type="StudentType"/>
<xs:element name="Subjects">
<xs:complexType>
<xs:sequence>
<xs:element name="Subject"
maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="Title"
type="xs:string"/>
<xs:element
name="MarksObtained" type="xs:integer"/>
<xs:element name="MaxMarks"
type="xs:integer"/>
</xs:sequence>
<xs:attribute name="code"
type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Total" type="xs:integer"/>
<xs:element name="Percentage" type="xs:decimal"/>
</xs:sequence>
<xs:attribute name="roll" type="xs:string"
use="required"/>
<xs:attribute name="semester" type="xs:integer"
use="required"/>
</xs:complexType>
</xs:element>
<xs:complexType name="StudentType">
<xs:sequence>
<xs:element name="Name" type="xs:string"/>
<xs:element name="Program" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
🧠 Module 2 — JavaScript (ES5 & ES6)
M2 — Q1. Digital clock on a web page
<!DOCTYPE html>
<html>
<head>
<title>Digital Clock</title>
</head>
<body>
<div id="clock" style="font-size: 40px; font-family:
monospace;"></div>
<script>
function updateClock() {
const now = new Date();
// toLocaleTimeString formats the time based on the user's
locale
const time = [Link]();
[Link]('clock').textContent = time;
}
// Call updateClock every 1000 milliseconds (1 second)
setInterval(updateClock, 1000);
// Initial call to display the time immediately
updateClock();
</script>
</body>
</html>
M2 — Q5 & Q15. Accept two numbers and display sum
1. Using page inputs (sum displayed inline)
<!DOCTYPE html>
<html>
<body>
<label for="a">Number 1:</label>
<input type="number" id="a">
<label for="b">Number 2:</label>
<input type="number" id="b">
<button onclick="showSum()">Sum</button>
<div id="out"></div>
<script>
function showSum() {
const a = Number([Link]('a').value) || 0;
const b = Number([Link]('b').value) || 0;
[Link]('out').textContent = 'Sum = ' + (a
+ b);
}
</script>
</body>
</html>
2. Popup version (using prompt)
// Note: alert() is typically avoided in modern web apps, but used
here for the prompt requirement.
const a = Number(prompt("Enter first number"));
const b = Number(prompt("Enter second number"));
[Link]("Sum = " + (a + b)); // Displaying in console instead of
alert()
M2 — Q6. Change background color with buttons
<!DOCTYPE html>
<html>
<body>
<button id="red">RED</button>
<button id="green">GREEN</button>
<script>
[Link]('red').onclick = () => {
[Link] = 'red';
};
[Link]('green').onclick = () => {
[Link] = 'green';
};
</script>
</body>
</html>
M2 — Q7, Q11, Q12, Q13, Q14. Form validation (various)
<!DOCTYPE html>
<html>
<body>
<form onsubmit="return validateForm()">
<label for="username">Username (5-15 alphanumeric):</label>
<input type="text" id="username"><br><br>
<label for="password">Password (min 8, complex):</label>
<input type="password" id="password"><br><br>
<label for="email">Email:</label>
<input type="email" id="email"><br><br>
<label for="age">Age (18-60):</label>
<input type="number" id="age"><br><br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
const u =
[Link]('username').[Link]();
const p = [Link]('password').value;
const e = [Link]('email').[Link]();
const age = Number([Link]('age').value);
// 1. Required fields check
if (!u || !p || !e || !age) {
[Link]('Validation Error: Fill all fields');
return false;
}
// 2. Username: alphanumeric, 5–15 characters
if (!/^[a-zA-Z0-9]{5,15}$/.test(u)) {
[Link]('Validation Error: Username invalid:
must be 5-15 alphanumeric characters.');
return false;
}
// 3. Password: min 8 chars, at least one uppercase, one
lowercase, one number
if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}/.test(p)) {
[Link]('Validation Error: Password weak: min 8
chars, must include uppercase, lowercase, and a number.');
return false;
}
// 4. Email basic check
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) {
[Link]('Validation Error: Email invalid
format.');
return false;
}
// 5. Age range check
if (age < 18 || age > 60) {
[Link]('Validation Error: Age must be between
18 and 60.');
return false;
}
[Link]('Form valid');
return true;
}
</script>
</body>
</html>
M2 — Q8 & Q14 (Email validation specific function)
function validateEmail(e) {
if () {
[Link]("Email must contain '@'. Re-enter.");
return false;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) {
[Link]("Invalid email format.");
return false;
}
return true;
}
M2 — Q9. Set a cookie
/**
* Sets a browser cookie.
* @param {string} name - The name of the cookie.
* @param {string} value - The value to store.
* @param {number} days - The number of days until the cookie expires.
*/
function setCookie(name, value, days) {
const d = new Date();
[Link]([Link]() + (days * 24 * 60 * 60 * 1000));
const expires = [Link]();
// Construct the cookie string
[Link] =
`${name}=${encodeURIComponent(value)};expires=${expires};path=/;Secure
`;
}
// Example usage
setCookie('username', 'mahir', 7);
M2 — Q10. Move an image continuously left→right
<!DOCTYPE html>
<html>
<head>
<style>
#car {
position: absolute;
top: 50px;
width: 100px;
}
</style>
</head>
<body>
<img id="car"
src="[[Link]
://[Link]/100x50/007bff/ffffff?text=Car)" alt="Moving
Car">
<script>
const img = [Link]('car');
let x = 0;
function animate() {
x += 2;
// If the image goes off the right edge, reset it to the
far left (minus its width)
if (x > [Link]) {
x = -[Link];
}
[Link] = x + 'px';
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
M2 — Q16. Cookies vs Local Storage (short code examples)
Feature Cookies Local Storage
Storage Limit Small (approx. 4KB) Large (approx. 5-10MB)
Expiration Set manually (expires on date) Never expires (unless cleared)
Sent with Request Yes (automatically with HTTP No
request)
Local Storage Example
// Set an item
[Link]('theme', 'dark');
// Get an item
const t = [Link]('theme');
// Remove an item
[Link]('theme');
⚛️ Module 3 — React Fundamentals
M3 — Q1. Class component Car and invoking it
[Link] (Class Component)
import React from 'react';
class Car extends [Link] {
render() {
return (
<div>
<h2>Car model: {[Link] || "Default"}</h2>
</div>
);
}
}
export default Car;
Invocation Example (conceptual [Link])
// import { createRoot } from 'react-dom/client';
// import Car from './Car';
// const root = createRoot([Link]('root'));
// [Link](<Car model="Tesla Model S" />);
M3 — Q2. Event handling: Button “Greet the User”
function App() {
const greet = () => [Link]('Hello!');
return (
<button onClick={greet}>
Greet the User
</button>
);
}
// export default App;
M3 — Q3 & Q4. Component lifecycle (class) — brief code example
The React component lifecycle has three main phases: Mounting, Updating, and Unmounting.
[Link] (Lifecycle Example)
import React from 'react';
class Timer extends [Link] {
// Mounting Phase: Called after the component is rendered to the
DOM
componentDidMount() {
[Link] = setInterval(() => [Link]('Timer tick...'),
1000);
}
// Unmounting Phase: Called right before the component is
destroyed
componentWillUnmount() {
clearInterval([Link]); // Cleanup is crucial
}
// Updating Phase occurs when props or state change
render() {
return <div>Timer running (check console)</div>;
}
}
// export default Timer;
M3 — Q6. JSX example: Single Page message
function Welcome() {
return (
<div className="welcome-message">
<h1>Hello! Welcome to React</h1>
<p>This is a simple JSX rendering example.</p>
</div>
);
}
// export default Welcome;
M3 — Q7 & Q8. State vs Props and example
Feature State Props
Purpose Manages data local to a Passes data from a parent to a
component that changes over child component.
time.
Mutability Can be changed by the Read-only for the child
component using setter component.
functions (useState).
import React, { useState } from 'react';
function ItemList() {
// STATE (Internal data)
const [items, setItems] = useState(['A', 'B']);
return (
<div>
{/* PROPS (Data/function passed to child) */}
<Child
items={items}
add={() => setItems([...items, 'C'])}
/>
</div>
);
}
function Child({ items, add }) {
return (
<>
<ul>
{/* Uses data received via props */}
{[Link]((i, idx) => (
<li key={idx}>{i}</li>
))}
</ul>
{/* Calls function received via props to update parent
state */}
<button onClick={add}>Add</button>
</>
);
}
// export default ItemList;
M3 — Q9 & Q10. React Router example (v6)
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
const HomePage = () => <h1>Home Page Content</h1>;
const AboutPage = () => <h1>About Us</h1>;
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> | <Link
to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
</Routes>
</BrowserRouter>
);
}
// export default App;
M3 — Q11. Functional component with Hooks to add/remove items
import React, { useState } from 'react';
export default function Todo() {
const [items, setItems] = useState([]);
const [text, setText] = useState('');
const addItem = () => {
if (text) {
setItems([...items, text]);
setText('');
}
};
const removeItem = (indexToRemove) => {
setItems([Link]((_, j) => j !== indexToRemove));
};
return (
<div>
<input
value={text}
onChange={e => setText([Link])}
placeholder="New item..."
/>
<button onClick={addItem}>Add</button>
<ul>
{[Link]((it, i) => (
<li key={i}>
{it}
<button onClick={() =>
removeItem(i)}>X</button>
</li>
))}
</ul>
</div>
);
}
M3 — Q12. Fetch data from external API and display it
import React, { useEffect, useState } from 'react';
function Users() {
const [users, setUsers] = useState([]);
// useEffect is used to run the side effect (data fetch) after
render
useEffect(() => {
fetch('[[Link]
[Link]/users)')
.then(res => [Link]())
.then(setUsers)
.catch(err => [Link](err));
}, []); // Empty dependency array ensures it runs only on mount
return (
<div>
<h2>User List</h2>
<ul>
{[Link](u => <li key={[Link]}>{[Link]} -
{[Link]}</li>)}
</ul>
</div>
);
}
// export default Users;
M3 — Q13. Form component handling submit + confirmation
import React, { useState } from 'react';
function Contact() {
const [name, setName] = useState('');
const [submitted, setSubmitted] = useState(false);
const onSubmit = (e) => {
[Link](); // Prevent page reload
// Simulate form processing
setTimeout(() => setSubmitted(true), 500);
};
return (
<div>
{submitted ? (
<h3>Thanks, {name} — form submitted.</h3>
) : (
<form onSubmit={onSubmit}>
<input
value={name}
onChange={e => setName([Link])}
placeholder="Name"
required
/>
<button type="submit">Submit</button>
</form>
)}
</div>
);
}
// export default Contact;
🟢 Module 4 — [Link]
M4 — Q1. Simple Node server showing “Welcome”
[Link]
const http = require('http');
const port = 3000;
const server = [Link]((req, res) => {
[Link](200, {'Content-Type': 'text/plain'});
[Link]('Welcome\n');
});
[Link](port, () => {
[Link](`Server running at [Link]
});
// To run: node [Link]
M4 — Q2. Create a text file with user-provided data (console input)
const fs = require('fs');
const readline = require('readline');
const rl = [Link]({ input: [Link], output:
[Link]});
[Link]('Enter text to save: ', (ans) => {
try {
[Link]('[Link]', ans);
[Link]('Text successfully saved to [Link]');
} catch (err) {
[Link]('Error writing file:', err);
}
[Link]();
});
M4 — Q6 & Q7. Event Loop explanation + example
The [Link] Event Loop is the mechanism that handles asynchronous operations (I/O, timers,
etc.) non-blockingly. It continuously checks various phases for pending operations.
Example showing non-blocking I/O
const fs = require('fs');
[Link]('start'); // Synchronous code runs first
// Timer (Timers phase)
setTimeout(() => [Link]('timeout callback'), 0);
// I/O (Poll phase)
[Link](__filename, () => [Link]('file read callback'));
// Microtask (High priority, runs before Timers/I/O)
[Link]().then(() => [Link]('promise microtask'));
[Link]('end'); // Synchronous code runs immediately after 'start'
// Execution order (Synchronous > Microtasks > Timers > I/O > Check)
// 1. start
// 2. end
// 3. promise microtask
// 4. timeout callback
// 5. file read callback
M4 — Q8. Callback in [Link] with example
function doTask(cb) {
// Simulate async operation
setTimeout(() => {
// Standard (err, result) convention
cb(null, 'done');
}, 1000);
}
// Pass a callback function to handle the result later
doTask((err, res) => {
if (err) [Link](err);
else [Link](res);
});
[Link]('Program continues while task runs.');
M4 — Q10. Using streams for efficient read/write
Streams are used for very large data (files, network) to process chunks without loading
everything into memory, saving resources.
const fs = require('fs');
// Create a readable stream for a source file
const read = [Link]('[Link]');
// Create a writable stream for a destination file
const write = [Link]('[Link]');
// Pipe connects the output of the read stream to the input of the
write stream
[Link](write);
[Link]('end', () => [Link]('Copied using streams.'));
M4 — Q11. Read file and send as HTTP response
const http = require('http');
const fs = require('fs');
[Link]((req, res) => {
const stream = [Link]('[Link]');
[Link](200, {'Content-Type': 'text/html'});
// Pipe the file data directly into the HTTP response (efficient)
[Link](res);
[Link]('error', (err) => {
[Link](500);
[Link]('File not found.');
});
}).listen(3000);
M4 — Q12. Callbacks, Promises, async/await examples
Callback
const fs = require('fs');
[Link]('[Link]', 'utf8', (err, data) => {
if (err) throw err;
[Link](data);
});
Promise
const fsPromises = require('fs').promises;
[Link]('[Link]', 'utf8')
.then(data => [Link](data))
.catch([Link]);
Async/Await
const fsPromises = require('fs').promises;
(async () => {
try {
const data = await [Link]('[Link]', 'utf8');
[Link](data);
} catch (e) {
[Link](e);
}
})();
🚀 Module 5 — [Link]
M5 — Q6. Express app handling GET & POST, routing, error handling
[Link]
const express = require('express');
const app = express();
const port = 3000;
// Middleware to parse JSON body for POST/PUT requests
[Link]([Link]());
// GET /
[Link]('/', (req, res) => [Link]('Hello from Express'));
// GET /items
[Link]('/items', (req, res) => [Link]([{ id: 1, name: 'item1' }]));
// POST /items (Handles data submission)
[Link]('/items', (req, res) => {
const item = [Link];
if (!item || ![Link]) {
// Validation check
return [Link](400).json({ error: 'name required' });
}
// Success response
[Link] = [Link]();
[Link](201).json(item);
});
// Basic Error Handling Middleware (must take 4 arguments)
[Link]((err, req, res, next) => {
[Link]([Link]); // Log the error
[Link](500).send('Server error');
});
[Link](port, () => [Link]('Express listening on', port));
M5 — Q7. Express + React integration (simple flow)
Express provides the Backend (REST API endpoints), and React acts as the Frontend (SPA).
Flow:
1. React component mounts.
2. useEffect hook calls fetch('/items').
3. Express handles the /items GET request and returns JSON.
4. React receives the JSON, updates state (useState), and re-renders the UI.
M5 — Q5. Express Router purpose (example)
Purpose: To create modular, maintainable route handlers, isolating routes for specific resources
(e.g., all /items logic).
routes/[Link] (Modular Route)
const express = require('express');
const router = [Link]();
[Link]('/', (req, res) => [Link]({ message: 'Items list from
router' }));
[Link]('/', (req, res) => [Link](201).json([Link]));
[Link] = router;
[Link] (Using the Router)
// ... in [Link]
const itemsRouter = require('./routes/items');
// Mount the router, prefixing all its routes with '/items'
[Link]('/items', itemsRouter);
✨ Module 6 — Advanced React
M6 — Q1 & Q3. Hooks concept + rules
Concept: Hooks (like useState, useEffect) let functional components "hook into" React features
like state and lifecycle.
Rules:
1. Top-Level Only: Call Hooks only at the top of your functional components.
2. React Functions Only: Call Hooks only from functional components or custom Hooks
(not regular JavaScript functions).
M6 — Q2. useState example: 4 color buttons
import React, { useState } from 'react';
function ColorButtons() {
const [color, setColor] = useState('none');
const colors = ['Red', 'Blue', 'Green', 'Yellow'];
return (
<div>
<p>Selected: <span style={{ color: color
}}>{color}</span></p>
{[Link](c => (
<button key={c} onClick={() =>
setColor([Link]())}>
{c}
</button>
))}
</div>
);
}
// export default ColorButtons;
M6 — Q4. useEffect to fetch data (with cleanup)
import React, { useEffect, useState } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
let mounted = true; // Use for cleanup/unmount safety
fetch('/api/data')
.then(res => [Link]())
.then(d => {
if (mounted) setData(d);
});
// Cleanup function
return () => {
mounted = false; // Mark component as unmounted
};
}, []); // Empty array = run once on mount
return <div>Data: {data ? 'Loaded' : 'Loading...'}</div>;
}
// export default DataFetcher;
M6 — Q7. Redux example (very short)
Redux centralizes application state in a single Store. Actions describe what happened, and
Reducers update the state immutably.
Component Usage (using react-redux hooks)
// import { useDispatch, useSelector } from 'react-redux';
// import { addItem } from './actions';
function ReduxExample() {
// const items = useSelector(s => [Link]); // Read state
// const dispatch = useDispatch(); // Get dispatch function
// const handleAdd = () => {
// dispatch(addItem('New Item')); // Send an action
// };
return <p>Redux uses Store, Actions, and Reducers for centralized
state.</p>;
}
// export default ReduxExample;
M6 — Q8 & Q10. Refs and useEffect example
useRef is used to access the underlying DOM element directly.
import React, { useRef, useEffect } from 'react';
function FocusInput() {
// 1. Create the ref object
const inputRef = useRef(null);
// 2. useEffect runs after the component is mounted
useEffect(() => {
// 3. Access the DOM node via .current and call a DOM method
[Link] && [Link]();
}, []); // Run only once on mount
return (
<input
type="text"
ref={inputRef} // 4. Attach the ref to the element
placeholder="I auto-focus"
/>
);
}
// export default FocusInput;