Course code: BCA203 (2018 equivalent: CACS205)
Semester: 3
Credits: 3
Class load: 6 Hrs./Week (Theory: 3 Hrs., Practical: 3 Hrs.)
Syllabus status: The unit breakdown and teaching hours below are carried over from the 2018 CACS205 syllabus. The official 2025 TU document lists BCA203 but has no verified numbered unit outline for this semester, so these units and hours are pending 2025 confirmation rather than verified 2025 TU content.
Course Overview
The World Wide Web is the most widely used part of the Internet. Almost every piece of software you encounter — from banking apps to social media — has a web interface. This course teaches the fundamental technologies that make web applications work, from the markup you write in HTML to the multi-tier architectures that power large-scale sites.
You will learn HTML to structure content, CSS to style it, JavaScript for interactivity, XML and related technologies for data exchange, and server-side concepts for dynamic content generation. By the end of the course you can describe the full technology stack of a web application and understand how data moves between browsers and servers.
Learning Outcomes
- Write valid HTML documents using structure, formatting, table, frame, form, and image-map tags.
- Apply CSS stylesheets using inline, embedded, and linked approaches.
- Explain the architectural differences between 2-tier, 3-tier, and n-tier web applications.
- Use XML to define, validate (DTD/XSD), transform (XSLT/XPath), and query (XQuery) data.
- Work with XML parsers using SAX and DOM approaches.
- Describe server-tier concepts: web servers, dynamic content, sessions, error handling, and tag libraries.
- Apply server-side features: database connectivity, SQL statements, authentication, cookies, and file/form handling.
Unit 1: HTML and CSS
Teaching hours: 15
HTML (HyperText Markup Language) defines the structure and content of web pages. CSS (Cascading Style Sheets) controls their visual presentation. Together they are the foundation of every web page.
1.1 HTML Basics and Tag Reference
HTML document structure:
<!DOCTYPE html> <!-- declares HTML5 document type -->
<html lang="en"> <!-- root element; lang sets language -->
<head> <!-- metadata section -->
<meta charset="UTF-8"> <!-- character encoding -->
<title>BCA Nepal</title> <!-- browser tab title -->
</head>
<body> <!-- visible page content goes here -->
<h1>Welcome</h1>
<p>This is a paragraph.</p>
</body>
</html>
Tag syntax: <tagname attribute="value">content</tagname>
Self-closing tags: <img>, <br>, <hr>, <input>, <meta> — have no closing tag in HTML5.
Global Attributes
Global attributes can be applied to any HTML element:
| Attribute | Purpose | Example |
|---|---|---|
id |
Unique identifier on the page | id="header" |
class |
CSS class name(s) | class="highlight bold" |
style |
Inline CSS | style="color:red" |
title |
Tooltip on hover | title="Click to expand" |
lang |
Language of the element | lang="ne" |
data-* |
Custom data attributes | data-userid="42" |
Document Structure Tags
<html> <!-- root element -->
<head> <!-- metadata, links, scripts -->
<body> <!-- visible content -->
<header> <nav> <main> <article> <section> <aside> <footer> <!-- HTML5 semantics -->
Formatting Tags
<h1> to <h6> <!-- headings; h1 is largest/most important -->
<p> <!-- paragraph; browsers add space before and after -->
<strong> <!-- important text (bold by default) -->
<em> <!-- emphasized text (italic by default) -->
<b> <!-- bold (no semantic meaning) -->
<i> <!-- italic (no semantic meaning) -->
<u> <!-- underline -->
<s> <!-- strikethrough -->
<sub> <!-- subscript: H<sub>2</sub>O -->
<sup> <!-- superscript: x<sup>2</sup> -->
<br> <!-- line break (self-closing) -->
<hr> <!-- horizontal rule/divider (self-closing) -->
<pre> <!-- preformatted text; preserves spaces and newlines -->
<code> <!-- inline code -->
<blockquote> <!-- indented quotation block -->
<abbr title="BCA">BCA</abbr> <!-- abbreviation with full text in title -->
Text-Level Formatting
<span style="color:blue;">Blue text</span> <!-- inline container for styling -->
<mark>highlighted</mark> <!-- yellow-highlighted text -->
<del>deleted</del> <ins>inserted</ins> <!-- tracked changes -->
Block-Level Formatting
<div class="container"> <!-- generic block container; no semantic meaning -->
<p>Block-level content.</p>
</div>
Block vs. inline elements:
- Block elements (
<p>,<div>,<h1>,<ul>) start on a new line and take full width. - Inline elements (
<span>,<a>,<strong>,<em>) flow within text.
List Tags
<!-- Unordered (bulleted) list -->
<ul>
<li>Apple</li>
<li>Banana</li>
</ul>
<!-- Ordered (numbered) list -->
<ol type="A"> <!-- type: 1 (default), a, A, i, I -->
<li>First</li>
<li>Second</li>
</ol>
<!-- Definition list -->
<dl>
<dt>HTML</dt> <!-- term -->
<dd>HyperText Markup Language</dd> <!-- definition -->
</dl>
<!-- Nested list -->
<ul>
<li>Fruits
<ul>
<li>Mango</li>
<li>Orange</li>
</ul>
</li>
</ul>
Executable Content Tags (Scripts and Objects)
<script src="app.js"></script> <!-- links to external JavaScript file -->
<script>alert("Hello");</script> <!-- inline JavaScript -->
<noscript>Enable JavaScript.</noscript> <!-- fallback when JS is disabled -->
<object data="video.mp4" type="video/mp4"> <!-- embeds external content -->
<embed src="file.pdf" type="application/pdf"> <!-- inline embedding -->
1.2 Images and Image Maps
<!-- Basic image -->
<img src="logo.png" alt="BCA Nepal Logo" width="200" height="100">
<!-- src: image file path or URL -->
<!-- alt: alternative text (accessibility; shown when image fails to load) -->
<!-- width, height: dimensions in pixels -->
Client-Side Image Map:
Defines clickable regions on an image. Each region (hotspot) is a <area> element linked to a URL.
<img src="nepal-map.png" alt="Nepal Map" usemap="#nepalmap">
<map name="nepalmap"> <!-- name matches usemap value (without #) -->
<area shape="rect" coords="10,20,100,80" href="kathmandu.html" alt="Kathmandu">
<!-- rect: rectangular area; coords = x1,y1,x2,y2 (top-left, bottom-right) -->
<area shape="circle" coords="200,150,30" href="pokhara.html" alt="Pokhara">
<!-- circle: coords = centerX,centerY,radius -->
<area shape="poly" coords="300,10,350,50,280,80" href="biratnagar.html" alt="Biratnagar">
<!-- poly: coords = x1,y1,x2,y2,... for polygon vertices -->
</map>
Server-Side Image Map:
Click coordinates are sent to the server as URL?x,y. The server interprets the coordinates and returns the appropriate response. Used when region boundaries must be computed dynamically (less common today).
Alternative text for image maps: Each <area> must have an alt attribute for screen readers and when the image fails to load.
1.3 HTML Tables
Tables organise data in rows and columns.
<table border="1" cellpadding="5" cellspacing="0" width="80%">
<!-- border: outer border thickness -->
<!-- cellpadding: space inside each cell -->
<!-- cellspacing: space between cells -->
<!-- width: table width relative to parent -->
<caption>Student Marks</caption> <!-- caption displayed above table -->
<thead> <!-- semantic group for header rows -->
<tr> <!-- table row -->
<th>Name</th> <!-- header cell; bold and centred by default -->
<th>Mark</th>
</tr>
</thead>
<tbody> <!-- semantic group for data rows -->
<tr>
<td>Sita</td> <!-- data cell -->
<td bgcolor="#ffffcc">85</td> <!-- bgcolor: background colour -->
</tr>
<tr>
<td colspan="2" align="center">Total students: 1</td>
<!-- colspan: cell spans 2 columns -->
<!-- align: horizontal alignment (left, center, right) -->
</tr>
</tbody>
</table>
Row and column spanning:
<td rowspan="2">Monday</td> <!-- cell spans 2 rows -->
<td colspan="3">Morning</td> <!-- cell spans 3 columns -->
Table sections: <thead>, <tbody>, <tfoot> provide semantic structure and allow the browser to scroll the body while keeping header/footer visible.
Tables as design tools: Historically used for page layout (placing content in grid), but CSS grid and flexbox have replaced this practice. Tables should only be used for tabular data.
1.4 Frames
Frames divide a browser window into sections, each loading a separate HTML document.
<!-- frameset.html: defines the frame layout -->
<frameset cols="20%,80%"> <!-- split horizontally: 20% left, 80% right -->
<frame src="nav.html" name="navframe">
<frame src="content.html" name="contentframe">
</frameset>
<!-- Nesting: frameset inside frameset -->
<frameset rows="80px,*"> <!-- 80px top bar, rest is main area -->
<frame src="header.html">
<frameset cols="20%,80%">
<frame src="sidebar.html">
<frame src="main.html">
</frameset>
</frameset>
Targeting named frames:
<a href="newpage.html" target="contentframe">Load in content frame</a>
<!-- target names a frame by its name attribute -->
<!-- target="_blank": new browser tab -->
<!-- target="_self": same frame (default) -->
<!-- target="_top": full browser window (break out of all frames) -->
Floating frames (<iframe>):
<iframe src="map.html" width="400" height="300" name="mapframe">
Fallback text if iframes not supported.
</iframe>
Hidden frames: Set width="0" height="0" — used to load resources without displaying them (early AJAX workaround).
Frames are deprecated in HTML5. Modern sites use CSS for layout and JavaScript (fetch/AJAX) for dynamic content. The <iframe> element remains valid.
1.5 HTML Forms
Forms collect user input and send it to a server.
<form action="submit.php" method="POST">
<!-- action: URL to submit data to -->
<!-- method: GET (data in URL) or POST (data in request body) -->
<!-- Text input -->
<label for="username">Username:</label>
<input type="text" id="username" name="username" placeholder="Enter name"
required maxlength="50">
<!-- id: for label association; name: key in form data; placeholder: hint text -->
<!-- required: browser will not submit if empty; maxlength: character limit -->
<!-- Password (masked input) -->
<input type="password" name="pass">
<!-- Radio buttons: only one in a group can be selected -->
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<!-- Checkboxes: multiple can be selected -->
<input type="checkbox" name="hobby" value="coding"> Coding
<input type="checkbox" name="hobby" value="reading"> Reading
<!-- Select (drop-down) -->
<select name="course">
<option value="">-- Select --</option>
<option value="bca" selected>BCA</option> <!-- selected: pre-selected option -->
<option value="bsc">BSc</option>
</select>
<!-- Multi-line text area -->
<textarea name="message" rows="5" cols="40"></textarea>
<!-- Hidden field (not visible to user) -->
<input type="hidden" name="csrf_token" value="abc123">
<!-- File upload -->
<input type="file" name="resume" accept=".pdf,.docx">
<!-- Submit and reset buttons -->
<input type="submit" value="Submit">
<input type="reset" value="Clear">
<button type="submit">Submit</button> <!-- alternative button -->
</form>
Form validation: The required, minlength, maxlength, min, max, pattern attributes enable HTML5 client-side validation before submission. Server-side validation is still required because client-side checks can be bypassed.
Passing form data: GET appends data to the URL as a query string (?name=value&...) — suitable for search forms. POST sends data in the HTTP request body — required for sensitive data (passwords) and large payloads (file uploads).
1.6 CSS Style Sheets
CSS controls the visual appearance (colour, font, layout, spacing) of HTML elements.
Three Approaches
1. Inline styles — applied directly to an element:
<p style="color: blue; font-size: 16px;">Blue text</p>
Highest specificity; hard to maintain.
2. Internal (embedded) styles — inside <style> in <head>:
<head>
<style>
p { color: blue; font-size: 16px; }
.highlight { background-color: yellow; }
#header { font-weight: bold; }
</style>
</head>
Good for single-page documents.
3. External stylesheet — separate .css file linked with <link>:
<head>
<link rel="stylesheet" href="styles.css">
</head>
Best for multi-page sites — one file controls the whole site.
CSS Selectors
| Selector | Syntax | Matches |
|---|---|---|
| Element | p { } |
All <p> elements |
| Class | .box { } |
All elements with class="box" |
| ID | #header { } |
The element with id="header" |
| Attribute | input[type="text"] { } |
Inputs with type text |
| Descendant | div p { } |
<p> inside any <div> |
| Child | ul > li { } |
<li> direct children of <ul> |
| Pseudo-class | a:hover { } |
<a> when mouse is over it |
CSS Cascade
"Cascading" means multiple rules can apply to the same element. Priority (highest to lowest):
- Inline style
- Internal
<style>/ external stylesheet rules (by specificity) - Browser default styles
Specificity: ID selectors > Class selectors > Element selectors. When specificity is equal, the later rule wins.
Key Terms — Unit 1
- HTML tag — markup element;
<tag>content</tag>or<tag>for void elements - Attribute — extra information inside an opening tag:
name="value" - CSS selector — pattern matching which elements to style
- Cascade — priority rules determining which CSS declarations apply
- Image map — image with clickable areas defined by
<area>elements
Unit 2: Issue of Web Technology
Teaching hours: 3
2.1 Architectural Issues of the Web Layer
A web application is different from a desktop application because requests travel over a network between clients (browsers) and servers. This introduces several architectural concerns:
- Statelessness: HTTP is a stateless protocol — each request is independent. The server does not automatically remember previous requests from the same client. Sessions (Unit 5) solve this.
- Scalability: As users increase, the server must handle more concurrent requests.
- Security: Data travels over public networks and can be intercepted or modified.
- Latency: Network round trips add time; architecture affects how many trips a user experience requires.
2.2 Two-Tier Architecture
[Client: Browser] ←── HTTP ──→ [Server: Application + Database]
The simplest model: the browser sends requests directly to a server that also contains the application logic and the database.
Advantages:
- Simple to build and deploy
- Low latency (no intermediate layer)
Disadvantages:
- Poor scalability (business logic and database compete on one machine)
- Security risk (database directly reachable from application, which is internet-facing)
- Difficult to maintain (business logic mixed with presentation logic)
Typical use: Small personal sites, internal tools, early web applications.
2.3 Three-Tier Architecture
[Presentation Tier] ←─── [Logic Tier] ←─── [Data Tier]
Browser / Client Application Database
Server
The three layers are:
- Presentation tier: The browser. Renders HTML, handles user interaction.
- Business logic tier: The application server. Processes requests, applies business rules, coordinates with the data tier.
- Data tier: The database server. Stores and retrieves data.
Advantages:
- Each tier can be scaled independently
- Presentation tier cannot directly access the database (security)
- Business logic can be reused by different clients (web, mobile)
- Easier to maintain — changes to one tier do not break others
Disadvantages:
- More complex to design and deploy
- Extra network hop between tiers adds some latency
Example: A user submits a login form → browser (tier 1) → Django/Rails application server (tier 2) → MySQL database (tier 3). The application server verifies credentials and returns a session token. The browser never touches the database directly.
2.4 N-Tier Architecture
For very large applications, the logic tier can itself be subdivided:
- API gateway — authentication, rate limiting, routing
- Microservices — separate services for user management, orders, payments
- Caching layer — Redis between application and database
- Message queue — asynchronous task processing (email sending, report generation)
graph LR
A[Browser] --> B[Load Balancer]
B --> C[App Server 1]
B --> D[App Server 2]
C --> E[Cache Redis]
D --> E
E --> F[Database]
C --> G[Message Queue]
An n-tier web architecture showing load balancing across multiple application servers, a cache layer, and a message queue for asynchronous processing.
Key Terms — Unit 2
- 2-tier — client + combined application+database server
- 3-tier — presentation + logic + data tiers separated
- N-tier — logic tier further divided into microservices, caches, queues
- Stateless protocol — HTTP; each request is independent
Unit 3: The Client Tier
Teaching hours: 10
3.1 Representing Content with XML
XML (eXtensible Markup Language) is a markup language designed to store and transport data in a format that is both human-readable and machine-readable. Unlike HTML, XML does not define presentation — it defines structure and meaning.
<?xml version="1.0" encoding="UTF-8"?> <!-- XML declaration -->
<students>
<student id="101">
<name>Sita Rai</name>
<major>BCA</major>
<marks>85</marks>
</student>
<student id="102">
<name>Ram Sharma</name>
<major>BCA</major>
<marks>78</marks>
</student>
</students>
Why XML matters: It is the basis of SVG, XHTML, SOAP web services, RSS feeds, office document formats (DOCX, XLSX), and many configuration files.
3.2 XML Elements and Attributes
| Feature | Description | Example |
|---|---|---|
| Element | Node with open/close tags or self-closing | <name>Sita</name> or <br/> |
| Attribute | Name-value pair inside the opening tag | id="101" |
| Text node | Character data between tags | Sita Rai |
| CDATA section | Raw character data, not parsed | <![CDATA[<div>raw</div>]]> |
| Comment | Not processed | <!-- comment --> |
When to use elements vs. attributes: Use elements for content that may have sub-structure or needs to be transformed; use attributes for metadata/identifiers. The id="101" attribute uniquely identifies a student — good use of an attribute.
3.3 Rules for Writing Well-Formed XML
A well-formed XML document follows these syntactic rules:
- Exactly one root element.
- All elements must be properly closed:
<tag>...</tag>or<tag/>. - Tags must be properly nested (no crossing:
<a><b></a></b>is invalid). - Attribute values must be quoted (single or double).
- XML is case-sensitive:
<Name>and<name>are different elements. - Special characters must use entity references:
<for<,>for>,&for&,"for",'for'.
3.4 XML Namespaces
A namespace avoids naming conflicts when combining XML from different sources.
<root
xmlns:bca="http://bcanepal.edu/schema"
xmlns:hr="http://hr.company.com/schema">
<bca:student>Sita</bca:student> <!-- student from bca namespace -->
<hr:employee>Ram</hr:employee> <!-- employee from hr namespace -->
</root>
The URI in xmlns:prefix="URI" does not need to point to a real document — it is just a unique identifier.
3.5 XML Schema (XSD)
A schema validates that an XML document follows a defined structure — required elements, data types, constraints.
DTD (Document Type Definition): Older syntax, limited data types.
<!-- Internal DTD declaration within the XML file -->
<?xml version="1.0"?>
<!DOCTYPE students [
<!ELEMENT students (student+)> <!-- students contains one or more student -->
<!ELEMENT student (name, major)> <!-- student contains name then major -->
<!ELEMENT name (#PCDATA)> <!-- name contains text -->
<!ELEMENT major (#PCDATA)>
<!ATTLIST student id CDATA #REQUIRED> <!-- student has required id attribute -->
]>
<students>
<student id="101"><name>Sita</name><major>BCA</major></student>
</students>
Types of DTD declarations:
- Internal:
<!DOCTYPE root [...]>— embedded in the XML file itself. - Private external:
<!DOCTYPE root SYSTEM "students.dtd">— references a local DTD file. - Public external:
<!DOCTYPE root PUBLIC "-//W3C//DTD HTML..." "URL">— references a public DTD.
XSD (XML Schema Definition): More expressive; supports data types (integer, date, regex patterns).
<!-- students.xsd -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="students">
<xs:complexType>
<xs:sequence>
<xs:element name="student" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="major" type="xs:string"/>
</xs:sequence>
<xs:attribute name="id" type="xs:integer" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
3.6 XSD Simple Types, Complex Types, and Attributes
Simple types: Elements or attributes containing only text. Can be restricted:
<xs:simpleType name="GradeType">
<xs:restriction base="xs:string">
<xs:enumeration value="A"/>
<xs:enumeration value="B"/>
<xs:enumeration value="C"/>
</xs:restriction>
</xs:simpleType>
Facets restrict simple types: minLength, maxLength, pattern, minInclusive, maxInclusive, enumeration, totalDigits, fractionDigits.
Default and Fixed values:
<xs:element name="major" type="xs:string" default="BCA"/>
<xs:element name="currency" type="xs:string" fixed="NPR"/>
<!-- default: used when element is present but empty -->
<!-- fixed: value cannot be changed; always has this value -->
Complex types: Elements containing child elements or attributes.
<xs:sequence>— children must appear in order.<xs:all>— children can appear in any order.<xs:choice>— only one of the listed children may appear.
3.7 Occurrence Indicators
| Indicator | Meaning | Default |
|---|---|---|
minOccurs="0" |
Element is optional | 1 |
maxOccurs="unbounded" |
Unlimited repetitions | 1 |
minOccurs="1" maxOccurs="1" |
Exactly once | Required once |
<xs:element name="phone" minOccurs="0" maxOccurs="3"/>
<!-- phone is optional and can appear up to 3 times -->
3.8 XSL/XSLT
XSLT (XSL Transformations) transforms an XML document into another XML document, HTML, or plain text using a stylesheet.
<!-- students.xsl -->
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html><body>
<table border="1">
<xsl:for-each select="students/student">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="major"/></td>
</tr>
</xsl:for-each>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet>
Key XSLT instructions:
| Element | Purpose |
|---|---|
<xsl:template match="..."> |
Rule to apply when the XPath expression matches |
<xsl:for-each select="..."> |
Loop over selected nodes |
<xsl:value-of select="..."> |
Output text value of a node |
<xsl:if test="..."> |
Conditional output |
<xsl:choose> / <xsl:when> / <xsl:otherwise> |
Switch-like branching |
<xsl:sort select="..."> |
Sort during for-each |
3.9 XPath
XPath is a query language for selecting nodes from an XML document, used inside XSLT and XQuery.
| XPath Expression | Selects |
|---|---|
/students |
Root element students |
/students/student |
All student children of students |
//name |
All name elements anywhere in the document |
student[@id='101'] |
Student with attribute id=101 |
student[1] |
First student element (1-indexed) |
student[last()] |
Last student element |
student/name/text() |
Text content of name inside student |
@id |
The id attribute of the current node |
3.10 XQuery
XQuery queries XML data using FLWOR expressions (For, Let, Where, Order by, Return):
for $s in /students/student
where $s/marks > 80
order by $s/name
return <result>{$s/name}</result>
This selects all students with marks above 80, sorts by name, and wraps each name in a <result> element.
3.11 SAX and DOM Parsers
| Feature | SAX (Simple API for XML) | DOM (Document Object Model) |
|---|---|---|
| Approach | Event-based; reads sequentially | Tree-based; loads entire document into memory |
| Memory | Low — processes one event at a time | High — entire tree in RAM |
| Speed | Fast for large documents | Slower for large documents |
| Navigation | Forward only; cannot go back | Random access to any node |
| Modification | Cannot modify the document | Can add, change, remove nodes |
| Use case | Large XML files; read-only processing | Smaller files; needs editing or random access |
DOM in browser JavaScript (HTML DOM):
// Select an element by ID
let heading = document.getElementById("title");
// Change its text
heading.textContent = "Welcome to BCA Nepal";
// Create and add a new element
let para = document.createElement("p");
para.textContent = "New paragraph.";
document.body.appendChild(para);
3.12 Creating XML Documents and Parsers
Creating an XML document programmatically (DOM, pseudocode):
doc = createDocument("students")
root = doc.createElement("student")
root.setAttribute("id", "101")
nameEl = doc.createElement("name")
nameEl.setTextContent("Sita")
root.appendChild(nameEl)
doc.getRoot().appendChild(root)
Common mistakes:
- Forgetting to close tags or nest them correctly (not well-formed)
- Using reserved characters directly instead of entity references
- Not declaring a namespace when combining XML vocabularies
- Parsing XML with string processing instead of a proper parser (fragile and insecure)
Key Terms — Unit 3
- XML — eXtensible Markup Language; data-focused markup
- Well-formed — syntactically valid XML (closed tags, one root, quoted attributes)
- Valid — well-formed AND conforming to a DTD or XSD schema
- XPath — query language for selecting XML nodes
- XSLT — stylesheet language transforming XML to other formats
- SAX — event-based XML parser; memory efficient
- DOM — tree-based XML/HTML parser; allows random access and modification
Unit 4: The Server Tier
Teaching hours: 8
4.1 Web Server Concept
A web server is software (and the hardware it runs on) that receives HTTP requests from clients (browsers) and returns HTTP responses. The most common web servers are Apache HTTP Server, Nginx, and Microsoft IIS.
How an HTTP request is handled:
sequenceDiagram
participant B as Browser
participant W as Web Server
participant A as App Server
participant D as Database
B->>W: GET /students HTTP/1.1
W->>A: Forward dynamic request
A->>D: SELECT * FROM Student
D-->>A: Result rows
A-->>W: Generated HTML
W-->>B: HTTP 200 OK + HTML
A browser request for a dynamic page travels from the web server to the application server, which queries the database and returns generated HTML. The web server delivers it to the browser.
Static content (HTML, CSS, images) is served directly by the web server.
Dynamic content requires the application server to generate HTML from templates and data.
4.2 Creating Dynamic Content
A static page has the same content for all users. A dynamic page is generated per-request, drawing data from databases, user sessions, or APIs.
Server-side technologies:
| Technology | Language | Description |
|---|---|---|
| PHP | PHP | Most widely used; embedded in HTML |
| JSP | Java | Java Servlet Pages; compiled to Java |
| ASP.NET | C# | Microsoft's web framework |
| Django | Python | High-level framework; MVC-ish |
| Node.js | JavaScript | Server-side JS; non-blocking I/O |
Simple PHP example:
<?php
$name = "Sita";
echo "<h1>Welcome, $name</h1>";
// Dynamic content from database
$result = $db->query("SELECT * FROM Student");
while ($row = $result->fetch_assoc()) {
echo "<p>" . htmlspecialchars($row['Name']) . "</p>";
// htmlspecialchars: prevents XSS by encoding HTML special chars
}
?>
4.3 Using Control Flow to Control Dynamic Content Generation
Control flow directs which parts of the page are rendered based on conditions or loops.
<?php
// Conditional: show admin panel only to admins
if ($user['role'] === 'admin') {
echo "<a href='/admin'>Admin Panel</a>";
} else {
echo "<p>Welcome, " . htmlspecialchars($user['name']) . "</p>";
}
// Loop: generate a table from database results
echo "<table><tr><th>Name</th><th>Major</th></tr>";
foreach ($students as $s) {
echo "<tr><td>" . htmlspecialchars($s['name']) . "</td>"
. "<td>" . htmlspecialchars($s['major']) . "</td></tr>";
}
echo "</table>";
?>
4.4 Sessions and State
HTTP is stateless. A session is a server-side mechanism to track user state across multiple requests.
How sessions work:
- User logs in → server creates a session and stores user data server-side.
- Server sends a session ID in a cookie to the browser.
- On subsequent requests, the browser sends the cookie.
- Server looks up the session using the ID and retrieves stored state.
// Start or resume a session
session_start();
// Store data in the session
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
// Read from session
echo "Welcome, " . $_SESSION['username'];
// Destroy the session on logout
session_destroy();
Cookies vs. Sessions:
| Feature | Cookie | Session |
|---|---|---|
| Storage | Browser (client-side) | Server (server-side) |
| Security | Less secure (can be tampered with) | More secure |
| Expiry | Set by the server; persists after browser close | Typically expires after inactivity |
| Data size | Limited (~4KB) | Unlimited (bounded by server memory) |
| Use case | Remember preferences, tracking | Authentication state |
4.5 Error Handling
Proper error handling prevents exposing sensitive information and provides a good user experience.
// Set error reporting level
error_reporting(E_ALL); // during development
error_reporting(0); // in production (suppress display)
ini_set('display_errors', 0); // never show errors to users
ini_set('log_errors', 1); // but log them to file
// Try-catch (PHP 5+)
try {
$pdo->query("SELECT * FROM non_existent_table");
} catch (PDOException $e) {
error_log($e->getMessage()); // log internally
echo "Service temporarily unavailable."; // show user-friendly message
}
Golden rule: Log the full error server-side; show only a generic message to users. Stack traces and database error messages expose system internals to attackers.
4.6 Architecting Web Applications
MVC (Model-View-Controller): A common pattern for organizing web application code.
- Model — data access, business logic (talks to database)
- View — templates, HTML generation (what the user sees)
- Controller — handles requests, calls the model, passes data to the view
Benefits: Separation of concerns; easier testing; multiple views for the same model (HTML + JSON API).
4.7 Tag Libraries
A tag library (custom tags) allows server-side logic to be expressed as custom HTML-like tags in templates, keeping templates readable.
JSP Tag Library example (JSTL):
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<table>
<c:forEach items="${students}" var="s">
<tr>
<td>${s.name}</td>
<td>${s.major}</td>
</tr>
</c:forEach>
</table>
<c:forEach> replaces a Java for-loop inside JSP. The template remains readable even without deep Java knowledge.
Writing tag libraries: Java custom tags implement Tag or SimpleTag interfaces and register in a TLD (Tag Library Descriptor) XML file.
Key Terms — Unit 4
- Web server — software serving HTTP requests (Apache, Nginx, IIS)
- Dynamic content — generated per-request using server-side code
- Session — server-side state linked to a client via a cookie session ID
- MVC — Model-View-Controller architectural pattern
- Tag library — custom HTML-like tags that invoke server-side logic
Unit 5: Introduction to Advanced Server-Side Issues
Teaching hours: 9
5.1 Database Connectivity
Server-side languages connect to databases using drivers or connection libraries. The process:
- Open a connection with server address, port, database name, username, password.
- Prepare and execute SQL statements.
- Process results.
- Close the connection.
PHP PDO (PHP Data Objects):
// Connect (using PDO for security)
$pdo = new PDO(
"mysql:host=localhost;dbname=CollegeDB;charset=utf8mb4",
"dbuser", // username
"secretpassword" // password
);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Parameterized query (prevents SQL injection)
$stmt = $pdo->prepare("SELECT * FROM Student WHERE Major = :major");
$stmt->execute([':major' => 'BCA']); // :major is replaced safely
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Close connection
$pdo = null;
Always use parameterized queries (prepared statements). Never concatenate user input directly into SQL:
// DANGEROUS — vulnerable to SQL injection:
$sql = "SELECT * FROM Student WHERE Name = '" . $_GET['name'] . "'";
// If user enters: ' OR '1'='1
// Query becomes: SELECT * FROM Student WHERE Name = '' OR '1'='1'
// This returns ALL students — bypassing authentication or data controls.
5.2 SQL Statements in Server-Side Code
SELECT: Retrieve and display data.
$stmt = $pdo->prepare("SELECT StudentID, Name FROM Student WHERE Major = ?");
$stmt->execute(['BCA']);
while ($row = $stmt->fetch()) {
echo $row['Name'] . "<br>";
}
INSERT: Add new data from a form submission.
$stmt = $pdo->prepare(
"INSERT INTO Student (StudentID, Name, Major) VALUES (?, ?, ?)"
);
$stmt->execute([$id, $name, $major]);
UPDATE: Modify existing data.
$stmt = $pdo->prepare(
"UPDATE Student SET Major = ? WHERE StudentID = ?"
);
$stmt->execute([$newMajor, $id]);
DELETE: Remove data.
$stmt = $pdo->prepare("DELETE FROM Student WHERE StudentID = ?");
$stmt->execute([$id]);
Always validate and sanitize input before using it in SQL or displaying it in HTML.
5.3 Authentication
Authentication verifies the identity of a user.
Anonymous Access
Allows users to access content without logging in. Appropriate for public pages.
Authentication by IP Address and Domain
Restrict access to requests from specific IP ranges or domains. Configured in web server settings (Apache .htaccess, Nginx allow/deny). Useful for internal admin tools.
Integrated Windows Authentication
Used in Microsoft environments (IIS). The browser sends the user's Windows credentials automatically — no login form needed. Appropriate for intranet applications.
Form-Based Authentication (most common for web apps):
// Login form submission
$username = $_POST['username'];
$password = $_POST['password'];
// Look up user in database
$stmt = $pdo->prepare("SELECT UserID, PasswordHash FROM Users WHERE Username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();
// Verify password with hash comparison (NEVER store plain-text passwords)
if ($user && password_verify($password, $user['PasswordHash'])) {
session_start();
$_SESSION['user_id'] = $user['UserID'];
header("Location: dashboard.php");
} else {
echo "Invalid credentials.";
}
Security rules:
- Never store plain-text passwords. Use
password_hash()with bcrypt. - Use HTTPS so passwords travel encrypted.
- Implement rate limiting and account lockout to resist brute-force attacks.
5.4 Cookies
A cookie is a small piece of data the server sends to the browser, which stores it and sends it back with subsequent requests to the same domain.
Setting a cookie (PHP):
// Name, value, expiry time, path, domain, secure, httponly
setcookie(
"theme", // name
"dark", // value
time() + 86400, // expiry: 1 day from now (Unix timestamp)
"/", // path: accessible from entire site
"", // domain: current domain
true, // secure: only send over HTTPS
true // httponly: not accessible by JavaScript (prevents XSS theft)
);
Reading a cookie:
$theme = $_COOKIE['theme'] ?? 'light'; // ?? 'light' is the default if not set
Deleting a cookie: Set expiry to a past time:
setcookie("theme", "", time() - 3600, "/");
Security flags:
Secure— only sent over HTTPS; prevents interception on insecure networks.HttpOnly— not readable by JavaScript; prevents XSS attacks from stealing cookies.SameSite— controls cross-site cookie sending; prevents CSRF attacks.
5.5 File Handling
Server-side code reads configuration files, writes logs, processes uploads, and generates downloadable files.
// Read a file
$content = file_get_contents("data/config.txt");
// Write to a file (overwrite)
file_put_contents("logs/access.log", $entry, FILE_APPEND); // FILE_APPEND appends
// Without FILE_APPEND: overwrites the file
// Open, read line by line, close
$fh = fopen("students.csv", "r"); // r = read; w = write; a = append; r+ = read+write
while (($line = fgets($fh)) !== false) {
echo htmlspecialchars($line) . "<br>";
}
fclose($fh);
File upload handling:
// HTML form must have enctype="multipart/form-data"
$tmpPath = $_FILES['resume']['tmp_name']; // temp location on server
$origName = basename($_FILES['resume']['name']); // original filename
$size = $_FILES['resume']['size'];
$error = $_FILES['resume']['error'];
if ($error === UPLOAD_ERR_OK && $size < 2 * 1024 * 1024) {
$safeName = preg_replace('/[^a-zA-Z0-9._-]/', '', $origName); // sanitize
move_uploaded_file($tmpPath, "uploads/" . $safeName);
}
Security: Never trust the client-supplied filename. Sanitize it, check the MIME type server-side, and store uploads outside the web root to prevent direct execution.
5.6 Form Handling
Form handling receives data submitted by an HTML form, validates it, and processes it.
// Receive POST data
$name = trim($_POST['name'] ?? ''); // trim removes leading/trailing whitespace
$email = trim($_POST['email'] ?? '');
$age = (int)($_POST['age'] ?? 0); // cast to int; prevents string injection
// Server-side validation
$errors = [];
if (empty($name)) $errors[] = "Name is required.";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email.";
if ($age < 16 || $age > 100) $errors[] = "Age must be 16–100.";
if (empty($errors)) {
// Process data: insert to DB, send email, etc.
$stmt = $pdo->prepare("INSERT INTO Registrations (Name, Email, Age) VALUES (?,?,?)");
$stmt->execute([$name, $email, $age]);
echo "Registration successful.";
} else {
foreach ($errors as $e) echo "<p style='color:red'>$e</p>";
}
Key functions:
trim()— removes leading/trailing whitespacehtmlspecialchars()— converts<,>,&,"to HTML entities; prevents XSSfilter_var(value, FILTER_VALIDATE_*)— validates email, URL, int, float formatsstrip_tags()— removes HTML tags from input
Key Terms — Unit 5
- SQL injection — attacker inserts SQL into user input to manipulate queries
- Prepared statement / parameterized query — prevents SQL injection
- Cookie — small client-stored data sent with every request
HttpOnly/Securecookie flags — prevent XSS and interception- Session — server-side state; identified by a session cookie
- XSS — Cross-Site Scripting; attacker injects scripts into pages viewed by other users
htmlspecialchars()— encodes special HTML characters to prevent XSS
Detailed Practice Questions and Answer Key
Q1. Write an HTML form for a student registration with fields: name (text), email, gender (radio), course (select), and a submit button. Validate required fields with HTML5 attributes.
Answer:
<form action="register.php" method="POST">
<label>Name: <input type="text" name="name" required minlength="2"></label>
<label>Email: <input type="email" name="email" required></label>
<fieldset>
<legend>Gender</legend>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
</fieldset>
<label>Course:
<select name="course" required>
<option value="">-- Select --</option>
<option value="bca">BCA</option>
<option value="bsc">BSc</option>
</select>
</label>
<button type="submit">Register</button>
</form>
Q2. A website stores student data in XML. Write an XML document, an XSD snippet to validate it, and an XPath expression to select students with marks above 75.
Answer (XML):
<?xml version="1.0"?>
<students>
<student id="101"><name>Sita</name><marks>85</marks></student>
<student id="102"><name>Ram</name><marks>70</marks></student>
</students>
XSD snippet: Element marks defined as type="xs:integer" with minInclusive value="0" and maxInclusive value="100".
XPath: //student[marks > 75] — selects all student elements where the marks child value exceeds 75. Result: student id="101" (Sita, 85).
Q3. Why should form passwords never be stored in plain text? How should they be stored?
Answer: Plain-text storage means if the database is compromised, every user's password is immediately exposed. Passwords must be hashed with a slow, salted algorithm such as bcrypt (PHP's password_hash()). A hash is one-way — the original password cannot be recovered. During login, the submitted password is hashed and compared with the stored hash using password_verify(). Even if an attacker steals the hash, cracking it is computationally expensive.
Q4. Explain the difference between SAX and DOM parsing. When would you use each?
Answer: SAX is event-driven: it reads the XML sequentially and fires events (startElement, endElement, characters) as it encounters each piece. It never loads the full document into memory, making it suitable for very large XML files. It is read-only and forward-only. DOM loads the entire document into a tree in memory, allowing random access and modification of any node. Use SAX when processing large XML files where you only need to read once. Use DOM when you need to navigate, search, or modify the document structure.
References
- Earlier TU BCA syllabus compilation — CACS205, PDF p. 52–55
Source: the course outline
sourceHash:sha256:d126d513c1051b176b03e56e067608546786d279b596b7b431ecff4d944496cb - TU BCA 2025 mapping — BCA203 → CACS205 (provisional reuse)
Source:reports/syllabus-scrape/mapping-verification-2025.json