0% found this document useful (0 votes)
17 views37 pages

Institute Website and Registration Form

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

Institute Website and Registration Form

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

(1.

) Write an HTML program to design your institute website displaying name, address, and
department details.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Institute of Advanced Web Technologies</title>
<!-- Load Tailwind CSS -->
<script src="[Link]
<style>
/* Custom font for better look */
@import url('[Link] body {
font-family: 'Inter', sans-serif; background-color: #f4f6f8;
}
</style>
</head>
<body class="min-h-screen flex flex-col">
<!-- Header Section -->
<header class="bg-indigo-700 text-white shadow-lg p-4">
<div class="container mx-auto flex flex-col md:flex-row justify-between items-center">
<div class="text-2xl font-extrabold tracking-tight mb-2 md:mb-0">
Institute of Advanced Web Technologies (IAWT)
</div>
<div class="text-sm text-indigo-200">
<p>007 Vidya, Innovation City, Deoria 274202</p>
<p>Email: info@[Link] | Phone:8381937760</p></div></div>
</header>
<!-- Navigation -->
<nav class="bg-white shadow-md">
<div class="container mx-auto p-3 flex justify-center space-x-6 overflow-x-auto">
<a href="#" class="text-indigo-700 hover:text-indigo-900 font-semibold transition duration-150 border-b-
2 border-transparent hover:border-indigo-500 pb-
1">Home</a>
<a href="#" class="text-indigo-700 hover:text-indigo-900 font-semibold transition duration-150 border-b-
2 border-transparent hover:border-indigo-500 pb-
1">About Us</a>
<a href="#departments" class="text-indigo-700 hover:text-indigo-900 font-semibold transition duration-
150 border-b-2 border-transparent hover:borderindigo-500 pb-1">Departments</a>
<a href="#" class="text-indigo-700 hover:text-indigo-900 font-semibold transition duration-150 border-b-
2 border-transparent hover:border-indigo-500 pb-
1">Admissions</a>
<a href="#" class="text-indigo-700 hover:text-indigo-900 font-semibold transition duration-150 border-b-
2 border-transparent hover:border-indigo-500 pb-
1">Contact</a>
</div>
</nav>
<!-- Main Content -->
<main class="container mx-auto p-4 flex-grow">
<!-- Hero Section -->
<section class="mb-10 p-6 bg-white rounded-xl shadow-lg">
<h1 class="text-3xl font-bold text-gray-800 mb-4">Welcome to VIAWT</h1>
<p class="text-gray-600">The Vidya Institute of Advanced Web Technologies is dedicated to shaping the
next generation of digital innovators through cuttingedge curricula and practical experience.</p>
</section>
<!-- Department Details Section -->
<section id="departments" class="mb-10">
<h2 class="text-3xl font-bold text-indigo-700 mb-6 text-center">Our Departments</h2>
<!-- Responsive Grid for Departments -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<!-- Card 1: Computer Science -->
<div class="bg-white p-6 rounded-xl shadow-xl transition transform hover:scale-[1.02] duration-300">
<h3 class="text-xl font-semibold text-gray-900 mb-2 border-b pb-2">Computer Science &
Engineering</h3>
<p class="text-gray-600 mb-3">Focuses on algorithms, data structures, and fundamental computing
principles. Core programs include [Link] and [Link] in CSE.</p>
<a href="#" class="text-indigo-600 font-medium hover:text-indigo-800">Explore Programs &rarr;</a>
</div>
<!-- Card 2: Information Technology -->
<div class="bg-white p-6 rounded-xl shadow-xl transition transform hover:scale-[1.02] duration-300">
<h3 class="text-xl font-semibold text-gray-900 mb-2 border-b pb-2">Information Technology</h3>
<p class="text-gray-600 mb-3">Specializes in networking, database management, and cybersecurity.
Prepares students for immediate industry roles.</p>
<a href="#" class="text-indigo-600 font-medium hover:text-indigo-800">Explore Programs &rarr;</a>
</div>
<!-- Card 3: Web Development -->
<div class="bg-white p-6 rounded-xl shadow-xl transition transform hover:scale-[1.02] duration-300">
<h3 class="text-xl font-semibold text-gray-900 mb-2 border-b pb-2">Front-End & UX Design</h3>
<p class="text-gray-600 mb-3">Dedicated to modern web technologies, user experience (UX), and
interactive interface development.</p>
<a href="#" class="text-indigo-600 font-medium hover:text-indigo-800">Explore Programs &rarr;</a>
</div>
</div>
</section>
</main>
<!-- Footer -->
<footer class="bg-gray-800 text-white p-6 mt-10">
<div class="container mx-auto text-center text-sm">
&copy; Vidya Institute of Advanced Web Technologies. All rights reserved.
</div>
</footer>
</body>
</html>
(2.) Write an HTML form to accept student or employee details (Name, ID, Email, Department,
etc.).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student/Employee Registration</title>
<style>*{margin:0;padding:0;box-sizing:border-box;}body{font-family:Arial,sans-serif;background-
color:#f4f4f4;padding:2rem;}.container{maxwidth:600px;margin:0auto;background:white;padding:2rem;
border-radius:8px;box-shadow:02px10pxrgba(0,0,0,0.1);}h1{text-
align:center;color:#2c3e50;margin-bottom:1.5rem;}.form-group{margin-
bottom:1rem;}label{display:block;margin-
bottom:0.5rem;fontweight:bold;color:#333;}input,select,textarea{width:100%;padding:0.75rem;border:1p
x solid #ddd;border-radius:4px;font-
size:1rem;}button{background:#3498db;color:white;padding:0.75rem 2rem;border:none;border-
radius:4px;cursor:pointer;font-size:1rem;margintop:1rem;}button:hover{background:#2980b9;}.radio-
group{display:flex;gap:1rem;}.radio-group label{font-weight:normal;}</style></head> <body>
<div class="container">
<h1>Student/Employee Registration Form</h1> <form id="registrationForm">
<div class="form-group">
<label for="userType">Registering as:</label>
<div class="radio-group">
<label>
<input type="radio" name="userType" value="student" checked> Student
</label>
<label>
<input type="radio" name="userType" value="employee"> Employee
</label>
</div>
</div>
<div class="form-group">
<label for="fullName">Full Name *</label>
<input type="text" id="fullName" name="fullName" required>
</div>
<div class="form-group">
<label for="idNumber">ID Number *</label>
<input type="text" id="idNumber" name="idNumber" required>
</div>
<div class="form-group">
<label for="email">Email Address *</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="phone">Phone Number</label>
<input type="tel" id="phone" name="phone">
</div>
<div class="form-group">
<label for="department">Department *</label>
<select id="department" name="department" required>
<option value="">Select Department</option>
<option value="cse">Computer Science & Engineering</option>
<option value="ece">Electronics & Communication</option>
<option value="mech">Mechanical Engineering</option>
<option value="civil">Civil Engineering</option>
<option value="it">Information Technology</option>
</select>
</div>
<div class="form-group" id="studentFields">
<label for="semester">Semester</label>
<select id="semester" name="semester">
<option value="">Select Semester</option>
<option value="1">Semester 1</option>
<option value="2">Semester 2</option>
<option value="3">Semester 3</option>
<option value="4">Semester 4</option>
<option value="5">Semester 5</option>
<option value="6">Semester 6</option>
<option value="7">Semester 7</option>
<option value="8">Semester 8</option>
</select>
</div>
<div class="form-group" id="employeeFields" style="display: none;">
<label for="designation">Designation</label>
<input type="text" id="designation" name="designation">
</div>
<div class="form-group">
<label for="address">Address</label>
<textarea id="address" name="address" rows="3"></textarea>
</div>
<button type="submit">Submit Registration</button>
</form>
</div>
<script>
[Link]('input[name="userType"]').forEach(radio => {
[Link]('change', function() { if ([Link] === 'student') {
[Link]('studentFields').[Link] = 'block';
[Link]('employeeFields').[Link] = 'none';
} else {
[Link]('studentFields').[Link] = 'none';
[Link]('employeeFields').[Link] = 'block';
}
});
});
</script>
</body> </html>
(3.) Create a responsive website using HTML and CSS for a tutorial, blog, or company homepage.
block' <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The Tech Blog - Responsive Design</title>
<!-- Load Tailwind CSS -->
<script src="[Link]
<style>
@import url('[Link]
body {font-family: 'Inter', sans-serif; background-color: #f7f7f7;
}
</style>
</head>
<body class="min-h-screen flex flex-col">
<!-- Header & Navigation -->
<header class="bg-white shadow-md">
<div class="container mx-auto px-4 py-4 flex justify-between items-center">
<h1 class="text-3xl font-bold text-gray-900">
<a href="#" class="text-indigo-600 hover:text-indigo-800 transition">The Tech Blog</a>
</h1>
<!-- Mobile Menu Button (Hidden on larger screens) -->
<button id="menu-button" class="md:hidden text-gray-600 hover:text-indigo-600
focus:outline-none">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
xmlns="[Link] strokelinecap="round" stroke-linejoin="round" stroke-
width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg>
</button>
<!-- Desktop Navigation -->
<nav class="hidden md:flex space-x-4">
<a href="#" class="text-gray-600 hover:text-indigo-600 font-medium">Coding</a>
<a href="#" class="text-gray-600 hover:text-indigo-600 font-medium">Design</a>
<a href="#" class="text-gray-600 hover:text-indigo-600 font-medium">Tutorials</a>
<a href="#" class="bg-indigo-600 text-white px-3 py-1 rounded-full hover:bg-indigo-700
transition">Subscribe</a> </nav>
</div>
<!-- Mobile Menu (Hidden by default) -->
<div id="mobile-menu" class="hidden md:hidden bg-gray-50 border-t">
<nav class="flex flex-col p-4 space-y-2">
<a href="#" class="text-gray-700 hover:bg-indigo-100 p-2 rounded">Coding</a>
<a href="#" class="text-gray-700 hover:bg-indigo-100 p-2 rounded">Design</a>
<a href="#" class="text-gray-700 hover:bg-indigo-100 p-2 rounded">Tutorials</a>
<a href="#" class="text-white bg-indigo-500 p-2 rounded text-center">Subscribe</a>
</nav>
</div>
</header>
<!-- Main Content Layout (Responsive Grid) -->
<main class="container mx-auto p-4 flex-grow grid grid-cols-1 lg:grid-cols-4 lg:gap-8 mt-6">
<!-- Blog Posts (Main Content - Takes 3/4 on large screens) -->
<div class="lg:col-span-3 space-y-8">
<h2 class="text-2xl font-semibold text-gray-800 border-b pb-2 mb-4">Latest Articles</h2>
<!-- Article Card 1 -->
<article class="bg-white p-6 rounded-xl shadow-lg hover:shadow-xl transition duration-300">
<div class="flex flex-col md:flex-row gap-6">
<img class="w-full md:w-1/3 h-48 object-cover rounded-lg"
src="[Link]
alt="Thumbnail of responsive design code">
<div class="md:w-2/3">
<span class="text-sm font-medium text-indigo-600 uppercase">Coding | March 15,
2025</span>
<h3 class="text-2xl font-bold text-gray-900 mt-1 mb-3">Mastering Modern CSS Grid
and Flexbox</h3>
<p class="text-gray-600 line-clamp-3">A deep dive into the latest features of CSS Grid
and Flexbox. Learn how to create complex, robust, and highly responsive layouts without relying on
float-based hacks.</p>
<a href="#" class="mt-4 inline-block text-indigo-600 font-medium
hover:underline">Read Article &rarr;</a>
</div>
</div>
</article>
<!-- Article Card 2 -->
<article class="bg-white p-6 rounded-xl shadow-lg hover:shadow-xl transition duration-300">
<div class="flex flex-col md:flex-row gap-6">
<img class="w-full md:w-1/3 h-48 object-cover rounded-lg"
src="[Link]
alt="Thumbnail of React hooks">
<div class="md:w-2/3">
<span class="text-sm font-medium text-indigo-600 uppercase">Tutorials | March 10,
2025</span>
<h3 class="text-2xl font-bold text-gray-900 mt-1 mb-3">Understanding React Hooks:
State and Effects</h3>
<p class="text-gray-600 line-clamp-3">This tutorial walks through the core React
Hooks—`useState` and `useEffect`—and provides practical examples for managing component state
and side effects effectively.</p>
<a href="#" class="mt-4 inline-block text-indigo-600 font-medium
hover:underline">Read Article &rarr;</a>
</div>
</div>
</article>
<!-- Placeholder for more articles -->
<div class="text-center p-6 bg-gray-100 rounded-xl text-gray-500">
<p>--- More articles loading on scroll ---</p>
</div>
</div>
<!-- Sidebar (Takes 1/4 on large screens, stacks on mobile) -->
<aside class="lg:col-span-1 mt-8 lg:mt-0 space-y-8">
<!-- Category Widget -->
<div class="bg-white p-6 rounded-xl shadow-md">
<h3 class="text-xl font-semibold text-gray-800 mb-4 border-b pb-2">Categories</h3>
<ul class="space-y-2">
<li><a href="#" class="text-gray-600 hover:text-indigo-600">Frontend Development
(12)</a></li>
<li><a href="#" class="text-gray-600 hover:text-indigo-600">Backend Systems
(8)</a></li>
<li><a href="#" class="text-gray-600 hover:text-indigo-600">Cloud Computing
(5)</a></li>
<li><a href="#" class="text-gray-600 hover:text-indigo-600">UI/UX Design
(15)</a></li>
</ul>
</div>
<!-- Newsletter Widget -->
<div class="bg-indigo-600 text-white p-6 rounded-xl shadow-md"> <h3 class="text-
xl font-semibold mb-3">Stay Updated!</h3>
<p class="text-indigo-200 mb-4 text-sm">Get the latest articles delivered straight to your
inbox.</p>
<input type="email" placeholder="Your email address" class="w-full p-2 rounded-lg text-gray-
800 mb-3 focus:outline-none focus:ring-2 focus:ring-white">
<button class="w-full bg-white text-indigo-600 font-bold py-2 rounded-lg hover:bg-gray-
100 transition">Subscribe Now</button>
</div> </aside>
</main>
<!-- Footer -->
<footer class="bg-gray-800 text-white p-6 mt-10">
<div class="container mx-auto text-center
text-sm"> &copy; 2025 The Tech Blog. All rights reserved.
</div>
</footer>
<script>
// JavaScript for mobile menu toggle
[Link]('menu-button').addEventListener('click', function() {
const menu = [Link]('mobile-menu');
[Link]('hidden');
});
</script>
</body>
</html>
(4.) Write HTML and JavaScript code for input validation (e.g., email format, password length,
etc.).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Input Validation</title>
<!-- Load Tailwind CSS -->
<script src="[Link]
<style>
@import url('[Link]
body {
font-family: 'Inter', sans-serif; background-color: #f0f4f8;
}
</style>
</head>
<body class="flex items-center justify-center min-h-screen p-4">
<!-- Validation Form Container --> <div class="w-full max-w-md bg-white p-8 rounded-xl
shadow-2xl border border-indigo-100">
<h1 class="text-3xl font-bold text-center text-indigo-700 mb-6"> User Registration &
Validation
</h1><form id="validationForm" class="space-y-4">
<div><label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email
Address</label>
<input type="text" id="email" name="email" class="w-full px-4 py-2 border
border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 transition
duration-150" placeholder="user@[Link]">
<p id="emailError" class="text-xs mt-1 text-red-500 hidden">Please enter a valid email
address.</p>
</div>
<!-- 2. Password Input -->
<div>
<label for="password" class="block text-sm font-medium text-gray-700 mb-
1">Password</label>
<input type="password" id="password" name="password" class="w-full px-
4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500
transition duration-150" placeholder="Must be 8+ characters">
<p id="passwordError" class="text-xs mt-1 text-red-500 hidden">Password must be at
least 8 characters long.</p>
</div>
<!-- Submit Button -->
<div>
<button type="submit" class="w-full py-3 px-4 border border-transparent
rounded-lg shadow-md text-lg font-medium text-white bg-indigo-600 hover:bg-indigo-
700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition duration-
200 mt-4">Register</button></div></form> <!-- Global Status/Success Message (Replaces alert())
-->
<div id="statusMessage" class="mt-6 p-3 text-center rounded-lg text-sm hidden"></div>
</div> <script> const emailInput = [Link]('email'); const
passwordInput = [Link]('password'); const emailError =
[Link]('emailError'); const passwordError =
[Link]('passwordError'); const statusMessage =
[Link]('statusMessage'); const form =
[Link]('validationForm');
// Function to validate email format function validateEmail(email) {
// Regex for a simple email pattern: text@[Link] const re =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/; return [Link](String(email).toLowerCase());
}
// Function to validate password length function validatePassword(password) {
return [Link] >= 8;
}
// Input change/blur listener for Email [Link]('blur', () => {
if (!validateEmail([Link])) { [Link]('hidden');
[Link]('border-red-500');
} else {
[Link]('hidden');
[Link]('border-red-500');
}
});
// Input change/blur listener for Password [Link]('blur', () => { if
(!validatePassword([Link])) { [Link]('hidden');
[Link]('border-red-500');
} else {
[Link]('hidden');
[Link]('border-red-500');
}
});
// Form Submission Handler
[Link]('submit', (e) => {
[Link](); // Stop default form submission
let isValid = true;
// Re-run all validations on submit
if (!validateEmail([Link]))
{ [Link]('hidden');
[Link]('border-red-500');
isValid = false;
} else {
[Link]('hidden');
[Link]('border-red-500');
}
if (!validatePassword([Link])) { [Link]('hidden');
[Link]('border-red-500'); isValid = false;
} else {
[Link]('hidden'); [Link]('border-
red-500');
}
// Display status if (isValid) {
// Success message [Link] = "Registration successful! Data
is ready for server processing."; [Link] = "mt-6 p-3 text-center
rounded-lg text-sm bg-green-100 text-green-700"; [Link] = 'block';
[Link](); // Clear the form
} else {
// Error message [Link] = "Validation failed. Please correct
the highlighted fields."; [Link] = "mt-6 p-3 text-center rounded-lg
text-sm bg-red-100 text-red-700"; [Link] = 'block';
}
});
</script>
</body>
</html>
(5).Write a program in XML for creating DTD, specifying sets of rules, and display using CSS/XSL.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE library SYSTEM "[Link]">
<?xml-stylesheet type="text/css" href="[Link]"?>
<library>
<book category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author><year>1925</year>
<price currency="USD">12.99</price>
<isbn>978-0-7432-7356-5</isbn>
<description>A classic novel of the Jazz Age</description>
</book>
<book category="programming">
<title>Clean Code</title>
<author>Robert C. Martin</author>
<year>2008</year>
<price currency="USD">37.99</price>
<isbn>978-0-13-235088-4</isbn>
<description>A handbook of agile software craftsmanship</description> </book>
<book category="science">
<title>A Brief History of Time</title>
<author>Stephen Hawking</author>
<year>1988</year>
<price currency="USD">15.99</price>
<isbn>978-0-553-10953-5</isbn>
<description>From the Big Bang to Black Holes</description>
</book>
<book category="fiction">
<title>1984</title>
<author>George Orwell</author>
<year>1949</year>
<price currency="USD">9.99</price>
<isbn>978-0-452-28423-4</isbn>
<description>A dystopian social science fiction novel</description>
</book>
</library>
DTD Code ([Link]):
<!ELEMENT library (book+)>
<!ELEMENT book (title, author, year, price, isbn, description)>
<!ATTLIST book category (fiction|programming|science|history) #REQUIRED>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ATTLIST price currency CDATA #REQUIRED>
<!ELEMENT isbn (#PCDATA)> <!ELEMENT description (#PCDATA)>
CSS Code ([Link]):
<style>library{font-family:Arial,sans-serif;max-width:1200px;margin:0
auto;padding:20px;background-
color:#f9f9f9;}book{display:block;background:white;margin:20px 0;padding:20px;border-
radius:8px;box-shadow:0 2px 5px rgba(0,0,0,0.1);borderleft:5px solid
#3498db;}book[category="fiction"]{border-left-
color:#e74c3c;}book[category="programming"]{border-left-
color:#2ecc71;}book[category="science"]{border-left-color:#9b59b6;}title{display:block;font-
size:1.5em;font-weight:bold;color:#2c3e50;marginbottom:10px;}author{display:block;font-
size:1.1em;color:#34495e;margin-bottom:5px;font-style:italic;}year{display:inline-
block;background:#3498db;color:white;padding:2px 8px;border-radius:12px;font-
size:0.9em;margin-right:10px;}price{display:inline-block;fontweight:bold;color:#27ae60;font-
size:1.1em;}isbn{display:block;color:#7f8c8d;font-family:monospace;margin:5px 0;font-
size:0.9em;}description{display:block;margin-top:10px;color:#555;line-
height:1.4;}library:before{content:"Library Catalog";display:block;fontsize:2em;font-
weight:bold;text-align:center;color:#2c3e50;margin-bottom:30px;padding-bottom:10px;border-
bottom:2px solid #3498db;}</style>

Output:
![Styled XML document showing book catalog with different colored borders based on category,
displaying title, author, year, price, ISBN and description for each book]
(6).Create a Java Bean class for Employee information (EmpID, Name, Salary, Designation,
Department).
❖ Java Code ([Link]):
package [Link]; import [Link]; import [Link];
public class Employee implements Serializable {
private String empID; private String name; private double salary; private String
designation; private String department // Default constructor public Employee() {} //
Parameterized constructor
public Employee(String empID, String name, double salary, String designation, String
department) { [Link] = empID; [Link] = name; [Link] = salary;
[Link] = designation; [Link] = department;
}
// Getters and Setters public String getEmpID() {
return empID;
}
public void setEmpID(String empID) { [Link] = empID;
}
public String getName() { return name;
}
public void setName(String name) {
[Link] = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
[Link] = salary;
}

public String getDesignation() { return designation;


}
public void setDesignation(String designation) { [Link] = designation;
}
public String getDepartment() { return department;
}
public void setDepartment(String department) { [Link] = department;
}
// toString method @Override public String toString() {
return [Link]("Employee[ID: %s, Name: %s, Salary: $%.2f, Designation: %s,
Department: %s]", empID, name, salary, designation, department);
}
// equals and hashCode methods
@Override public boolean equals(Object o) { if (this == o) return true;
if (o == null || getClass() != [Link]()) return false; Employee employee = (Employee)
o; return [Link](empID, [Link]);
}
@Override
public int hashCode() { return [Link](empID);
}
}
Test Code ([Link]):
package [Link]; import [Link]; public class TestEmployee {
public static void main(String[] args) {
// Create Employee objects
Employee emp1 = new Employee("E001", "John Doe", 75000.0, "Software Engineer", "IT");
Employee emp2 = new Employee("E002", "Jane Smith", 65000.0, "HR Manager", "Human
Resources");
Employee emp3 = new Employee("E003", "Mike Johnson", 85000.0, "Senior Developer",
"IT"); // Display employee information
[Link]("=== Employee Information ===");
[Link](emp1);
[Link](emp2);
[Link](emp3);
// Test getters and setters
[Link]("\n=== Testing Getters and Setters ===");
Employee emp4 = new Employee();
[Link]("E004"); [Link]("Sarah Wilson");
[Link](72000.0); [Link]("QA Engineer");
[Link]("Quality Assurance"); [Link]("New Employee: " + emp4);
[Link]("Department: " + [Link]()); [Link]("Salary:
$" + [Link]());
}
} }
Output:
=== Employee Information ===
Employee[ID: E001, Name: John Doe, Salary: $75000.00, Designation: Software Engineer,
Department: IT]
Employee[ID: E002, Name: Jane Smith, Salary: $65000.00, Designation: HR Manager,
Department: Human Resources]
Employee[ID: E003, Name: Mike Johnson, Salary: $85000.00, Designation: Senior Developer,
Department: IT]

=== Testing Getters and Setters ===


New Employee: Employee[ID: E004, Name: Sarah Wilson, Salary: $72000.00, Designation: QA
Engineer, Department: Quality Assurance] Department: Quality Assurance
Salary: $72000.0
6. Write a [Link] command-line utility that performs a specific task such as:
o Convert text to uppercase
o Calculate factorial of a number
o Generate random passwords

#[Link]:
{
"name": "cli-utilities",
"version": "1.0.0",
"description": "[Link] CLI Utilities",
"main": "[Link]",
"bin": {
"cli-utils": "./[Link]"
},
"scripts": {
"start": "node [Link]"
}
}
#Main CLI Code ([Link]):
#!/usr/bin/env node const { program } = require('commander');
const readline = require('readline');
program
.version('1.0.0')
.description('[Link] CLI Utilities'); // Convert text to uppercase program
.command('uppercase <text>')
.description('Convert text to uppercase')
.action((text) => {
[Link](`Original: ${text}`); [Link](`Uppercase: ${[Link]()}`);
});
// Calculate factorial
program
.command('factorial <number>')
.description('Calculate factorial of a number')
.action((number) => { const num = parseInt(number); if (isNaN(num) || num < 0) {
[Link]('Please enter a valid non-negative integer'); return;
}
function calculateFactorial(n) {
if (n === 0 || n === 1) return 1; return n * calculateFactorial(n - 1);
}
const result = calculateFactorial(num); [Link](`Factorial of ${num} is: ${result}`);
});
// Generate random password
program
.command('password [length]')
.description('Generate a random password')
.option('-s, --strength <type>', 'Password strength: weak, medium, strong', 'medium')
.action((length = 12, options) => { function generatePassword(len, strength) { const
lowercase = 'abcdefghijklmnopqrstuvwxyz'; const uppercase =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numbers = '0123456789'; const symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?'; let
charset = ''; switch (strength) { case 'weak':
charset = lowercase + numbers; break; case 'medium': charset = lowercase +
uppercase + numbers; break; case 'strong':
charset = lowercase + uppercase + numbers + symbols; break; default:
charset = lowercase + uppercase + numbers;
}
let password = ''; for (let i = 0; i < len; i++) {
const randomIndex = [Link]([Link]() * [Link]); password +=
charset[randomIndex];
}
return password;
}
const password = generatePassword(parseInt(length), [Link]); [Link](`Generated
Password (${[Link]}): ${password}`); [Link](`Password Length:
${[Link]}`);
});
// Interactive mode program
.command('interactive')
.description('Interactive mode')
.action(() => {
const rl = [Link]({ input: [Link], output: [Link]
});
[Link]('=== Interactive CLI Utilities ==='); [Link]('1. Convert to Uppercase');
[Link]('2. Calculate Factorial'); [Link]('3. Generate Password');
[Link]('4. Exit'); function showMenu() {
[Link]('\nChoose an option (1-4): ', (choice) => { switch (choice) { case '1':
[Link]('Enter text to convert: ', (text) => { [Link](`Uppercase:
${[Link]()}`); showMenu();
}); break; case '2':
[Link]('Enter a number: ', (num) => { const number = parseInt(num); if
(isNaN(number) || number < 0) {
[Link]('Invalid number!');
} else { function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
}
[Link](`Factorial of ${number} is: ${fact(number)}`);
}
showMenu();
}); break; case '3':
[Link]('Enter password length (default 12): ', (len) => { const length = len ?
parseInt(len) : 12;
const charset =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
let password = '';
for (let i = 0; i < length; i++) {
password += charset[[Link]([Link]() * [Link])];
}
[Link](`Generated Password: ${password}`);
showMenu();
}); break; case '4':
[Link]('Goodbye!'); [Link](); break; default:
[Link]('Invalid option!'); showMenu();
}
});
}
showMenu();
});
[Link]([Link]);
#Usage Examples and Output:
# Install dependencies npm install commander # Run the CLI commands node [Link] uppercase
"hello world"
node [Link] factorial 5
node [Link] password 16 --strength strong node [Link] interactive
Sample Output:
$ node [Link] uppercase "hello world"
Original: hello world
Uppercase: HELLO WORLD

$ node [Link] factorial 5


Factorial of 5 is: 120

$ node [Link] password 16 --strength strong


Generated Password (strong): k8#mP!qR3$vB2@wN
Password Length: 16

$ node [Link] interactive


=== Interactive CLI Utilities ===
1. Convert to Uppercase
2. Calculate Factorial
3. Generate Password
4. Exit

Choose an option (1-4): 1 Enter text to convert: [Link]


Uppercase: [Link]
MongoDB
8. Write a MongoDB aggregation script to perform operations like grouping, filtering, and sorting.
Example: Find the average age of users in different cities.

#MongoDB JavaScript File ([Link]):


[Link] // MongoDB Aggregation - Compressed Version
db=connect('localhost:27017/test');[Link]();[Link]([{name:"John
Doe",age:28,city:"New
York",salary:75000,department:"Engineering",joinDate:new Date("2020-03-15")},{name:"Jane
Smith",age:32,city:"San
Francisco",salary:82000,department:"Engineering",joinDate:new Date("2019-07-22")},{name:"Mike
Johnson",age:25,city:"New
York",salary:68000,department:"Marketing",joinDate:new Date("2021-01-10")},{name:"Sarah
Wilson",age:29,city:"Chicago",salary:72000,department:"HR",joinDate:new Date("2020-11-
05")},{name:"David Brown",age:35,city:"San
Francisco",salary:95000,department:"Engineering",joinDate:new Date("2018-05-30")},{name:"Emily
Davis",age:27,city:"Chicago",salary:65000,department:"Marketing",joinDate:new Date("2021-03-
18")},{name:"Robert Lee",age:31,city:"New
York",salary:88000,department:"Sales",joinDate:new Date("2019-09-12")}]);print("=== Sample Data
Inserted ===");[Link]().forEach(printjson);

print("\n=== 1. Average Age by City


===");[Link]([{$group:{_id:"$city",averageAge:{$avg:"$age"},userCount:{$sum:1}}},{
$sort:{averageAge:-
1}},{$project:{city:"$_id",averageAge:{$round:["$averageAge",2]},userCount:1,_id:0}}]).forEach(pr
intjson);

print("\n=== 2. Average Salary by Department (Salary > 70000)


===");[Link]([{$match:{salary:{$gt:70000}}},{$group:{_id:"$department",averageSalar
y:{$avg:"$salary"},maxSalary:{$max:"$salary"},mi
nSalary:{$min:"$salary"},employeeCount:{$sum:1}}},{$sort:{averageSalary:-
1}},{$project:{department:"$_id",averageSalary:{$round:["$averageSalary",2]},maxSalary:1,minSala
ry:1,employeeCount:1,_id:0}}]).forEach(printjson
);

print("\n=== 3. Users Count by City and Department


===");[Link]([{$group:{_id:{city:"$city",department:"$department"},count:{$sum:1},av
erageAge:{$avg:"$age"}}},{$sort:{"_id.city":1,cou nt:-
1}},{$project:{city:"$_id.city",department:"$_id.department",count:1,averageAge:{$round:["$averag
eAge",2]},_id:0}}]).forEach(printjson);

print("\n=== 4. Seniority Analysis


===");[Link]([{$addFields:{yearsWithCompany:{$floor:{$divide:[{$subtract:[new
Date(),"$joinDate"]},365*24*60*60*1000]}}}},{$match:{yearsWithCompany:{$gte:1}}},{$group:{
_id:"$department",averageExperience:{$avg:"$years
WithCompany"},totalEmployees:{$sum:1},averageSalary:{$avg:"$salary"}}},{$sort:{averageExperi
ence:-
1}},{$project:{department:"$_id",averageExperience:{$round:["$averageExperience",2]},averageSal
ary:{$round:["$averageSalary",2]},totalEmployee s:1,_id:0}}]).forEach(printjson);
#How to Run:
mongosh [Link]
# or with older MongoDB versions:
mongo [Link]

#Sample Output:
=== Sample Data Inserted ===
{ "_id": ObjectId("..."), "name": "John Doe", "age": 28, "city": "New York", ... }

=== 1. Average Age by City ===


{ "city": "San Francisco", "averageAge": 33.5, "userCount": 2 }
{ "city": "New York", "averageAge": 28, "userCount": 3 }
{ "city": "Chicago", "averageAge": 28, "userCount": 2 }

=== 2. Average Salary by Department (Salary > 70000) ===


{ "department": "Engineering", "averageSalary": 84000, "maxSalary": 95000, "minSalary": 75000,
"employeeCount": 3 }
{ "department": "Sales", "averageSalary": 88000, "maxSalary": 88000, "minSalary": 88000,
"employeeCount": 1 }
{ "department": "HR", "averageSalary": 72000, "maxSalary": 72000, "minSalary": 72000,
"employeeCount": 1 }

=== 3. Users Count by City and Department ===


{ "city": "Chicago", "department": "HR", "count": 1, "averageAge": 29 }
{ "city": "Chicago", "department": "Marketing", "count": 1, "averageAge": 27 }
{ "city": "New York", "department": "Engineering", "count": 1, "averageAge": 28 }

=== 4. Seniority Analysis ===


{ "department": "Engineering", "averageExperience": 2.67, "averageSalary": 84000,
"totalEmployees": 3 }
{ "department": "Sales", "averageExperience": 2.5, "averageSalary": 88000, "totalEmployees": 1 }
{ "department": "HR", "averageExperience": 1.5, "averageSalary": 72000, "totalEmployees": 1 }
Servlet / JSP
(9). Assume four users (user1, user2, user3, user4) have passwords.
o Write a Servlet to create a cookie storing user credentials.
o Authenticate login data from an HTML form using the cookie.
# Database Setup (MySQL):
CREATE DATABASE userdb;
USE userdb; CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL, email VARCHAR(150) UNIQUE NOT NULL,
phone VARCHAR(15),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP); INSERT INTO users (name,
password, email, phone) VALUES
('user1', 'pass1', 'user1@[Link]', '1234567890'),
('user2', 'pass2', 'user2@[Link]', '2345678901'),
('user3', 'pass3', 'user3@[Link]', '3456789012'),
('user4', 'pass4', 'user4@[Link]', '4567890123');
#Login Servlet ([Link]):
package [Link]; import [Link].*; import [Link].*; import [Link].*;
import [Link].*; public class LoginServlet extends HttpServlet { private Connection connection;
@Override public void init() throws ServletException {
try {
[Link]("[Link]"); connection =
[Link](
"jdbc:mysql://localhost:3306/userdb", "username", "password");
} catch (Exception e) { throw new ServletException("Database connection failed", e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { String username = [Link]("username");
String password = [Link]("password"); String remember =
[Link]("remember"); [Link]("text/html");
PrintWriter out = [Link](); try {
String sql = "SELECT * FROM users WHERE name = ? AND password = ?";
PreparedStatement stmt = [Link](sql); [Link](1, username);
[Link](2, password); ResultSet rs = [Link](); if ([Link]()) {
// Create cookie if remember me is checked if ("on".equals(remember)) {
Cookie userCookie = new Cookie("userCredentials", username + ":" +
password); [Link](7 * 24 * 60 * 60); // 7 days
[Link](userCookie);
}
HttpSession session = [Link](); [Link]("username",
username); [Link]("userEmail", [Link]("email"));
[Link]("[Link]");
} else {
[Link]("<html><body>"); [Link]("<h3>Login Failed!</h3>");
[Link]("<p>Invalid username or password</p>"); [Link]("<a
href='[Link]'>Try Again</a>"); [Link]("</body></html>");
}
} catch (SQLException e) { [Link]();
[Link]("Database error occurred");
}
}
@Override
public void destroy() {
try {
if (connection != null) [Link](); } catch (SQLException e) {
[Link]();}}}

#Registration Servlet ([Link]):


package [Link]; import [Link].*; import [Link].*; import [Link].*;
import [Link].*; public class RegisterServlet extends HttpServlet { private Connection connection;
@Override public void init() throws ServletException { try {
[Link]("[Link]"); connection =
[Link](
"jdbc:mysql://localhost:3306/userdb", "username", "password");
} catch (Exception e) { throw new ServletException("Database connection failed", e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name = [Link]("name");
String password = [Link]("password");
String email = [Link]("email"); String phone = [Link]("phone");
[Link]("text/html"); PrintWriter out = [Link](); try {
String sql = "INSERT INTO users (name, password, email, phone) VALUES (?, ?, ?, ?)";
PreparedStatement stmt = [Link](sql); [Link](1, name);
[Link](2, password); [Link](3, email); [Link](4, phone);
int rows = [Link](); if (rows > 0) { [Link]("<html><body>");
[Link]("<h3>Registration Successful!</h3>"); [Link]("<p>Welcome, " + name +
"!</p>"); [Link]("<a href='[Link]'>Login Now</a> | "); [Link]("<a
href='[Link]'>View All Users</a>"); [Link]("</body></html>");
} else {
[Link]("<h3>Registration Failed!</h3>");
}
} catch (SQLException e) { if ([Link]() == 1062) {
[Link]("<h3>Email already exists!</h3>");
} else {
[Link](); [Link]("<h3>Database error occurred</h3>");
}
[Link]("<a href='[Link]'>Try Again</a>"); }}}
#Login HTML ([Link]):
<!DOCTYPE html>
<html>
<head>
<title>User Login</title>
<style>
body { font-family: Arial; max-width: 400px; margin: 50px auto; padding: 20px; }
.container { border: 1px solid #ddd; padding: 20px; border-radius: 5px; }
.form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; }
input[type="text"], input[type="password"] { width: 100%; padding: 8px; border: 1px solid
#ddd; border-radius: 3px;
}
button { background: #007bff; color: white; padding: 10px 20px; border: none;
border-radius: 3px; cursor: pointer;
}
.links { margin-top: 15px; text-align: center; }
</style>
</head>
<body>
<div class="container">
<h2>User Login</h2>
<form action="login" method="post">
<div class="form-group">
<label>Username:</label>
<input type="text" name="username" required>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" name="password" required>
</div>
<div class="form-group">
<label>
<input type="checkbox" name="remember"> Remember me
</label>
</div>
<button type="submit">Login</button>
</form>
<div class="links">
<a href="[Link]">Create New Account</a> |
<a href="[Link]">View All Users</a>
</div>
</div>
</body>
</html>
#Registration HTML ([Link]):
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
<style> body { font-family: Arial; max-width: 400px; margin: 50px auto; padding: 20px; }
.container { border: 1px solid #ddd; padding: 20px; border-radius: 5px; }
.form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; }
input[type="text"], input[type="password"], input[type="email"], input[type="tel"] { width:
100%; padding: 8px; border: 1px solid #ddd; border-radius: 3px;
}
button { background: #28a745; color: white; padding: 10px 20px; border: none;
border-radius: 3px; cursor: pointer;
}
.links { margin-top: 15px; text-align: center; }
</style>
</head>
<body>
<div class="container">
<h2>User Registration</h2>
<form action="register" method="post">
<div class="form-group">
<label>Full Name:</label>
<input type="text" name="name" required>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" name="password" required>
</div>
<div class="form-group">
<label>Email:</label>
<input type="email" name="email" required>
</div>
<div class="form-group">
<label>Phone Number:</label>
<input type="tel" name="phone">
</div>
<button type="submit">Register</button>
</form>
<div class="links">
<a href="[Link]">Back to Login</a>
</div>
</div>
</body>
</htm l>
#Welcome JSP ([Link]):
<%@ page import="[Link].*, [Link]" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
<style> body { font-family: Arial; max-width: 800px; margin: 0 auto; padding: 20px; }
.welcome { background: #d4edda; padding: 20px; border-radius: 5px; margin-bottom: 20px; }
.user-info { background: #f8f9fa; padding: 15px; border-radius: 5px; }
</style>
</head>
<body>
<%
String username = (String) [Link]("username"); if (username == null) {
[Link]("[Link]");
return;
}
// Check for cookies
Cookie[] cookies = [Link](); String cookieInfo = ""; if (cookies != null) {
for (Cookie cookie : cookies) { if ("userCredentials".equals([Link]())) {
cookieInfo = " (Remembered via Cookie)"; break;}}} %>
<div class="welcome">
<h1>Welcome, <%= username %>!</h1>
<p>You have successfully logged in<%= cookieInfo %></p>
</div>
<div class="user-info">
<h3>Your Session Information:</h3>
<p><strong>Username:</strong> <%= username %></p>
<p><strong>Email:</strong> <%= [Link]("userEmail") %></p>
<p><strong>Session ID:</strong> <%= [Link]() %></p>
</div>
<div style="margin-top: 20px;">
<a href="[Link]">View All Registered Users</a> |
<a href="logout">Logout</a>
</div>
</body>
</html>
#Users Display JSP ([Link]):
</body><%@ page import="[Link].*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>All Registered Users</title>
<style>
body { font-family: Arial; max-width: 1000px; margin: 0 auto; padding: 20px; } table {
width: 100%; border-collapse: collapse; margin-top: 20px; } th, td { border: 1px solid #ddd;
padding: 12px; text-align: left; } th { background-color: #f2f2f2; }
tr:nth-child(even) { background-color: #f9f9f9; }
.header { background: #007bff; color: white; padding: 20px; border-radius: 5px; }
</style>
</head>
<body>
<div class="header">
<h1>Registered Users</h1>
<p>Total users in the system</p>
</div>
<%
Connection connection = null;
try {
[Link]("[Link]"); connection =
[Link](
"jdbc:mysql://localhost:3306/userdb", "username", "password");
String sql = "SELECT * FROM users ORDER BY reg_date DESC";
Statement stmt = [Link]();
ResultSet rs = [Link](sql);
%>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Registration Date</th>
</tr>
</thead>
<tbody>
<% while ([Link]()) {
%>
<tr>
<td><%= [Link]("id") %></td>
<td><%= [Link]("name") %></td>
<td><%= [Link]("email") %></td>
<td><%= [Link]("phone") %></td>
<td><%= [Link]("reg_date") %></td>
</tr>
<% } %>
</tbody>
</table>
<%
} catch (Exception e) {
[Link](); [Link]("<p style='color: red;'>Error loading users: " +
[Link]() + "</p>");
} finally { if (connection != null) {
try { [Link](); } catch (SQLException e) { [Link](); }}}
%>
<div style="margin-top: 20px;">
<a href="[Link]">Login</a> |
<a href="[Link]">Register New User</a> |
<a href="[Link]">Dashboard</a>
</div> </body> </html>
#Logout Servlet ([Link]):
package [Link]; import [Link].*; import [Link].*; import [Link].*;
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { HttpSession session = [Link](false); if (session
!= null) { [Link]();
}
// Clear remember me cookie
Cookie cookie = new Cookie("userCredentials", ""); [Link](0);
[Link](cookie); [Link]("[Link]");
}}
(10). Create a user registration system using Servlet/JSP connected to a database with fields:
• name, password, email, phone number
• Display all registered users dynamically.

I'll provide you with a complete user registration system using Servlet/JSP with MySQL database. ➢
Database Setup:
Create database
CREATE DATABASE user_management;
USE user_management;
-- Create users table CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL, password VARCHAR(255) NOT NULL, email
VARCHAR(150) UNIQUE NOT NULL, phone VARCHAR(15), registration_date
TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Insert sample data
INSERT INTO users (name, password, email, phone) VALUES
('John Doe', 'password123', '[Link]@[Link]', '1234567890'),
('Jane Smith', 'pass123', '[Link]@[Link]', '2345678901'), ('Mike Johnson', 'mikepass',
'[Link]@[Link]', '3456789012');
➢ User Model Class:
package [Link]; import [Link]; public class User { private int id;
private String name; private String password; private String email; private String phone;
private Timestamp registrationDate;
// Constructors public User() {} public User(String name, String password, String email,
String phone) { [Link] = name; [Link] = password; [Link] = email;
[Link] = phone;
}
// Getters and Setters public int getId() { return id; } public void setId(int id) { [Link] = id; }
public String getName() { return name; } public void setName(String name) { [Link] = name;
} public String getPassword() { return password; } public void setPassword(String password) {
[Link] = password; } public String getEmail() { return email; }
public void setEmail(String email) { [Link] = email; } public String getPhone() { return
phone; }
public void setPhone(String phone) { [Link] = phone; } public Timestamp
getRegistrationDate() { return registrationDate; } public void setRegistrationDate(Timestamp
registrationDate) { [Link] = registrationDate;
} @Override public String toString() { return "User{id=" + id + ", name='" + name +
"', email='" + email + "'}";
}}
➢ User DAO (Data Access Object)
package [Link]; import [Link]; import
[Link]; import [Link].*; import [Link]; import [Link];
public class UserDAO { // Create a new user
public boolean createUser(User user) {
String sql = "INSERT INTO users (name, password, email, phone) VALUES (?, ?, ?, ?)";
try (Connection conn = [Link](); PreparedStatement stmt =
[Link](sql)) { [Link](1, [Link]()); [Link](2,
[Link]()); [Link](3, [Link]()); [Link](4,
[Link]()); int rowsAffected = [Link](); return rowsAffected > 0;
} catch (SQLException e) { [Link](); return false;
}
}
// Get all users
public List<User> getAllUsers() {
List<User> users = new ArrayList<>();
String sql = "SELECT * FROM users ORDER BY registration_date DESC"; try
(Connection conn = [Link]();
Statement stmt = [Link](); ResultSet rs = [Link](sql)) {
while ([Link]()) { User user = new User(); [Link]([Link]("id"));
[Link]([Link]("name")); [Link]([Link]("password"));
[Link]([Link]("email")); [Link]([Link]("phone"));
[Link]([Link]("registration_date")); [Link](user);
}
} catch (SQLException e) { [Link]();
}
return users;
}
// Delete user by ID
public boolean deleteUser(int userId) { String sql = "DELETE FROM users WHERE id = ?";
try (Connection conn = [Link](); PreparedStatement stmt =
[Link](sql)) {
[Link](1, userId); int rowsAffected = [Link]();
return rowsAffected > 0; } catch (SQLException e) { [Link]();
return false;
}
}
// Check if email already exists public boolean emailExists(String email) {
String sql = "SELECT COUNT(*) FROM users WHERE email = ?"; try (Connection
conn = [Link](); PreparedStatement stmt =
[Link](sql)) {
[Link](1, email); ResultSet rs = [Link](); if
([Link]()) {
return [Link](1) > 0;
}
} catch (SQLException e) { [Link]();
}
return false;
}
}

➢ Registration Servlet
package [Link]; import [Link]; import
[Link]; import [Link].*; import [Link].*; import [Link].*;
public class RegisterServlet extends HttpServlet { private UserDAO userDAO;
@Override
public void init() throws ServletException { userDAO = new UserDAO();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get form parameters
String name = [Link]("name");
String password = [Link]("password");
String email = [Link]("email");
String phone = [Link]("phone");
// Validate input if (name == null || [Link]().isEmpty() || password == null ||
[Link]().isEmpty() || email == null || [Link]().isEmpty()) {
[Link]("errorMessage", "Name, password, and email are required fields.");
[Link]("[Link]").forward(request, response); return;
}
// Check if email already exists if ([Link](email)) {
[Link]("errorMessage", "Email already exists. Please use a different email.");
[Link]("[Link]").forward(request, response); return;
}
// Create user object
User user = new User([Link](), [Link](), [Link](), phone !=
null ? [Link]() : null);
boolean success = [Link](user);
if (success) {
[Link]("successMessage", "Registration successful! Welcome " + name);
[Link]("user", user);
[Link]("[Link]").forward(request, response);
} else {
[Link]("errorMessage", "Registration failed. Please try again.");
[Link]("[Link]").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("[Link]");
}
}
➢ User List Servlet
package [Link];
import [Link];
import [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
public class UserListServlet extends HttpServlet { private UserDAO userDAO;
@Override public void init() throws ServletException { userDAO = new UserDAO();}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get all users from database
List<User> users = [Link](); // Set users in request attribute
[Link]("users", users);
// Forward to JSP page
RequestDispatcher dispatcher = [Link]("[Link]");
[Link](request, response);
}
}
➢ Delete User Servlet
package [Link]; import [Link];
import [Link].*; import [Link].*; import [Link].*;
public class DeleteUserServlet extends HttpServlet { private UserDAO userDAO; public void
init() throws ServletException { userDAO = new UserDAO();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { String userIdStr = [Link]("userId");
if (userIdStr != null && ![Link]().isEmpty()) { try {
int userId = [Link](userIdStr);
boolean success = [Link](userId); if (success) {
[Link]().setAttribute("message", "User deleted successfully!");
} else {
[Link]().setAttribute("message", "Failed to delete user.");
}
} catch (NumberFormatException e) {
[Link]().setAttribute("message", "Invalid user ID.");
}
}
[Link]("user-list");
}
}
➢ JSP Pages
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>User Registration</title>
<link rel="stylesheet" type="text/css" href="[Link]">
</head>
<body>
<div class="container">
<div class="header">
<h1>User Registration</h1>
<p>Create a new account</p>
</div>
<%-- Display error message --%>
<%
String errorMessage = (String) [Link]("errorMessage"); if
(errorMessage != null) {
%>
<div class="error-message">
<%= errorMessage %>
</div>
<%
}
%>
<form action="register" method="post" class="registration-form">
<div class="form-group">
<label for="name">Full Name *</label>
<input type="text" id="name" name="name" required value="<%=
[Link]("name") != null ? [Link]("name") : "" %>">
</div>
<div class="form-group">
<label for="password">Password *</label>
<input type="password" id="password" name="password" required>
</div>
<div class="form-group">
<label for="email">Email Address *</label>
<input type="email" id="email" name="email" required
value="<%= [Link]("email") != null ? [Link]("email") :
"" %>"> </div>
<div class="form-group">
<label for="phone">Phone Number</label> <input type="tel" id="phone"
name="phone"
value="<%= [Link]("phone") != null ? [Link]("phone") :
"" %>">
</div>
<button type="submit" class="btn-primary">Register</button>
</form>
<div class="links">
<a href="user-list">View All Registered Users</a>
</div>
</div>
</body>
</html>
➢ [Link]
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Registration Successful</title>
<link rel="stylesheet" type="text/css" href="[Link]">
</head>
<body>
<div class="container">
<div class="success-header">
<h1> Registration Successful!</h1>
</div> <%
String successMessage = (String) [Link]("successMessage");
[Link] user = ([Link]) [Link]("user");
%>
<div class="success-message">
<p><%= successMessage %></p>
</div>
<% if (user != null) { %>
<div class="user-details">
<h3>Your Details:</h3>
<table class="user-info">
<tr>
<td><strong>Name:</strong></td>
<td><%= [Link]() %></td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td><%= [Link]() %></td>
</tr>
<tr>
<td><strong>Phone:</strong></td>
<td><%= [Link]() != null ? [Link]() : "Not provided" %></td>
</tr>
</table>
</div>
<% } %>
<div class="action-buttons">
<a href="[Link]" class="btn-secondary">Register Another User</a>
<a href="user-list" class="btn-primary">View All Users</a> </div>
</div>
</body>
</html>
➢ [Link]
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="[Link], [Link]" %>
<html>
<head>
<title>Registered Users</title>
<link rel="stylesheet" type="text/css" href="[Link]">
</head>
<body>
<div class="container">
<div class="header">
<h1>Registered Users</h1>
<p>All users in the system</p>
</div>
<%-- Display message --%>
<%
String message = (String) [Link]("message"); if (message != null) {
%>
<div class="info-message">
<%= message %>
</div>
<%
[Link]("message");
}
%> <%
List<User> users = (List<User>) [Link]("users"); if (users == null ||
[Link]()) {
%>
<div class="no-users">
<p>No users registered yet.</p>
</div>
<%
} else {
%>
<div class="users-table-container">
<table class="users-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Registration Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody> <%
for (User user : users) {
%>
<tr>
<td><%= [Link]() %></td>
<td><%= [Link]() %></td>
<td><%= [Link]() %></td>
<td><%= [Link]() != null ? [Link]() : "N/A" %></td>
<td><%= [Link]() %></td>
<td>
<form action="delete-user" method="post" class="delete-form">
<input type="hidden" name="userId" value="<%= [Link]() %>">
<button type="submit" class="btn-danger"
onclick="return confirm('Are you sure you want to delete this user?')">
Delete
</button>
</form>
</td>
</tr>
<%
}
%>
</tbody>
</table>
<div class="stats">
<p>Total Users: <strong><%= [Link]() %></strong></p>
</div>
</div>
<%
}
%>
<div class="action-buttons">
<a href="[Link]" class="btn-primary">Register New User</a>
</div>
</div>
</body>
</html>
➢ CSS Styling
<style>*{margin:0;padding:0;box-sizing:border-box;}body{font-family:'Segoe
UI',Tahoma,Geneva,Verdana,sans-serif;background-
color:#f5f5f5;lineheight:1.6;color:#333;}.container{max-width:1000px;margin:0
auto;padding:20px;}.header{background:linear-gradient(135deg,#667eea 0%,#764ba2
100%);color:white;padding:30px;border-radius:10px;margin-bottom:30px;text-align:center;}.header
h1{font-size:2.5em;marginbottom:10px;}.header p{font-size:1.1em;opacity:0.9;}.success-
header{background:linear-gradient(135deg,#4CAF50 0%,#45a049
100%);color:white;padding:30px;border-radius:10px;margin-bottom:30px;text-
align:center;}.registrationform{background:white;padding:30px;border-radius:10px;box-shadow:0
4px 6px rgba(0,0,0,0.1);margin-bottom:20px;}.form-group{marginbottom:20px;}.form-group
label{display:block;margin-bottom:5px;font-weight:600;color:#555;}.form-group
input{width:100%;padding:12px;border:2px solid #ddd;border-radius:5px;font-
size:16px;transition:border-color 0.3s;}.form-group input:focus{outline:none;border-
color:#667eea;}.btn-primary{background:#667eea;color:white;padding:12px
30px;border:none;borderradius:5px;font-size:16px;cursor:pointer;text-
decoration:none;display:inline-block;transition:background
0.3s;}.btnprimary:hover{background:#5a6fd8;}.btn-
secondary{background:#6c757d;color:white;padding:12px 30px;border:none;border-
radius:5px;fontsize:16px;cursor:pointer;text-decoration:none;display:inline-
block;transition:background 0.3s;}.btn-
secondary:hover{background:#5a6268;}.btndanger{background:#dc3545;color:white;padding:8px
15px;border:none;border-radius:3px;font-size:14px;cursor:pointer;transition:background 0.3s;}.btn-
danger:hover{background:#c82333;}.error-
message{background:#f8d7da;color:#721c24;padding:15px;border-
radius:5px;marginbottom:20px;border:1px solid #f5c6cb;}.success-
message{background:#d4edda;color:#155724;padding:15px;border-
radius:5px;marginbottom:20px;border:1px solid #c3e6cb;}.info-
message{background:#d1ecf1;color:#0c5460;padding:15px;border-
radius:5px;marginbottom:20px;border:1px solid #bee5eb;}.users-table-
container{background:white;padding:20px;border-radius:10px;box-shadow:0 4px 6px
rgba(0,0,0,0.1);margin-bottom:20px;overflow-x:auto;}.users-table{width:100%;border-
collapse:collapse;}.users-table th,.users-table td{padding:12px;text-align:left;border-bottom:1px
solid #ddd;}.users-table th{background-color:#f8f9fa;font-weight:600;color:#555;}.users-table
tr:hover{background-color:#f8f9fa;}.user-details{background:white;padding:20px;border-
radius:10px;box-shadow:0 4px 6px rgba(0,0,0,0.1);marginbottom:20px;}.user-
info{width:100%;border-collapse:collapse;}.user-info td{padding:8px;border-bottom:1px solid
#eee;}.nousers{background:white;padding:40px;text-align:center;border-radius:10px;box-shadow:0
4px 6px rgba(0,0,0,0.1);marginbottom:20px;}.stats{margin-
top:20px;padding:15px;background:#f8f9fa;border-radius:5px;text-align:center;}.action-
buttons{textalign:center;margin-top:20px;}.action-buttons a{margin:0 10px;}.links{text-
align:center;margin-top:20px;}.links a{color:#667eea;textdecoration:none;}.links a:hover{text-
decoration:underline;}.delete-form{display:inline;}</style>
➢ [Link] Configuration
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link] version="4.0">
<!-- Servlets -->
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet>
<servlet-name>UserListServlet</servlet-name>
<servlet-class>[Link]</servlet-class> </servlet>
<servlet>
<servlet-name>DeleteUserServlet</servlet-name>
<servlet-class>[Link]</servlet-class> </servlet>
<!-- Servlet Mappings -->
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UserListServlet</servlet-name>
<url-pattern>/user-list</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DeleteUserServlet</servlet-name>
<url-pattern>/delete-user</url-pattern>
</servlet-mapping>
<!-- Welcome Files -->
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
<!-- Session Configuration -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web- app>

You might also like