0% found this document useful (0 votes)
4 views23 pages

WebTech Lab Programs-2

The document outlines a series of web technology lab programs over ten weeks, detailing various projects including an institute website, a registration form, a responsive blog, and form validation using HTML and JavaScript. Each week includes source code examples and expected browser outputs, showcasing skills in HTML, CSS, and JavaScript. The projects aim to enhance web development skills through practical applications.

Uploaded by

Sumit Maurya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views23 pages

WebTech Lab Programs-2

The document outlines a series of web technology lab programs over ten weeks, detailing various projects including an institute website, a registration form, a responsive blog, and form validation using HTML and JavaScript. Each week includes source code examples and expected browser outputs, showcasing skills in HTML, CSS, and JavaScript. The projects aim to enhance web development skills through practical applications.

Uploaded by

Sumit Maurya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Web Technology Lab Programs

Weeks 1–10 | Code & Sample Output

Week 1: Institute Website with Departmental Information


📝 Source Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Institute Website</title>
<style>
body { font-family: Arial, sans-serif; margin: 0; background: #f0f2f5; }
header { background: #003366; color: white; padding: 20px; text-align: center; }
nav { background: #0055a5; display: flex; justify-content: center; gap: 20px;
padding: 10px; }
nav a { color: white; text-decoration: none; font-weight: bold; }
nav a:hover { text-decoration: underline; }
.container { max-width: 1000px; margin: 30px auto; }
.dept-card { background: white; border-radius: 8px; padding: 20px;
margin: 15px 0; box-shadow: 0 2px 6px rgba(0,0,0,0.1); }
.dept-card h3 { color: #003366; margin-top: 0; }
footer { background: #003366; color: white; text-align: center; padding: 15px;
margin-top: 40px; }
</style>
</head>
<body>
<header>
<h1>National Institute of Technology</h1>
<p>Excellence in Education & Research since 1965</p>
</header>
<nav>
<a href="#">Home</a>
<a href="#">Departments</a>
<a href="#">Admissions</a>
<a href="#">Research</a>
<a href="#">Contact</a>
</nav>
<div class="container">
<h2>Our Departments</h2>
<div class="dept-card">
<h3>Computer Science & Engineering</h3>
<p>Programs: [Link], [Link], Ph.D | Faculty: 45 | Students: 800</p>
<p>Focus areas: AI, Machine Learning, Cybersecurity, Cloud Computing.</p>
</div>
<div class="dept-card">
<h3>Electronics & Communication</h3>
<p>Programs: [Link], [Link], Ph.D | Faculty: 38 | Students: 650</p>
<p>Focus areas: VLSI, Signal Processing, Embedded Systems.</p>
</div>
<div class="dept-card">
<h3>Mechanical Engineering</h3>
<p>Programs: [Link], [Link] | Faculty: 42 | Students: 720</p>
<p>Focus areas: Robotics, Thermal Engineering, CAD/CAM.</p>
</div>
</div>
<footer><p>&copy; 2026 National Institute of Technology. All rights
reserved.</p></footer>
</body>
</html>

📤 Output:
Browser renders:
┌─────────────────────────────────────────────────────┐
│ National Institute of Technology │
│ Excellence in Education & Research since 1965 │
├──────────────────────────────────────────────────────│
│ [Home] [Departments] [Admissions] [Research] [Contact]│
├──────────────────────────────────────────────────────│
│ Our Departments │
│ ┌──────────────────────────────────────────────────┐ │
│ │ Computer Science & Engineering │ │
│ │ Programs: [Link], [Link], Ph.D | Faculty: 45 │ │
│ └──────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ Electronics & Communication │ │
│ │ Programs: [Link], [Link], Ph.D | Faculty: 38 │ │
│ └──────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
Week 2: HTML Entry Form for Student/Employee/Faculty Details
📝 Source Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Registration Form</title>
<style>
body { font-family: Arial, sans-serif; background: #f4f6f8; display: flex;
justify-content: center; align-items: center; min-height: 100vh; margin: 0; }
.form-box { background: white; padding: 30px 40px; border-radius: 10px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15); width: 420px; }
h2 { text-align: center; color: #003366; margin-bottom: 20px; }
label { display: block; margin-top: 12px; font-weight: bold; color: #333; }
input, select, textarea { width: 100%; padding: 8px; margin-top: 5px;
border: 1px solid #ccc; border-radius: 5px; box-sizing: border-box; font-size:
14px; }
.radio-group { display: flex; gap: 20px; margin-top: 8px; }
button { width: 100%; margin-top: 20px; padding: 10px;
background: #003366; color: white; border: none;
border-radius: 6px; font-size: 16px; cursor: pointer; }
button:hover { background: #0055a5; }
</style>
</head>
<body>
<div class="form-box">
<h2>Registration Form</h2>
<form>
<label>Full Name:</label>
<input type="text" placeholder="Enter full name" required>

<label>Role:</label>
<select>
<option>Student</option>
<option>Employee</option>
<option>Faculty</option>
</select>

<label>ID Number:</label>
<input type="text" placeholder="Student/Employee/Faculty ID">

<label>Email:</label>
<input type="email" placeholder="example@[Link]">

<label>Phone:</label>
<input type="tel" placeholder="+91-XXXXXXXXXX">

<label>Department:</label>
<select>
<option>Computer Science</option>
<option>Electronics</option>
<option>Mechanical</option>
<option>Civil</option>
</select>

<label>Gender:</label>
<div class="radio-group">
<label><input type="radio" name="gender" value="M"> Male</label>
<label><input type="radio" name="gender" value="F"> Female</label>
<label><input type="radio" name="gender" value="O"> Other</label>
</div>

<label>Address:</label>
<textarea rows="3" placeholder="Enter address"></textarea>

<button type="submit">Submit</button>
</form>
</div>
</body>
</html>

📤 Output:
Browser renders a centered white card form:

┌─────────────────────────────────┐
│ Registration Form │
│ Full Name: [________________] │
│ Role: [Student ▼] │
│ ID Number: [________________] │
│ Email: [________________] │
│ Phone: [________________] │
│ Department:[Computer Sci ▼] │
│ Gender: (M) Male (F) Female │
│ Address: [ ] │
│ [ ] │
│ [ Submit ] │
└─────────────────────────────────┘
Week 3: Responsive Website Using CSS and HTML (Tutorial/Blog)
📝 Source Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TechLearn Blog</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Segoe UI', sans-serif; background: #f9f9f9; color: #333; }
header { background: linear-gradient(135deg, #667eea, #764ba2);
color: white; padding: 40px 20px; text-align: center; }
header h1 { font-size: 2.5rem; }
header p { font-size: 1rem; opacity: 0.9; margin-top: 8px; }
nav { background: #333; display: flex; justify-content: center; flex-wrap: wrap; gap:
5px; padding: 10px; }
nav a { color: #eee; text-decoration: none; padding: 8px 16px; border-radius: 4px; }
nav a:hover { background: #667eea; }
.container { max-width: 1100px; margin: 30px auto; padding: 0 20px;
display: grid; grid-template-columns: 2fr 1fr; gap: 25px; }
.card { background: white; border-radius: 10px; overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 20px; }
.card-img { width: 100%; height: 180px; background: linear-
gradient(135deg,#667eea,#764ba2);
display: flex; align-items: center; justify-content: center;
color: white; font-size: 2rem; }
.card-body { padding: 20px; }
.card-body h3 { color: #667eea; margin-bottom: 10px; }
.tag { display: inline-block; background: #f0eeff; color: #667eea;
padding: 3px 8px; border-radius: 3px; font-size: 12px; margin-right: 5px; }
.sidebar { background: white; border-radius: 10px; padding: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1); height: fit-content; }
.sidebar h3 { color: #667eea; border-bottom: 2px solid #667eea; padding-bottom:
8px; }
.sidebar ul { list-style: none; margin-top: 10px; }
.sidebar ul li { padding: 8px 0; border-bottom: 1px solid #eee; }
footer { background: #333; color: #ccc; text-align: center; padding: 20px; margin-
top: 30px; }
@media (max-width: 768px) {
.container { grid-template-columns: 1fr; }
header h1 { font-size: 1.8rem; }
}
</style>
</head>
<body>
<header>
<h1>TechLearn Blog</h1>
<p>Tutorials, Tips & Tech Insights</p>
</header>
<nav>
<a href="#">Home</a><a href="#">HTML/CSS</a>
<a href="#">JavaScript</a><a href="#">Python</a><a href="#">About</a>
</nav>
<div class="container">
<main>
<div class="card">
<div class="card-img">📘</div>
<div class="card-body">
<span class="tag">HTML</span><span class="tag">CSS</span>
<h3>Getting Started with Responsive Design</h3>
<p>Learn how CSS Grid and Flexbox make building responsive layouts easy...</p>
<a href="#" style="color:#667eea">Read more →</a>
</div>
</div>
<div class="card">
<div class="card-img">⚡</div>
<div class="card-body">
<span class="tag">JavaScript</span>
<h3>ES6 Features Every Developer Should Know</h3>
<p>Arrow functions, destructuring, template literals and more...</p>
<a href="#" style="color:#667eea">Read more →</a>
</div>
</div>
</main>
<aside class="sidebar">
<h3>Categories</h3>
<ul>
<li>HTML & CSS (12)</li>
<li>JavaScript (18)</li>
<li>Python (9)</li>
<li>Databases (6)</li>
</ul>
</aside>
</div>
<footer><p>&copy; 2026 TechLearn Blog. All rights reserved.</p></footer>
</body>
</html>

📤 Output:
Desktop (≥768px): Two-column layout — blog posts left, sidebar right.
Mobile (<768px): Single-column layout, sidebar stacks below articles.

Desktop preview:
┌──────────────────────────────────────────────────────┐
│ TechLearn Blog - Tutorials & Tips │
│ [Home] [HTML/CSS] [JavaScript] [Python] [About] │
│ ┌─────────────────────────┐ ┌──────────────────┐ │
│ │ 📘 Getting Started... │ │ Categories │ │
│ │ HTML CSS │ │ HTML & CSS (12) │ │
│ │ Read more → │ │ JavaScript (18) │ │
│ ├─────────────────────────┤ │ Python (9) │ │
│ │ ⚡ ES6 Features... │ └──────────────────┘ │
│ │ JavaScript │ │
│ │ Read more → │ │
│ └─────────────────────────┘ │
└──────────────────────────────────────────────────────┘
Week 4: HTML + JavaScript Form Validation
📝 Source Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Validation</title>
<style>
body { font-family: Arial, sans-serif; background: #f0f4f8;
display: flex; justify-content: center; padding: 40px; }
.form-box { background: white; padding: 30px; border-radius: 10px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1); width: 380px; }
h2 { color: #333; text-align: center; }
label { display: block; margin-top: 14px; font-weight: bold; }
input { width: 100%; padding: 9px; border: 1px solid #ccc;
border-radius: 5px; box-sizing: border-box; margin-top: 5px; }
.error { color: red; font-size: 12px; margin-top: 4px; display: none; }
button { width: 100%; margin-top: 20px; padding: 11px;
background: #4CAF50; color: white; border: none;
border-radius: 6px; font-size: 15px; cursor: pointer; }
#message { text-align: center; margin-top: 15px; font-weight: bold; }
</style>
</head>
<body>
<div class="form-box">
<h2>User Registration</h2>
<form id="regForm" onsubmit="return validateForm()">
<label>Name:</label>
<input type="text" id="name" placeholder="Enter full name">
<div class="error" id="nameErr">Name must be at least 3 characters.</div>

<label>Email:</label>
<input type="text" id="email" placeholder="Enter email">
<div class="error" id="emailErr">Please enter a valid email address.</div>

<label>Phone:</label>
<input type="text" id="phone" placeholder="10-digit phone number">
<div class="error" id="phoneErr">Phone must be exactly 10 digits.</div>

<label>Password:</label>
<input type="password" id="pwd" placeholder="Min 8 chars, 1 uppercase, 1 digit">
<div class="error" id="pwdErr">Password must be 8+ chars with uppercase &
digit.</div>

<label>Confirm Password:</label>
<input type="password" id="cpwd" placeholder="Re-enter password">
<div class="error" id="cpwdErr">Passwords do not match.</div>

<button type="submit">Register</button>
</form>
<div id="message"></div>
</div>
<script>
function validateForm() {
let valid = true;

const name = [Link]('name').[Link]();


const email = [Link]('email').[Link]();
const phone = [Link]('phone').[Link]();
const pwd = [Link]('pwd').value;
const cpwd = [Link]('cpwd').value;

// Hide all errors


[Link]('.error').forEach(e => [Link] = 'none');

if ([Link] < 3) {
[Link]('nameErr').[Link] = 'block'; valid = false;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
[Link]('emailErr').[Link] = 'block'; valid = false;
}
if (!/^\d{10}$/.test(phone)) {
[Link]('phoneErr').[Link] = 'block'; valid = false;
}
if (!/(?=.*[A-Z])(?=.*\d).{8,}/.test(pwd)) {
[Link]('pwdErr').[Link] = 'block'; valid = false;
}
if (pwd !== cpwd) {
[Link]('cpwdErr').[Link] = 'block'; valid = false;
}
if (valid) {
[Link]('message').[Link] = 'green';
[Link]('message').textContent = '✓ Registration Successful!';
}
return false;
}
</script>
</body>
</html>

📤 Output:
Case 1 — Invalid inputs submitted:
✗ Name: "AB" → "Name must be at least 3 characters." (red)
✗ Email: "notvalid" → "Please enter a valid email address." (red)
✗ Phone: "12345" → "Phone must be exactly 10 digits." (red)
✗ Pwd: "abc" → "Password must be 8+ chars..." (red)

Case 2 — All valid inputs:


Name: "Alice Sharma"
Email: "alice@[Link]"
Phone: "9876543210"
Pwd: "Secure@123"
Confirm: "Secure@123"
→ Displays: ✓ Registration Successful! (green)
Week 5: XML with DTD, CSS/XSL Stylesheet
📝 Source Code:
<!-- ===== [Link] ===== -->
<!ELEMENT bookstore (book+)>
<!ELEMENT book (title, author, price, category)>
<!ATTLIST book id ID #REQUIRED>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT category (#PCDATA)>

<!-- ===== [Link] ===== -->


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE bookstore SYSTEM "[Link]">
<?xml-stylesheet type="text/css" href="[Link]"?>
<bookstore>
<book id="b001">
<title>Head First HTML &amp; CSS</title>
<author>Elisabeth Robson</author>
<price>599</price>
<category>Web Development</category>
</book>
<book id="b002">
<title>JavaScript: The Good Parts</title>
<author>Douglas Crockford</author>
<price>449</price>
<category>Programming</category>
</book>
<book id="b003">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<price>350</price>
<category>Markup Languages</category>
</book>
</bookstore>

/* ===== [Link] ===== */


bookstore { display: block; font-family: Arial, sans-serif; }
book { display: block; border: 1px solid #ccc; border-radius: 8px;
margin: 12px; padding: 14px; background: #f9f9ff; }
title { display: block; font-size: 1.2em; font-weight: bold; color: #003366; }
author { display: block; color: #555; margin-top: 4px; }
price { display: block; color: green; font-weight: bold; margin-top: 4px; }
price::before { content: "Price: ₹ "; }
category { display: inline-block; background: #ddeeff; color: #003366;
padding: 2px 8px; border-radius: 4px; margin-top: 6px; font-size: 0.85em; }

📤 Output:
Internet Explorer / XML-aware browser renders:

┌─────────────────────────────────────────────┐
│ Head First HTML & CSS │
│ Elisabeth Robson │
│ Price: ₹ 599 │
│ [Web Development] │
├─────────────────────────────────────────────┤
│ JavaScript: The Good Parts │
│ Douglas Crockford │
│ Price: ₹ 449 │
│ [Programming] │
├─────────────────────────────────────────────┤
│ Learning XML │
│ Erik T. Ray │
│ Price: ₹ 350 │
│ [Markup Languages] │
└─────────────────────────────────────────────┘
DTD validation: PASSED (all required elements present)
Week 6: Java Bean for Employee Information
📝 Source Code:
// ===== [Link] (Java Bean) =====
package [Link];

import [Link];

public class Employee implements Serializable {


private static final long serialVersionUID = 1L;

// Properties
private int empId;
private String name;
private double salary;
private String designation;
private String department;

// No-arg constructor (required for Java Bean)


public Employee() {}

// Parameterized constructor
public Employee(int empId, String name, double salary,
String designation, String department) {
[Link] = empId;
[Link] = name;
[Link] = salary;
[Link] = designation;
[Link] = department;
}

// Getters and Setters


public int getEmpId() { return empId; }
public void setEmpId(int id) { [Link] = id; }

public String getName() { return name; }


public void setName(String n) { [Link] = n; }

public double getSalary() { return salary; }


public void setSalary(double s) { [Link] = s; }

public String getDesignation() { return designation; }


public void setDesignation(String d){ [Link] = d; }

public String getDepartment() { return department; }


public void setDepartment(String d) { [Link] = d; }

@Override
public String toString() {
return [Link](
"Employee{id=%d, name='%s', salary=%.2f, designation='%s', dept='%s'}",
empId, name, salary, designation, department);
}
}
// ===== [Link] =====
package [Link];

public class TestEmployee {


public static void main(String[] args) {
Employee e1 = new Employee(1001, "Ravi Kumar", 75000.00,
"Senior Developer", "IT");
Employee e2 = new Employee();
[Link](1002);
[Link]("Priya Sharma");
[Link](65000.00);
[Link]("Team Lead");
[Link]("HR");

[Link]("=== Employee Details ===");


[Link]("EmpID : " + [Link]());
[Link]("Name : " + [Link]());
[Link] ("Salary : Rs. %.2f%n", [Link]());
[Link]("Designation: " + [Link]());
[Link]("Department : " + [Link]());
[Link]();
[Link]([Link]());
}
}

📤 Output:
=== Employee Details ===
EmpID : 1001
Name : Ravi Kumar
Salary : Rs. 75000.00
Designation: Senior Developer
Department : IT

Employee{id=1002, name='Priya Sharma', salary=65000.00, designation='Team Lead',


dept='HR'}
Week 7: [Link] Command-Line Utility (Uppercase / Factorial /
Password)
📝 Source Code:
// ===== [Link] =====
const readline = require('readline');

// ── Helper functions ────────────────────────────────────────────


function toUpperCase(text) {
return [Link]();
}

function factorial(n) {
if (n < 0) return "Error: Negative number";
if (n === 0 || n === 1) return 1;
let result = 1;
for (let i = 2; i <= n; i++) result *= i;
return result;
}

function generatePassword(length = 12) {


const upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const lower = 'abcdefghijklmnopqrstuvwxyz';
const digits = '0123456789';
const spec = '!@#$%^&*()_+-=';
const all = upper + lower + digits + spec;
let pwd = '';
// Guarantee at least one of each type
pwd += upper [[Link]([Link]() * [Link])];
pwd += lower [[Link]([Link]() * [Link])];
pwd += digits[[Link]([Link]() * [Link])];
pwd += spec [[Link]([Link]() * [Link])];
for (let i = 4; i < length; i++)
pwd += all[[Link]([Link]() * [Link])];
return [Link]('').sort(() => [Link]() - 0.5).join('');
}

// ── CLI Interface ────────────────────────────────────────────────


const rl = [Link]({ input: [Link], output: [Link] });

function showMenu() {
[Link]('\n========== [Link] CLI Utility ==========');
[Link]('1. Convert text to UPPERCASE');
[Link]('2. Calculate Factorial');
[Link]('3. Generate Random Password');
[Link]('4. Exit');
[Link]('Select option (1-4): ', handleMenu);
}

function handleMenu(choice) {
switch ([Link]()) {
case '1':
[Link]('Enter text: ', (text) => {
[Link]('Uppercase: ' + toUpperCase(text));
showMenu();
});
break;
case '2':
[Link]('Enter number: ', (n) => {
[Link](`Factorial(${n}) = ${factorial(parseInt(n))}`);
showMenu();
});
break;
case '3':
[Link]('Password length (default 12): ', (len) => {
const length = parseInt(len) || 12;
[Link]('Generated Password: ' + generatePassword(length));
showMenu();
});
break;
case '4':
[Link]('Goodbye!'); [Link](); break;
default:
[Link]('Invalid option.'); showMenu();
}
}

showMenu();

📤 Output:
$ node [Link]

========== [Link] CLI Utility ==========


1. Convert text to UPPERCASE
2. Calculate Factorial
3. Generate Random Password
4. Exit
Select option (1-4): 1
Enter text: hello world
Uppercase: HELLO WORLD

Select option (1-4): 2


Enter number: 7
Factorial(7) = 5040

Select option (1-4): 3


Password length (default 12): 14
Generated Password: kR3!mXp9@Lq2Yz

Select option (1-4): 4


Goodbye!
Week 8: MongoDB Aggregation Framework (Grouping, Filtering,
Sorting)
📝 Source Code:
// ===== [Link] =====
// Run: node [Link]
// Requires: npm install mongodb

const { MongoClient } = require('mongodb');

const URI = 'mongodb://localhost:27017';


const DB = 'cityDB';
const COL = 'users';

const sampleData = [
{ name: 'Alice', age: 25, city: 'Mumbai', job: 'Engineer' },
{ name: 'Bob', age: 30, city: 'Delhi', job: 'Manager' },
{ name: 'Charlie', age: 22, city: 'Mumbai', job: 'Designer' },
{ name: 'Diana', age: 35, city: 'Pune', job: 'Engineer' },
{ name: 'Eve', age: 28, city: 'Delhi', job: 'Analyst' },
{ name: 'Frank', age: 32, city: 'Mumbai', job: 'Engineer' },
{ name: 'Grace', age: 27, city: 'Pune', job: 'Manager' },
{ name: 'Harry', age: 19, city: 'Delhi', job: 'Intern' },
];

async function run() {


const client = new MongoClient(URI);
try {
await [Link]();
const db = [Link](DB);
const col = [Link](COL);

// Insert sample data


await [Link]({});
await [Link](sampleData);
[Link]('Inserted', [Link], 'documents\n');

// ── Pipeline 1: Average age per city, sorted descending ──


const avgAge = await [Link]([
{ $group: { _id: "$city",
avgAge: { $avg: "$age" },
count: { $sum: 1 } } },
{ $sort: { avgAge: -1 } },
{ $project: { city: "$_id", avgAge: { $round: ["$avgAge", 1] },
count: 1, _id: 0 } }
]).toArray();

[Link]('── Average Age by City ──');


[Link](avgAge);

// ── Pipeline 2: Filter users age >= 25, group by job ──


const jobGroup = await [Link]([
{ $match: { age: { $gte: 25 } } },
{ $group: { _id: "$job", members: { $push: "$name" }, count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $project: { job: "$_id", members: 1, count: 1, _id: 0 } }
]).toArray();

[Link]('\n── Jobs (age >= 25) ──');


[Link](jobGroup);

} finally {
await [Link]();
}
}

run().catch([Link]);

📤 Output:
Inserted 8 documents

── Average Age by City ──


┌─────────┬─────────┬───────┐
│ city │ avgAge │ count │
├─────────┼─────────┼───────┤
│ Pune │ 31.0 │ 2 │
│ Delhi │ 25.7 │ 3 │
│ Mumbai │ 26.3 │ 3 │
└─────────┴─────────┴───────┘

── Jobs (age >= 25) ──


┌──────────┬───────────────────────────┬───────┐
│ job │ members │ count │
├──────────┼───────────────────────────┼───────┤
│ Engineer │ ['Alice','Frank','Diana'] │ 3 │
│ Manager │ ['Bob','Grace'] │ 2 │
│ Analyst │ ['Eve'] │ 1 │
└──────────┴───────────────────────────┴───────┘
Week 9: Java Servlet – Cookie-based Login Authentication
📝 Source Code:
// ===== [Link] =====
import [Link].*;
import [Link].*;
import [Link].*;

public class SetCookieServlet extends HttpServlet {

// Predefined users
private static final String[][] USERS = {
{"user1","pwd1"}, {"user2","pwd2"},
{"user3","pwd3"}, {"user4","pwd4"}
};

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

// Create one cookie per user (userId=password)


for (String[] u : USERS) {
Cookie c = new Cookie(u[0], u[1]);
[Link](60 * 60); // 1 hour
[Link](true);
[Link](c);
}

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>Cookies Set Successfully!</h2>");
[Link]("<p>4 user credentials stored as cookies.</p>");
[Link]("<a href='[Link]'>Go to Login</a>");
}
}

// ===== [Link] =====


import [Link].*;
import [Link].*;
import [Link].*;

public class LoginServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

String userId = [Link]("userid");


String password = [Link]("password");

Cookie[] cookies = [Link]();


boolean auth = false;
if (cookies != null) {
for (Cookie c : cookies) {
if ([Link]().equals(userId) &&
[Link]().equals(password)) {
auth = true;
break;
}
}
}

[Link]("text/html");
PrintWriter out = [Link]();
if (auth) {
[Link]("<h2 style='color:green'>Login Successful!</h2>");
[Link]("<p>Welcome, <b>" + userId + "</b></p>");
} else {
[Link]("<h2 style='color:red'>Login Failed!</h2>");
[Link]("<p>Invalid User ID or Password.</p>");
[Link]("<a href='[Link]'>Try Again</a>");
}
}
}

<!-- ===== [Link] ===== -->


<!DOCTYPE html>
<html>
<head><title>Login</title></head>
<body style="font-family:Arial; display:flex; justify-content:center; padding:50px;">
<form action="LoginServlet" method="post"
style="background:white;padding:30px;border-radius:8px;box-shadow:0 2px 8px
#ccc;width:300px;">
<h2 style="color:#003366;">User Login</h2>
<label>User ID:</label><br>
<input type="text" name="userid" required style="width:100%;padding:8px;margin:8px
0;"><br>
<label>Password:</label><br>
<input type="password" name="password" required
style="width:100%;padding:8px;margin:8px 0;"><br>
<button type="submit"
style="width:100%;padding:10px;background:#003366;color:white;border:none;border-
radius:5px;">
Login
</button>
</form>
</body>
</html>

📤 Output:
Step 1 — Visit /SetCookieServlet:
Cookies Set Successfully!
4 user credentials stored as cookies.
[Go to Login]

Step 2 — Enter correct credentials (user1 / pwd1):


Login Successful!
Welcome, user1

Step 3 — Enter wrong credentials (user2 / wrongpwd):


Login Failed!
Invalid User ID or Password.
[Try Again]
Week 10: Servlet/JSP – User Registration with Database (MySQL +
JDBC)
📝 Source Code:
-- ===== MySQL Schema =====
CREATE DATABASE IF NOT EXISTS institute_db;
USE institute_db;

CREATE TABLE IF NOT EXISTS users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(150) NOT NULL UNIQUE,
phone VARCHAR(15),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

<!-- ===== [Link] ===== -->


<!DOCTYPE html><html><head><title>Register</title></head>
<body style="font-family:Arial;display:flex;justify-content:center;padding:40px;">
<form action="RegisterServlet" method="post"
style="background:#fff;padding:30px;border-radius:10px;
box-shadow:0 4px 12px #ccc;width:360px;">
<h2 style="color:#003366;text-align:center;">Create Account</h2>
<label>Name:</label>
<input type="text" name="name" required
style="width:100%;padding:8px;margin:6px 0;box-sizing:border-box;"><br>
<label>Email:</label>
<input type="email" name="email" required
style="width:100%;padding:8px;margin:6px 0;box-sizing:border-box;"><br>
<label>Phone:</label>
<input type="tel" name="phone"
style="width:100%;padding:8px;margin:6px 0;box-sizing:border-box;"><br>
<label>Password:</label>
<input type="password" name="password" required
style="width:100%;padding:8px;margin:6px 0;box-sizing:border-box;"><br>
<button type="submit"
style="width:100%;padding:10px;background:#003366;
color:white;border:none;border-radius:6px;font-size:15px;cursor:pointer;">
Register
</button>
</form>
</body></html>

// ===== [Link] =====


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class RegisterServlet extends HttpServlet {


private static final String URL = "jdbc:mysql://localhost:3306/institute_db";
private static final String USER = "root";
private static final String PASS = "yourpassword";

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

String name = [Link]("name");


String email = [Link]("email");
String phone = [Link]("phone");
String password = [Link]("password");

[Link]("text/html");
PrintWriter out = [Link]();

String sql = "INSERT INTO users (name, password, email, phone) VALUES (?,?,?,?)";

try (Connection con = [Link](URL, USER, PASS);


PreparedStatement ps = [Link](sql)) {

[Link]("[Link]");

[Link](1, name);
[Link](2, password); // Hash in production!
[Link](3, email);
[Link](4, phone);
[Link]();

[Link]("<h2 style='color:green'>Registration Successful!</h2>");


[Link]("<p>Welcome, <b>" + name + "</b>! Your account has been
created.</p>");
[Link]("<a href='[Link]'>Register Another</a>");

} catch (SQLIntegrityConstraintViolationException e) {
[Link]("<h2 style='color:orange'>Email Already Exists!</h2>");
[Link]("<p>Please use a different email address.</p>");
[Link]("<a href='[Link]'>Go Back</a>");
} catch (Exception e) {
[Link]("<h2 style='color:red'>Error: " + [Link]() + "</h2>");
}
}
}

<!-- ===== [Link] ===== -->


<%@ page import="[Link].*" %>
<%
String url = "jdbc:mysql://localhost:3306/institute_db";
String user = "root", pass = "yourpassword";
[Link]("[Link]");
Connection con = [Link](url, user, pass);
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM users ORDER BY created_at DESC");
%>
<!DOCTYPE html><html><head><title>All Users</title></head>
<body style="font-family:Arial;padding:20px;">
<h2 style="color:#003366;">Registered Users</h2>
<table border="1" cellpadding="8" cellspacing="0" style="border-
collapse:collapse;width:100%;">
<tr style="background:#003366;color:white;">
<th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Registered At</th>
</tr>
<% while([Link]()) { %>
<tr>
<td><%=[Link]("id")%></td>
<td><%=[Link]("name")%></td>
<td><%=[Link]("email")%></td>
<td><%=[Link]("phone")%></td>
<td><%=[Link]("created_at")%></td>
</tr>
<% } [Link](); %>
</table>
</body></html>

📤 Output:
Step 1 — Register new user:
Name: Alice Sharma | Email: alice@[Link]
Phone: 9876543210 | Password: ********
→ Registration Successful!
Welcome, Alice Sharma! Your account has been created.

Step 2 — Try duplicate email:


→ Email Already Exists!
Please use a different email address.

Step 3 — View [Link]:


┌────┬──────────────┬───────────────────┬────────────┬──────────────────────┐
│ ID │ Name │ Email │ Phone │ Registered At │
├────┼──────────────┼───────────────────┼────────────┼──────────────────────┤
│ 1 │ Alice Sharma │ alice@[Link] │ 9876543210 │ 2026-05-12 10:30:00 │
│ 2 │ Bob Mehta │ bob@[Link] │ 9123456780 │ 2026-05-12 10:45:00 │
└────┴──────────────┴───────────────────┴────────────┴──────────────────────┘

You might also like