Q1:-Write HTML Program for designing your institute website.
Display departmental information of
your institute on the website.
HTML Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Institute Website</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
</head>
<body>
<!-- Header Section -->
<header>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#departments">Departments</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<!-- Home Section -->
<section id="home" class="section">
<h1>Welcome to XYZ Institute</h1>
<p>We offer high-quality education and research opportunities in various fields.</p>
</section>
<!-- Departments Section -->
<section id="departments" class="section">
<h2>Our Departments</h2>
<div class="department-list">
<div class="department" onclick="showInfo('computerScience')">
<h3>Computer Science</h3>
<p>Explore cutting-edge technology and computer science research.</p>
</div>
<div class="department" onclick="showInfo('mechanical')">
<h3>Mechanical Engineering</h3>
<p>Learn about mechanics, thermodynamics, and automation technologies.</p>
</div>
<div class="department" onclick="showInfo('civil')">
<h3>Civil Engineering</h3>
<p>Study the foundations of infrastructure development and design.</p>
</div>
<div class="department" onclick="showInfo('electrical')">
<h3>Electrical Engineering</h3>
<p>Discover the world of electrical systems and power generation.</p>
</div>
</div>
<!-- Department Information (Hidden by Default) -->
<div id="departmentInfo" class="department-info">
<h3>Department Information</h3>
<p id="departmentDetails">Click on a department to view more information.</p>
</div>
</section>
<!-- Contact Section -->
<section id="contact" class="section">
<h2>Contact Us</h2>
<p>For inquiries, please email us at <a
href="mailto:info@xyzinstitute.com">info@xyzinstitute.com</a></p>
</section>
<!-- Footer Section -->
<footer>
<p>© 2024 XYZ Institute. All Rights Reserved.</p>
</footer>
</body>
</html>
CSS Code:-
/* Reset some default browser styling */
*{
margin: 0;
padding: 0;
box-sizing: border-box;
/* Body Styling */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
color: #333;
/* Header Styling */
header {
background-color: #0044cc;
color: white;
padding: 10px 0;
text-align: center;
nav ul {
list-style-type: none;
nav ul li {
display: inline;
margin-right: 20px;
nav ul li a {
text-decoration: none;
color: white;
font-weight: bold;
/* Section Styling */
.section {
padding: 40px;
text-align: center;
#home {
background-color: #e0f7fa;
#departments {
background-color: #ffffff;
#contact {
background-color: #f4f4f4;
/* Department Styling */
.department-list {
display: flex;
justify-content: space-around;
flex-wrap: wrap;
margin-top: 20px;
.department {
background-color: #f0f0f0;
padding: 20px;
width: 250px;
margin: 10px;
cursor: pointer;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: transform 0.3s;
.department:hover {
transform: scale(1.05);
.department h3 {
margin-bottom: 10px;
/* Department Info Section Styling */
.department-info {
display: none;
background-color: #fff;
padding: 20px;
margin-top: 30px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
footer {
background-color: #0044cc;
color: white;
text-align: center;
padding: 10px;
margin-top: 40px;
JS Code:-
// JavaScript function to display department information dynamically
function showInfo(department) {
let departmentDetails = '';
if (department === 'computerScience') {
departmentDetails = 'The Computer Science Department offers programs in software
engineering, data science, AI, and more. We prepare students for a future in technology and
innovation.';
} else if (department === 'mechanical') {
departmentDetails = 'The Mechanical Engineering Department focuses on areas such as
thermodynamics, fluid mechanics, and robotics. Our students gain hands-on experience in industry-
standard tools and practices.';
} else if (department === 'civil') {
departmentDetails = 'The Civil Engineering Department provides education on structural design,
construction management, and environmental engineering. Our faculty are experts in infrastructure
development.';
} else if (department === 'electrical') {
departmentDetails = 'The Electrical Engineering Department specializes in power generation,
electronics, and automation. Our programs prepare students to meet the challenges of modern
electrical systems.';
// Display department info
document.getElementById('departmentInfo').style.display = 'block';
document.getElementById('departmentDetails').textContent = departmentDetails;
Q2:-Write HTML program to design an entry form student detail/employee
information/faculty/detail.
HTML Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Entry Form - Student/Employee/Faculty</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
</head>
<body>
<div class="form-container">
<h1>Enter Details</h1>
<!-- Form for Student/Employee/Faculty -->
<form id="entryForm" onsubmit="return validateForm(event)">
<div class="input-group">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" required placeholder="Enter full name">
</div>
<div class="input-group">
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" required placeholder="Enter email">
</div>
<div class="input-group">
<label for="contact">Contact Number:</label>
<input type="text" id="contact" name="contact" required placeholder="Enter contact
number">
</div>
<div class="input-group">
<label for="department">Department:</label>
<select id="department" name="department" required>
<option value="">Select Department</option>
<option value="computerScience">Computer Science</option>
<option value="mechanical">Mechanical Engineering</option>
<option value="civil">Civil Engineering</option>
<option value="electrical">Electrical Engineering</option>
</select>
</div>
<div class="input-group">
<label for="role">Role:</label>
<select id="role" name="role" required>
<option value="">Select Role</option>
<option value="student">Student</option>
<option value="employee">Employee</option>
<option value="faculty">Faculty</option>
</select>
</div>
<div id="extraField" class="input-group" style="display: none;">
<label for="experience">Experience (if applicable):</label>
<input type="number" id="experience" name="experience" placeholder="Enter years of
experience">
</div>
<button type="submit">Submit</button>
</form>
<div id="formOutput" class="form-output"></div>
</div>
</body>
</html>
CSS Code:-
/* Reset default styles */
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Body Styling */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
color: #333;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
/* Form Container Styling */
.form-container {
background-color: #ffffff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 400px;
/* Title Styling */
h1 {
text-align: center;
margin-bottom: 20px;
color: #333;
/* Input Group Styling */
.input-group {
margin-bottom: 15px;
.input-group label {
display: block;
margin-bottom: 5px;
.input-group input, .input-group select {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
.input-group input:focus, .input-group select:focus {
border-color: #007bff;
/* Button Styling */
button {
width: 100%;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
button:hover {
background-color: #0056b3;
/* Form Output Styling */
.form-output {
margin-top: 20px;
text-align: center;
font-size: 16px;
color: #333;
font-weight: bold;
JS Code:-
// JavaScript function to validate the form and show the experience field conditionally
function validateForm(event) {
event.preventDefault(); // Prevent form submission for validation
const role = document.getElementById('role').value;
const experienceField = document.getElementById('extraField');
// Show the experience field only if role is 'faculty' or 'employee'
if (role === 'employee' || role === 'faculty') {
experienceField.style.display = 'block';
} else {
experienceField.style.display = 'none';
// Grab form data for display or processing
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const contact = document.getElementById('contact').value;
const department = document.getElementById('department').value;
const roleSelected = document.getElementById('role').value;
const experience = document.getElementById('experience') ?
document.getElementById('experience').value : 'N/A';
// Display the submitted data
const formOutput = document.getElementById('formOutput');
formOutput.innerHTML = `
<h2>Submitted Information</h2>
<p><strong>Name:</strong> ${name}</p>
<p><strong>Email:</strong> ${email}</p>
<p><strong>Contact:</strong> ${contact}</p>
<p><strong>Department:</strong> ${department}</p>
<p><strong>Role:</strong> ${roleSelected}</p>
<p><strong>Experience:</strong> ${experience}</p>
`;
// Optionally, reset the form after showing the output (if needed)
// document.getElementById('entryForm').reset();
Q3:-Develop a responsive website using CSS and HTML. Website may be for
tutorial/blogs/commercial website.
HTML Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Blog/Tutorial Website</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<!-- Header Section -->
<header>
<div class="container">
<h1>LearnTech Blog</h1>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#tutorials">Tutorials</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</div>
</header>
<!-- Hero Section -->
<section id="home" class="hero">
<div class="hero-content">
<h2>Welcome to LearnTech Blog</h2>
<p>Explore tutorials, tips, and tricks on various tech topics!</p>
<a href="#tutorials" class="btn">Start Learning</a>
</div>
</section>
<!-- Tutorials Section -->
<section id="tutorials" class="section">
<div class="container">
<h2>Latest Tutorials</h2>
<div class="tutorials">
<div class="tutorial">
<img src="https://via.placeholder.com/300" alt="Tutorial 1">
<h3>Getting Started with HTML</h3>
<p>Learn the basics of HTML, the building block of web development.</p>
<a href="#">Read More</a>
</div>
<div class="tutorial">
<img src="https://via.placeholder.com/300" alt="Tutorial 2">
<h3>CSS for Beginners</h3>
<p>A comprehensive guide to styling your website with CSS.</p>
<a href="#">Read More</a>
</div>
<div class="tutorial">
<img src="https://via.placeholder.com/300" alt="Tutorial 3">
<h3>JavaScript 101</h3>
<p>Master the fundamentals of JavaScript and build interactive websites.</p>
<a href="#">Read More</a>
</div>
</div>
</div>
</section>
<!-- About Section -->
<section id="about" class="section about">
<div class="container">
<h2>About LearnTech Blog</h2>
<p>LearnTech Blog is your go-to platform for learning web development. Our tutorials are
easy to follow, comprehensive, and updated regularly. Whether you’re a beginner or an experienced
developer, we have something for everyone.</p>
</div>
</section>
<!-- Contact Section -->
<section id="contact" class="section contact">
<div class="container">
<h2>Contact Us</h2>
<form action="#">
<input type="text" placeholder="Your Name" required>
<input type="email" placeholder="Your Email" required>
<textarea placeholder="Your Message" required></textarea>
<button type="submit">Send Message</button>
</form>
</div>
</section>
<!-- Footer Section -->
<footer>
<div class="container">
<p>© 2024 LearnTech Blog | All rights reserved</p>
</div>
</footer>
</body>
</html>
CSS Code:-
/* General Reset */
*{
margin: 0;
padding: 0;
box-sizing: border-box;
/* Body Styling */
body {
font-family: Arial, sans-serif;
line-height: 1.6;
background-color: #f4f4f4;
color: #333;
/* Header Styling */
header {
background-color: #333;
color: white;
padding: 20px 0;
header .container {
display: flex;
justify-content: space-between;
align-items: center;
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
header h1 {
font-size: 1.8em;
header nav ul {
list-style: none;
display: flex;
}
header nav ul li {
margin-left: 20px;
header nav ul li a {
color: white;
text-decoration: none;
font-size: 1.1em;
header nav ul li a:hover {
text-decoration: underline;
/* Hero Section Styling */
.hero {
background-color: #007bff;
color: white;
padding: 100px 0;
text-align: center;
.hero-content h2 {
font-size: 2.5em;
margin-bottom: 20px;
.hero-content p {
font-size: 1.2em;
margin-bottom: 30px;
}
.hero .btn {
padding: 10px 20px;
background-color: #ffffff;
color: #007bff;
text-decoration: none;
font-size: 1.1em;
border-radius: 5px;
.hero .btn:hover {
background-color: #f4f4f4;
/* Section Styling */
.section {
padding: 60px 0;
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
h2 {
font-size: 2em;
margin-bottom: 30px;
text-align: center;
}
/* Tutorials Section Styling */
.tutorials {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
.tutorial {
width: 32%;
background-color: #fff;
padding: 20px;
margin: 10px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
text-align: center;
.tutorial img {
width: 100%;
height: auto;
margin-bottom: 20px;
border-radius: 5px;
.tutorial h3 {
font-size: 1.5em;
margin-bottom: 10px;
.tutorial p {
margin-bottom: 15px;
.tutorial a {
color: #007bff;
text-decoration: none;
font-weight: bold;
.tutorial a:hover {
text-decoration: underline;
/* About Section Styling */
.about p {
font-size: 1.2em;
text-align: center;
max-width: 800px;
margin: 0 auto;
/* Contact Section Styling */
.contact form {
max-width: 600px;
margin: 0 auto;
.contact input, .contact textarea {
width: 100%;
padding: 15px;
margin-bottom: 20px;
border: 1px solid #ccc;
border-radius: 5px;
.contact button {
width: 100%;
padding: 15px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
font-size: 1.1em;
.contact button:hover {
background-color: #0056b3;
/* Footer Section Styling */
footer {
background-color: #333;
color: white;
padding: 20px 0;
text-align: center;
/* Responsive Design */
@media (max-width: 768px) {
header .container {
flex-direction: column;
text-align: center;
}
header nav ul {
flex-direction: column;
margin-top: 20px;
.tutorials {
flex-direction: column;
.tutorial {
width: 100%;
margin-bottom: 20px;
.hero-content h2 {
font-size: 2em;
.hero-content p {
font-size: 1.1em;
Q4:- Write program using HTML and JS For validation of input data.
Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation Example</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
.form-container {
background-color: #fff;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
width: 300px;
h2 {
text-align: center;
.form-group {
margin-bottom: 20px;
label {
display: block;
margin-bottom: 5px;
input {
width: 100%;
padding: 10px;
margin: 5px 0;
border: 1px solid #ccc;
border-radius: 5px;
.error {
color: red;
font-size: 12px;
.success {
color: green;
font-size: 14px;
button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
</style>
</head>
<body>
<div class="form-container">
<h2>Registration Form</h2>
<form id="registrationForm" onsubmit="return validateForm()">
<div class="form-group">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your name" required>
<div id="nameError" class="error"></div>
</div>
<div class="form-group">
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" placeholder="Enter your email" required>
<div id="emailError" class="error"></div>
</div>
<div class="form-group">
<label for="age">Age:</label>
<input type="number" id="age" name="age" placeholder="Enter your age" required>
<div id="ageError" class="error"></div>
</div>
<button type="submit">Submit</button>
<div id="successMessage" class="success"></div>
</form>
</div>
<script>
function validateForm() {
// Clear previous error messages
document.getElementById("nameError").textContent = "";
document.getElementById("emailError").textContent = "";
document.getElementById("ageError").textContent = "";
document.getElementById("successMessage").textContent = "";
let isValid = true;
// Name validation (must not be empty)
const name = document.getElementById("name").value;
if (name.trim() === "") {
document.getElementById("nameError").textContent = "Name is required.";
isValid = false;
// Email validation (must be in a valid email format)
const email = document.getElementById("email").value;
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (!email.match(emailPattern)) {
document.getElementById("emailError").textContent = "Please enter a valid email
address.";
isValid = false;
// Age validation (must be a positive number and >= 18)
const age = document.getElementById("age").value;
if (age < 18 || age === "") {
document.getElementById("ageError").textContent = "Age must be 18 or older.";
isValid = false;
// If everything is valid, show success message
if (isValid) {
document.getElementById("successMessage").textContent = "Form submitted
successfully!";
return true; // Allow form submission
// Prevent form submission if any validation fails
return false;
</script>
</body>
</html>
Q5:- Write a programs in XML for creation of DTD, which specifies set of rules. Crate a style sheet in
css/Xsl & display the document in internet explorer.
XML with DTD Code:-
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE student SYSTEM "student.dtd">
<student>
<name>John Doe</name>
<age>22</age>
<major>Computer Science</major>
<contact>
<email>johndoe@example.com</email>
<phone>123-456-7890</phone>
</contact>
</student>
DTD Document Code:-
<!ELEMENT student (name, age, major, contact)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ELEMENT major (#PCDATA)>
<!ELEMENT contact (email, phone)>
<!ELEMENT email (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
XSLT Stylesheet Code:-
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Template for the root element (student) -->
<xsl:template match="/student">
<html>
<head>
<title>Student Information</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
h1 {
color: #333;
}
.container {
width: 80%;
margin: auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
table {
width: 100%;
border-collapse: collapse;
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
th {
background-color: #f2f2f2;
</style>
</head>
<body>
<div class="container">
<h1>Student Information</h1>
<table>
<tr>
<th>Name</th>
<td><xsl:value-of select="name"/></td>
</tr>
<tr>
<th>Age</th>
<td><xsl:value-of select="age"/></td>
</tr>
<tr>
<th>Major</th>
<td><xsl:value-of select="major"/></td>
</tr>
<tr>
<th>Email</th>
<td><xsl:value-of select="contact/email"/></td>
</tr>
<tr>
<th>Phone</th>
<td><xsl:value-of select="contact/phone"/></td>
</tr>
</table>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Link the XML to XSLT Code:-
<?xml-stylesheet type="text/xsl" href="student.xsl"?>
Complete XML Document Code:-
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="student.xsl"?>
<!DOCTYPE student SYSTEM "student.dtd">
<student>
<name>John Doe</name>
<age>22</age>
<major>Computer Science</major>
<contact>
<email>johndoe@example.com</email>
<phone>123-456-7890</phone>
</contact>
</student>
Q6:-Create a Java Bean for Employee(EmpID, Name, Salary, Designation and Department).
public class Employee {
// Private fields
private int empID;
private String name;
private double salary;
private String designation;
private String department;
// Default constructor
public Employee() {
// Parameterized constructor
public Employee(int empID, String name, double salary, String designation, String department) {
this.empID = empID;
this.name = name;
this.salary = salary;
this.designation = designation;
this.department = department;
}
// Getter and Setter methods for EmpID
public int getEmpID() {
return empID;
public void setEmpID(int empID) {
this.empID = empID;
// Getter and Setter methods for Name
public String getName() {
return name;
public void setName(String name) {
this.name = name;
// Getter and Setter methods for Salary
public double getSalary() {
return salary;
public void setSalary(double salary) {
this.salary = salary;
// Getter and Setter methods for Designation
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
// Getter and Setter methods for Department
public String getDepartment() {
return department;
public void setDepartment(String department) {
this.department = department;
// toString method for displaying Employee information
@Override
public String toString() {
return "Employee [EmpID=" + empID + ", Name=" + name + ", Salary=" + salary + ",
Designation=" + designation
+ ", Department=" + department + "]";
Q7:- Build a command-line utility using Node.js that performs a specific task, such as converting text
to uppercase, calculating the factorial of a number, or generating random passwords.
Code:-
// Importing required modules
const readline = require('readline');
// Create an interface for reading input from the command line
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Function to generate a random password
function generatePassword(length) {
const characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+[]{}|;:,.<
>?';
let password = '';
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
password += characters[randomIndex];
return password;
// Ask user for the password length
rl.question('Enter the password length: ', (input) => {
const length = parseInt(input);
// Check if the input is a valid number
if (isNaN(length) || length <= 0) {
console.log('Please enter a valid positive number.');
rl.close();
} else {
const password = generatePassword(length);
console.log('Generated Password:', password);
rl.close();
});
Q8:- Develop a script that uses MongoDB's aggregation framework to perform operations like
grouping, filtering, and sorting.For instance, aggregate user data to find the average age of users in
different cities.
aggregateUserData.js Code:-
// Import MongoDB client
const { MongoClient } = require('mongodb');
// Define the MongoDB connection URI
const uri = 'mongodb://localhost:27017'; // Change this to your MongoDB URI
const dbName = 'userdb'; // Name of the database
const collectionName = 'users'; // Name of the collection
async function aggregateUserData() {
// Connect to the MongoDB server
const client = new MongoClient(uri);
try {
await client.connect();
console.log('Connected to MongoDB');
const database = client.db(dbName);
const collection = database.collection(collectionName);
// Aggregation pipeline to find the average age of users in different cities
const pipeline = [
// Stage 1: Match users who have an 'age' and 'city' field
$match: {
age: { $exists: true, $ne: null },
city: { $exists: true, $ne: null }
},
// Stage 2: Group users by city and calculate the average age
$group: {
_id: "$city", // Group by city
avgAge: { $avg: "$age" }, // Calculate average age
userCount: { $sum: 1 } // Count the number of users per city
},
// Stage 3: Sort cities by average age in descending order
$sort: { avgAge: -1 }
},
// Stage 4: Project the results to format the output
$project: {
_id: 0,
city: "$_id",
avgAge: 1,
userCount: 1
];
// Execute the aggregation pipeline
const result = await collection.aggregate(pipeline).toArray();
console.log('Average Age of Users in Different Cities:');
result.forEach((doc) => {
console.log(`City: ${doc.city}, Average Age: ${doc.avgAge}, User Count: ${doc.userCount}`);
});
} catch (error) {
console.error('Error executing aggregation:', error);
} finally {
await client.close();
// Run the aggregation function
aggregateUserData();
Sample Data Code:-
{ "name": "Alice", "age": 25, "city": "New York" },
{ "name": "Bob", "age": 30, "city": "New York" },
{ "name": "Charlie", "age": 35, "city": "Los Angeles" },
{ "name": "David", "age": 40, "city": "Los Angeles" },
{ "name": "Eve", "age": 28, "city": "Chicago" }
Running the Script:-
node aggregateUserData.js
Example Output:-
Connected to MongoDB
Average Age of Users in Different Cities:
City: Los Angeles, Average Age: 37.5, User Count: 2
City: New York, Average Age: 27.5, User Count: 2
City: Chicago, Average Age: 28, User Count: 1
Q9:- Assume four users user1, user2, user3 and user4 having the passwords pwd1, pwd2, pwd3 and
pwd4 respectively. Write a servlet for doing the following: 1. Create a Cookie and add these four user
id’s and passwords to this Cookie. 2. Read the user id and passwords entered in the Login form and
authenticate with the values available in the cookies.
Servlet for creating cookies with user credentials Code:-
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class CreateCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Create user IDs and passwords
Map<String, String> users = new HashMap<>();
users.put("user1", "pwd1");
users.put("user2", "pwd2");
users.put("user3", "pwd3");
users.put("user4", "pwd4");
// Set the content type for the response
response.setContentType("text/html");
// Create a Cookie for each user and password pair
for (Map.Entry<String, String> entry : users.entrySet()) {
String userId = entry.getKey();
String password = entry.getValue();
// Create cookies to store the user ID and password
Cookie userCookie = new Cookie(userId, password);
// Set the cookie's lifetime to 24 hours
userCookie.setMaxAge(60 * 60 * 24); // 1 day
response.addCookie(userCookie); // Add cookie to response
// Provide a response to the client indicating cookies have been created
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h3>Cookies with user credentials have been created successfully.</h3>");
out.println("<a href='login.html'>Go to Login Page</a>");
out.println("</body></html>");
Login Form (HTML) Code:-
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login Form</h2>
<form action="AuthenticateServlet" method="post">
<label for="userId">User ID:</label>
<input type="text" id="userId" name="userId" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Servlet for Authentication Code:-
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.annotation.*;
@WebServlet("/AuthenticateServlet")
public class AuthenticateServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get user input from the login form
String userId = request.getParameter("userId");
String password = request.getParameter("password");
// Set content type
response.setContentType("text/html");
// Get cookies from the request
Cookie[] cookies = request.getCookies();
boolean isAuthenticated = false;
if (cookies != null) {
// Iterate over all cookies to find matching user credentials
for (Cookie cookie : cookies) {
String storedPassword = cookie.getValue();
String storedUserId = cookie.getName();
// Check if the user ID and password match the values in the cookies
if (userId.equals(storedUserId) && password.equals(storedPassword)) {
isAuthenticated = true;
break;
}
PrintWriter out = response.getWriter();
out.println("<html><body>");
if (isAuthenticated) {
out.println("<h3>Login Successful!</h3>");
} else {
out.println("<h3>Invalid credentials. Please try again.</h3>");
out.println("</body></html>");
Q10:- Create a table which should contain at least the following fields: name, password, email-id,
phone number Write Servlet/JSP to connect to that database and extract data from the tables and
display them. Insert the details of the users who register with the web site, whenever a new user
clicks the submit button in the registration page.
Database Setup Code:-
CREATE DATABASE userdb;
USE userdb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
password VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(20)
);
JSP for User Registration (registration.jsp) Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration</title>
</head>
<body>
<h2>User Registration</h2>
<form action="RegisterServlet" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<label for="email">Email ID:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="phone">Phone Number:</label>
<input type="text" id="phone" name="phone" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Servlet for Registration (RegisterServlet.java) Code:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class RegisterServlet extends HttpServlet {
// Database connection parameters
private static final String DB_URL = "jdbc:mysql://localhost:3306/userdb";
private static final String DB_USER = "root"; // Change if necessary
private static final String DB_PASSWORD = "root"; // Change if necessary
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get user details from the form
String name = request.getParameter("name");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
// Establish connection to the database
try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
// SQL to insert the new user into the table
String sql = "INSERT INTO users (name, password, email, phone) VALUES (?, ?, ?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
// Set the values for the parameters
stmt.setString(1, name);
stmt.setString(2, password);
stmt.setString(3, email);
stmt.setString(4, phone);
// Execute the update (insertion)
int rowsAffected = stmt.executeUpdate();
if (rowsAffected > 0) {
// Redirect to a success page or confirmation page
response.sendRedirect("registrationSuccess.jsp");
} else {
response.sendRedirect("registrationFailed.jsp");
}
} catch (SQLException e) {
e.printStackTrace();
response.getWriter().println("Database error: " + e.getMessage());
Success Page (registrationSuccess.jsp) Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Successful</title>
</head>
<body>
<h2>Registration Successful!</h2>
<p>Welcome, you have successfully registered. <a href="viewUsers.jsp">View Registered
Users</a></p>
</body>
</html>
Servlet to Fetch and Display Data (ViewUsersServlet.java) Code:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class ViewUsersServlet extends HttpServlet {
private static final String DB_URL = "jdbc:mysql://localhost:3306/userdb";
private static final String DB_USER = "root"; // Change if necessary
private static final String DB_PASSWORD = "root"; // Change if necessary
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Set content type for the response
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Establish connection to the database
try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
// SQL to fetch all users
String sql = "SELECT * FROM users";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
// Start of HTML table for displaying users
out.println("<html><body>");
out.println("<h2>List of Registered Users</h2>");
out.println("<table border='1'><tr><th>Name</th><th>Email</th><th>Phone</th></tr>");
// Iterate over the result set and display each user's data
while (rs.next()) {
String name = rs.getString("name");
String email = rs.getString("email");
String phone = rs.getString("phone");
out.println("<tr>");
out.println("<td>" + name + "</td>");
out.println("<td>" + email + "</td>");
out.println("<td>" + phone + "</td>");
out.println("</tr>");
out.println("</table>");
out.println("</body></html>");
} catch (SQLException e) {
e.printStackTrace();
out.println("Database error: " + e.getMessage());
JSP for Displaying Users (viewUsers.jsp) Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registered Users</title>
</head>
<body>
<h2>Registered Users</h2>
<form action="ViewUsersServlet" method="GET">
<input type="submit" value="View All Users">
</form>
</body>
</html>
Web Deployment Descriptor (web.xml) Code:-
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ViewUsersServlet</servlet-name>
<servlet-class>ViewUsersServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ViewUsersServlet</servlet-name>
<url-pattern>/ViewUsersServlet</url-pattern>
</servlet-mapping>
</web-app>
Q11:-Write a JSP which insert the details of the 3 or 4 users who register with the web site by using
registration form. Authenticate the user when he submits the login form using the user name and
password from the database.
Database Setup Code:-
CREATE DATABASE userdb;
USE userdb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(100),
phone VARCHAR(20)
);
JSP for User Registration (register.jsp) Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration</title>
</head>
<body>
<h2>User Registration</h2>
<form action="RegisterServlet" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<label for="email">Email ID:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="phone">Phone Number:</label>
<input type="text" id="phone" name="phone" required><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
Servlet for Registration (RegisterServlet.java) Code:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class RegisterServlet extends HttpServlet {
private static final String DB_URL = "jdbc:mysql://localhost:3306/userdb";
private static final String DB_USER = "root"; // Change if necessary
private static final String DB_PASSWORD = "root"; // Change if necessary
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get user details from the form
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
// Establish connection to the database
try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
// SQL to insert the new user into the table
String sql = "INSERT INTO users (username, password, email, phone) VALUES (?, ?, ?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
// Set the values for the parameters
stmt.setString(1, username);
stmt.setString(2, password);
stmt.setString(3, email);
stmt.setString(4, phone);
// Execute the update (insertion)
int rowsAffected = stmt.executeUpdate();
if (rowsAffected > 0) {
// Redirect to a success page
response.sendRedirect("registrationSuccess.jsp");
} else {
response.sendRedirect("registrationFailed.jsp");
} catch (SQLException e) {
e.printStackTrace();
response.getWriter().println("Database error: " + e.getMessage());
Success Page After Registration (registrationSuccess.jsp) Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Successful</title>
</head>
<body>
<h2>Registration Successful!</h2>
<p>You have been successfully registered. <a href="login.jsp">Login</a></p>
</body>
</html>
JSP for User Login (login.jsp) Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Login</title>
</head>
<body>
<h2>User Login</h2>
<form action="LoginServlet" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Servlet for User Authentication (LoginServlet.java) Code:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class LoginServlet extends HttpServlet {
private static final String DB_URL = "jdbc:mysql://localhost:3306/userdb";
private static final String DB_USER = "root"; // Change if necessary
private static final String DB_PASSWORD = "root"; // Change if necessary
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get the login details from the form
String username = request.getParameter("username");
String password = request.getParameter("password");
// Establish connection to the database
try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
// SQL to authenticate the user
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, username);
stmt.setString(2, password);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
// User found, login successful
response.sendRedirect("loginSuccess.jsp");
} else {
// Authentication failed
response.sendRedirect("loginFailed.jsp");
} catch (SQLException e) {
e.printStackTrace();
response.getWriter().println("Database error: " + e.getMessage());
Success Page After Login (loginSuccess.jsp) Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Successful</title>
</head>
<body>
<h2>Login Successful!</h2>
<p>Welcome back, you have logged in successfully.</p>
</body>
</html>
Failure Page for Registration (registrationFailed.jsp) Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Failed</title>
</head>
<body>
<h2>Registration Failed!</h2>
<p>Something went wrong. Please try again.</p>
<a href="register.jsp">Go back to registration page</a>
</body>
</html>
Failure Page for Login (loginFailed.jsp) Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Failed</title>
</head>
<body>
<h2>Login Failed!</h2>
<p>Invalid username or password. Please try again.</p>
<a href="login.jsp">Go back to login page</a>
</body>
</html>
Web Deployment Descriptor (web.xml) Code:-
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- RegisterServlet -->
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<!-- LoginServlet -->
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
Q12:- Design and implement a simple shopping cart example with session tracking API.
Define a Product Catalog Code:-
public class Product {
private String id;
private String name;
private double price;
public Product(String id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
public String getId() {
return id;
public String getName() {
return name;
public double getPrice() {
return price;
Create a Product Catalog (catalog.jsp) Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product Catalog</title>
</head>
<body>
<h2>Product Catalog</h2>
<ul>
<li>
<form action="AddToCartServlet" method="POST">
<p>Product 1 - $10.0</p>
<input type="hidden" name="productId" value="1">
<input type="submit" value="Add to Cart">
</form>
</li>
<li>
<form action="AddToCartServlet" method="POST">
<p>Product 2 - $20.0</p>
<input type="hidden" name="productId" value="2">
<input type="submit" value="Add to Cart">
</form>
</li>
<li>
<form action="AddToCartServlet" method="POST">
<p>Product 3 - $30.0</p>
<input type="hidden" name="productId" value="3">
<input type="submit" value="Add to Cart">
</form>
</li>
</ul>
<br>
<a href="viewCart.jsp">View Cart</a>
</body>
</html>
Add Items to the Cart (AddToCartServlet.java) Code:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class AddToCartServlet extends HttpServlet {
// Define the available products
private static final Map<String, Product> productCatalog = new HashMap<>();
static {
productCatalog.put("1", new Product("1", "Product 1", 10.0));
productCatalog.put("2", new Product("2", "Product 2", 20.0));
productCatalog.put("3", new Product("3", "Product 3", 30.0));
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String productId = request.getParameter("productId");
Product product = productCatalog.get(productId);
// Get the current session or create a new one
HttpSession session = request.getSession();
List<Product> cart = (List<Product>) session.getAttribute("cart");
if (cart == null) {
cart = new ArrayList<>();
session.setAttribute("cart", cart);
}
// Add product to the cart
cart.add(product);
// Redirect to the catalog page or the cart page
response.sendRedirect("catalog.jsp");
View Cart Page (viewCart.jsp) Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Shopping Cart</title>
</head>
<body>
<h2>Your Shopping Cart</h2>
<table border="1">
<thead>
<tr>
<th>Product Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<%
HttpSession session = request.getSession();
List<Product> cart = (List<Product>) session.getAttribute("cart");
double total = 0;
if (cart != null && !cart.isEmpty()) {
for (Product product : cart) {
%>
<tr>
<td><%= product.getName() %></td>
<td><%= product.getPrice() %></td>
<td>
<form action="RemoveFromCartServlet" method="POST">
<input type="hidden" name="productId" value="<%= product.getId() %>">
<input type="submit" value="Remove">
</form>
</td>
</tr>
<%
total += product.getPrice();
} else {
%>
<tr><td colspan="3">Your cart is empty.</td></tr>
<%
%>
</tbody>
</table>
<br>
<p>Total: $<%= total %></p>
<a href="catalog.jsp">Continue Shopping</a>
</body>
</html>
Remove Items from the Cart (RemoveFromCartServlet.java) Code:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class RemoveFromCartServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String productId = request.getParameter("productId");
// Get the current session
HttpSession session = request.getSession();
List<Product> cart = (List<Product>) session.getAttribute("cart");
if (cart != null && !cart.isEmpty()) {
// Remove the product from the cart
cart.removeIf(product -> product.getId().equals(productId));
// Redirect to the cart page
response.sendRedirect("viewCart.jsp");
Web Deployment Descriptor (web.xml) Code:-
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- Add to Cart Servlet -->
<servlet>
<servlet-name>AddToCartServlet</servlet-name>
<servlet-class>AddToCartServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddToCartServlet</servlet-name>
<url-pattern>/AddToCartServlet</url-pattern>
</servlet-mapping>
<!-- Remove from Cart Servlet -->
<servlet>
<servlet-name>RemoveFromCartServlet</servlet-name>
<servlet-class>RemoveFromCartServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RemoveFromCartServlet</servlet-name>
<url-pattern>/RemoveFromCartServlet</url-pattern>
</servlet-mapping>
</web-app>