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

Institute Website HTML Design Guide

The document outlines a series of experiments focused on web development using HTML, CSS, and JavaScript. Each experiment has specific objectives, such as designing an institute website, creating forms for data entry, developing responsive websites, and implementing input validation. It details the hardware and software requirements, theoretical concepts, and provides example HTML code for practical implementation.

Uploaded by

ALL in tech
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)
4 views78 pages

Institute Website HTML Design Guide

The document outlines a series of experiments focused on web development using HTML, CSS, and JavaScript. Each experiment has specific objectives, such as designing an institute website, creating forms for data entry, developing responsive websites, and implementing input validation. It details the hardware and software requirements, theoretical concepts, and provides example HTML code for practical implementation.

Uploaded by

ALL in tech
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

Experiment No: 01

Objective: Write an HTML program for designing your institute website. Display departmental
information of your institute on the website.

Apparatus/Tools Used:
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory: Based on HTML & CSS

● Inline CSS: Styles are directly applied using the style attribute within the HTML tags.
● Header: Displays the name of the institute in a large, bold format.
● Navigation: A simple horizontal navigation bar with links (not functional in this
example).
● Department Section: Each department has a title and a brief description.
● Footer: Contains copyright information.

Method / Procedure:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Institute - Departmental Information</title>
</head>
<body>

<!-- Header with Institute Name and Motto -->


<header>
<h1>Institute of Technology</h1>
<h2 >Empowering Minds for a Brighter Future</h2>
<hr>
</header>

<!-- Navigation Section (using semantic tags) -->


<nav>
<h3>Quick Links</h3>
<ul>
<li><a href="#cs-department">Computer Science</a></li>
<li><a href="#me-department">Mechanical Engineering</a></li>
<li><a href="#ee-department">Electrical Engineering</a></li>
<li><a href="#ce-department">Civil Engineering</a></li>
<li><a href="#contact">Contact Us</a></li>
</ul>
<hr>
</nav>

<!-- Article section with information about the institute -->


<article>
<h3>About the Institute</h3>
<p>Our Institute is a premier educational institution providing high-quality education in
engineering and technology. We are committed to nurturing innovative minds and preparing
students for the challenges of tomorrow. Our state-of-the-art infrastructure and experienced
faculty ensure that students receive the best learning experience.</p>
</article>

<!-- Section for displaying departmental information -->


<section id="departments">
<h3>Departments at Institute</h3>

<!-- Computer Science Department -->


<section id="cs-department">
<h4>Department of Computer Science</h4>
<p>The Department of Computer Science offers cutting-edge courses in software
development, data science, and artificial intelligence. Our programs are designed to produce
industry-ready professionals.</p>

<h5>Courses Offered:</h5>
<ul>
<li>Bachelor of Science in Computer Science (BSc CS)</li>
<li>Master of Science in Computer Science (MSc CS)</li>
<li>Diploma in Software Engineering</li>
</ul>

<blockquote>
<p>"Innovating the future with technology." - Head of Department</p>
</blockquote>
</section>
<hr>

<!-- Mechanical Engineering Department -->


<section id="me-department">
<h4>Department of Mechanical Engineering</h4>
<p>The Mechanical Engineering Department focuses on design, manufacturing, and
thermal engineering. Our graduates are equipped with practical and theoretical knowledge to
excel in the industry.</p>

<h5>Courses Offered:</h5>
<ol>
<li>Bachelor of Technology in Mechanical Engineering (BTech ME)</li>
<li>Master of Technology in Mechanical Engineering (MTech ME)</li>
<li>Diploma in Automotive Engineering</li>
</ol>

<figure>
<img src="[Link]" alt="Mechanical Engineering Lab">
<figcaption>Mechanical Engineering Lab at ABC Institute</figcaption>
</figure>
</section>
<hr>

<!-- Electrical Engineering Department -->


<section id="ee-department">
<h4>Department of Electrical Engineering</h4>
<p>The Electrical Engineering Department specializes in power systems, electronics, and
renewable energy. We train students to contribute to sustainable energy solutions.</p>

<h5>Courses Offered:</h5>
<ul>
<li>Bachelor of Technology in Electrical Engineering (BTech EE)</li>
<li>Master of Technology in Electrical Engineering (MTech EE)</li>
<li>Diploma in Power Systems</li>
</ul>

<table border="1">
<caption>Program Details</caption>
<thead>
<tr>
<th>Program Name</th>
<th>Duration</th>
<th>Eligibility</th>
</tr>
</thead>
<tbody>
<tr>
<td>BTech EE</td>
<td>4 Years</td>
<td>12th with Science</td>
</tr>
<tr>
<td>MTech EE</td>
<td>2 Years</td>
<td>BTech in Electrical Engineering</td>
</tr>
</tbody>
</table>
</section>
<hr>

<!-- Civil Engineering Department -->


<section id="ce-department">
<h4>Department of Civil Engineering</h4>
<p>The Civil Engineering Department focuses on the design, construction, and
maintenance of infrastructure. Our students are prepared to take on the challenges of urban
development and environmental engineering.</p>

<h5>Courses Offered:</h5>
<ul>
<li>Bachelor of Technology in Civil Engineering (BTech CE)</li>
<li>Master of Technology in Structural Engineering (MTech SE)</li>
<li>Diploma in Construction Technology</li>
</ul>

<details>
<summary>More Information about Civil Engineering</summary>
<p>Civil Engineering is one of the oldest and most important branches of engineering.
It involves the development of roads, bridges, buildings, and other infrastructure projects that
form the foundation of modern society.</p>
</details>
</section>
</section>

<!-- Contact Section -->


<footer id="contact">
<h3>Contact Us</h3>
<address>
ABC Institute<br>
Main Road, City XYZ, Country<br>
Phone: +123 456 7890<br>
Email: <a href="[Link]
</address>
<p>&copy; 2024 ABC Institute. All rights reserved.</p>
</footer>

</body>
</html>
Input: Source code in terms of HTML and CSS files

Figure: - 1.1: Input Screenshot for designing your institute website


Output: Webpage Display of Webpage
Figure: - 1.2: Output Screenshot for designing your institute website
Experiment No: 2

Objective: Write an HTML program to design an entry form for student details/employee
information/faculty details.

Apparatus Used: -
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory:

● Full Name: Text input for entering the person's full name.
● Email: Email input field with validation.
● Contact Number: Telephone number input.
● Role Selection: Dropdown menu to select the role (Student, Employee, Faculty).
● Address: Textarea for entering the address.
● Submit Button: A large, cantered submit button.

Method / Procedure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Details Entry Form</title>
</head>
<body>

<h1>Student Details Entry Form</h1>

<!-- Form to capture student details -->


<form action="/submit" method="post">
<!-- Student Name -->
<label for="student_name">Student Name:</label>
<input type="text" id="student_name" name="student_name" required>
<br><br>

<!-- Date of Birth -->


<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required>
<br><br>

<!-- Gender -->


<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="Male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label>
<input type="radio" id="other" name="gender" value="other">
<label for="other">other</label>
<br><br>

<!-- Email -->


<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<!-- Phone Number -->
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" pattern="[0-9]{10}"
placeholder="1234567890" required>
<br><br>

<!-- Course -->


Figure: - 3.4: Output Screenshot for responsive website
Experiment No: 03

Objective: Develop a responsive website using CSS and HTML. Website may be for
tutorial/blogs/commercial website.

Apparatus/Tools Used:
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Website</title>

<style>
body {
margin: 0;
font-family: Arial, sans-serif;
background-color: #f2f2f2;
}

/* Navigation Bar */
nav {
background-color: #003366;
color: white;
padding: 15px;
display: flex;
justify-content: space-between;
align-items: center;
}

nav .logo {
font-size: 22px;
font-weight: bold;
}

nav ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
}

nav ul li {
margin: 0 15px;
}

nav ul li a {
text-decoration: none;
color: white;
font-weight: bold;
}

/* Hero Section */
.hero {
background: url('[Link] no-repeat center/cover;
height: 350px;
display: flex;
justify-content: center;
align-items: center;
color: white;
text-align: center;
}

.hero h1 {
font-size: 45px;
background-color: rgba(0, 0, 0, 0.5);
padding: 10px 20px;
}

/* Cards Section */
.container {
padding: 30px;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.card {
background-color: white;
width: 30%;
padding: 20px;
box-shadow: 0 0 10px #aaa;
margin-bottom: 20px;
border-radius: 10px;
}

.card h3 {
color: #003366;
}

.card p {
color: #444;
}
/* Footer */
footer {
background-color: #003366;
color: white;
text-align: center;
padding: 15px;
margin-top: 20px;
}
/* RESPONSIVE DESIGN */
@media (max-width: 900px) {
.card {
width: 45%;
}
}
@media (max-width: 600px) {
nav ul {
flex-direction: column;
text-align: center;
}
nav ul li {
margin: 10px 0;
}
.card {
width: 100%;
} .hero h1 {
font-size: 30px;
}
}
</style>
</head>
<body>
<!-- Navigation -->
<nav>
<div class="logo">My Responsive Website</div>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Tutorials</a></li>
<li><a href="#">Blogs</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<section class="hero">
<h1>Welcome to My Tutorial & Blog Website</h1>
</section>
<!-- Cards Section -->
<div class="container">
<div class="card">
<h3>Web Development</h3>
<p>Learn HTML, CSS, JavaScript, and full-stack development tutorials.</p>
</div>
<div class="card">
<h3>Tech Blogs</h3>
<p>Read articles about latest technologies, gadgets, and innovations.</p>
</div>

<div class="card">
<h3>Commercial Services</h3>
<p>We provide website design, digital marketing, and SEO services.</p>
</div>
</div>
<!-- Footer -->
<footer>
© 2025 My Responsive Website | Designed with HTML & CSS
</footer>
</body>
</html>
Experiment No: 4

Objective: Write programs using HTML and JavaScript for validation of input data.
Apparatus/Tools Used:
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory: Based on HTML & CSS

● Header: Contains the title and a brief tagline for the website.
● Navigation Bar: A responsive menu that adjusts to screen sizes. Links highlight when
hovered.
● Main Content: Contains blog posts with a title, short description, and "Read More" link.
● Footer: Displays copyright information.
● Responsive Design: Uses media queries to adjust the layout for tablet and mobile
screens.

Method / Procedure:
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<script>
function validateForm() {
var email = [Link]["myForm"]["email"].value; var pwd =
[Link]["myForm"]["password"].value; var emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (![Link](email)) { alert("Please enter a valid email."); return false;
}
if ([Link] < 6) {
alert("Password must be at least 6 characters."); return false;
}
alert("Validation successful!"); return true;
}
</script>
</head>
<body>
<h2>Login Form</h2>
<form name="myForm" onsubmit="return validateForm()"> Email: <input type="text"
name="email"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Input: -

Figure: - 4.1: Input Screenshot of using JavaScript for Validation of Input Data

Output: -
Figure: - 4.2: Output Screenshot of using JavaScript for Validation of Input Data

Figure: - 4.3: Output Screenshot of using JavaScript for Validation of Input Data
Experiment No: 5

Objective: Write a program in XML for creation of DTD, which specifies a set of rules. Create a
style sheet in CSS/ XSL & display the document in internet explorer.

Apparatus/Tools Used :
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory : Based on XML, DTD & CSS

● DTD (Document Type Definition): Defines the structure and the legal elements and
attributes of your XML document.
● XML Document: Contains the actual data structured according to the DTD.
● CSS Stylesheet: Styles the XML document to make it visually appealing.
● Displaying in Internet Explorer: Steps to view the styled XML in IE.

Method/Procedure/Overview:

Create the DTD ([Link])

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE employees [
<!ELEMENT employees (employee+)>
<!ELEMENT employee (name, id, position, department)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT position (#PCDATA)>
<!ELEMENT department (#PCDATA)>
]>

Create the XML Document ([Link])

<?xml version="1.0" encoding="UTF-8"?>


<?xml-stylesheet type="text/css" href="[Link]"?>
<!DOCTYPE employees SYSTEM "[Link]">
<employees>
<employee>
<name>John Doe</name>
<id>12345</id>
<position>Software Engineer</position>
<department>IT</department>
</employee>
<employee>
<name>Jane Smith</name>
<id>67890</id>
<position>Project Manager</position>
<department>Operations</department>
</employee>
<employee>
<name>Robert Brown</name>
<id>11223</id>
<position>UX Designer</position>
<department>Design</department>
</employee>
</employees>

Create the CSS Stylesheet ([Link])

/* General Styles */
body {
font-family: Arial, sans-serif;
background-color: #eef2f3;
margin: 20px;
}

/* Root Element */
employees {
display: block;
margin: 0 auto;
max-width: 800px;
}

/* Employee Entries */
employee {
display: block;
border: 2px solid #4CAF50;
padding: 15px;
margin-bottom: 20px;
border-radius: 8px;
background-color: #ffffff;
box-shadow: 2px 2px 12px rgba(0,0,0,0.1);
}

/* Child Elements */
name {
display: block;
font-size: 1.5em;
color: #333333;
margin-bottom: 10px;
}

id, position, department {


display: block;
font-size: 1.1em;
color: #555555;
margin: 5px 0;
}

/* Hover Effects */
employee:hover {
border-color: #2e7d32;
box-shadow: 4px 4px 16px rgba(0,0,0,0.2);
}

Input: Source code in terms of XML and DTD files


Figure: - 5.1: Input Screenshot of XML program to create DTD

Output: Webpage Display of Webpage/Data Capture by Parser


Figure: - 5.2: Output Screenshot of XML program to create DTD

Figure: - 5.3: Output Screenshot of XML program to create DTD


Experiment No: 6

Objective: Create a Java Bean for Employee information (EmpID, Name, Salary, Designation
and Department)

Apparatus/Tools Used :
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory : Based on Java Beans

● Private Fields: empID, name, salary, designation, and department are private to follow
encapsulation principles.
● Public Getter and Setter Methods: These methods provide access to the private fields.
● No-Argument Constructor: Every JavaBean must have a default no-argument
constructor. This is required for tools that instantiate beans via reflection.
● Serializable Interface: JavaBeans should implement Serializable to allow instances to be
serialized, enabling saving or transferring objects.
● Optional Constructor: An additional constructor with arguments is provided to easily
create Employee objects with data.
● toString() Method: This method is overridden to provide a human-readable
representation of the Employee object, making it easier to print out details during testing.

Method / Procedure:
[Link] (Java Bean for Employee)

import [Link];

public class Employee implements Serializable {


private static final long serialVersionUID = 1L;

// Private fields (properties)


private int empID;
private String name;
private double salary;
private String designation;
private String department;

// Default no-arg constructor (required for a JavaBean)


public Employee() {
}

// Constructor with parameters (optional, but useful)


public Employee(int empID, String name, double salary, String designation, String
department) {
[Link] = empID;
[Link] = name;
[Link] = salary;
[Link] = designation;
[Link] = department;
}

// Getter and Setter for empID


public int getEmpID() {
return empID;
}

public void setEmpID(int empID) {


[Link] = empID;
}

// Getter and Setter for name


public String getName() {
return name;
}

public void setName(String name) {


[Link] = name;
}

// Getter and Setter for salary


public double getSalary() {
return salary;
}

public void setSalary(double salary) {


[Link] = salary;
}

// Getter and Setter for designation


public String getDesignation() {
return designation;
}

public void setDesignation(String designation) {


[Link] = designation;
}

// Getter and Setter for department


public String getDepartment() {
return department;
}

public void setDepartment(String department) {


[Link] = department;
}

// Optional: Overriding toString() method for easy display


@Override
public String toString() {
return "Employee [EmpID=" + empID + ", Name=" + name + ", Salary=" + salary
+ ", Designation=" + designation + ", Department=" + department + "]";
}
}

Example of Usage:

public class TestEmployee {


public static void main(String[] args) {
// Creating an Employee object using default constructor
Employee emp1 = new Employee();
[Link](101);
[Link]("John Doe");
[Link](50000);
[Link]("Software Engineer");
[Link]("IT");

// Printing employee details


[Link](emp1);

// Creating an Employee object using parameterized constructor


Employee emp2 = new Employee(102, "Jane Smith", 60000, "Project Manager",
"Operations");

// Printing employee details


[Link](emp2);
}
}

Input: Source code in terms of Java Bean and Test Bean files
Figure: - 6.1: Input Screenshot for Java Bean and Test Bean
Output:

Figure: - 6.2: Output Screenshot for Java Bean and Test Bean
Experiment No: 7

Objective: Build a command-line utility using [Link] that performs a specific task, such as
converting text to uppercase, calculating the factorial of a number, or generating random
passwords.
Apparatus/Tools Used:
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory: Based on [Link]


● Initialize [Link] Project: Open a terminal (Command Prompt or PowerShell), navigate
to your desired directory, and run:

npm init -y

● Create a JavaScript file (e.g., [Link]): Create a new file called [Link] in your project
directory.

Method / Procedure:

[Link] ([Link] Code)

// Importing necessary modules


const readline = require('readline');

// Create readline interface for input/output operations


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

// Function to convert text to uppercase


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

// Function to calculate factorial of a number


function calculateFactorial(num) {
if (num === 0 || num === 1) return 1;
return num * calculateFactorial(num - 1);
}

// Function to generate random password


function generatePassword(length = 8) {
const chars =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&
*()_+';
let password = '';
for (let i = 0; i < length; i++) {
password += [Link]([Link]([Link]() * [Link]));
}
return password;
}

// Command-line menu
function showMenu() {
[Link]("\nPlease choose one of the following options:");
[Link]("1. Convert text to uppercase");
[Link]("2. Calculate factorial of a number");
[Link]("3. Generate a random password");
[Link]("4. Exit");

[Link]("\nEnter your choice (1-4): ", (choice) => {


switch (choice) {
case '1':
[Link]("Enter the text to convert: ", (text) => {
[Link](`Uppercase: ${convertToUpper(text)}`);
showMenu();
});
break;

case '2':
[Link]("Enter a number to calculate its factorial: ", (number) => {
const num = parseInt(number);
if (!isNaN(num) && num >= 0) {
[Link](`Factorial of ${num}: ${calculateFactorial(num)}`);
} else {
[Link]("Please enter a valid non-negative number.");
}
showMenu();
});
break;

case '3':
[Link]("Enter the length of the password (default is 8): ", (length) => {
const pwdLength = parseInt(length) || 8;
[Link](`Generated Password: ${generatePassword(pwdLength)}`);
showMenu();
});
break;

case '4':
[Link]("Exiting...");
[Link]();
break;

default:
[Link]("Invalid choice. Please try again.");
showMenu();
}
});
}

// Start the utility by showing the menu


showMenu();

Explanation:

● convertToUpper: Converts the input text to uppercase.


● calculateFactorial: Recursively calculates the factorial of a non-negative integer.
● generatePassword: Generates a random password of specified length (default is 8
characters if no input is provided).
● readline: Used for interacting with users via the command line.
● showMenu: Presents a menu to the user for selecting tasks.

Input: Source code in terms of HTML and CSS files


Figure: - 7.1: Input Screenshot for command-line utility using [Link]
Output: Webpage Display of Webpage

Figure: - 7.2: Output Screenshot for command-line utility using [Link]


Experiment No: 8

Objective: To develop a script using MongoDB's aggregation framework to perform operations


like grouping, filtering, and sorting, we need to:
● Connect to MongoDB using [Link].
● Use MongoDB's aggregation framework to perform tasks like grouping users by cities,
calculating average age, filtering data, and sorting results.
Apparatus/Tools Used:
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory: MongoDB is a NoSQL, document-oriented database that stores data in JSON-like


BSON format, allowing for flexible and scalable schema design. MongoDB programs are
typically designed to demonstrate the creation, manipulation, and querying of databases using
CRUD operations (Create, Read, Update, Delete). These programs enable students to understand
how non-relational databases handle data differently from traditional RDBMS.
Method / Procedure:
Sample Data:

{
"_id": ObjectId("1"),
"name": "John Doe",
"age": 28,
"city": "New York"
},
{
"_id": ObjectId("2"),
"name": "Jane Smith",
"age": 34,
"city": "Los Angeles"
},
{
"_id": ObjectId("3"),
"name": "Alex Johnson",
"age": 22,
"city": "New York"
},
{
"_id": ObjectId("4"),
"name": "Emily Davis",
"age": 29,
"city": "Chicago"
}

MongoDB Aggregation Script ([Link])

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

// MongoDB connection URI


const uri = "mongodb://localhost:27017"; // Replace with your MongoDB URI
const client = new MongoClient(uri);

async function runAggregation() {


try {
await [Link]();

const database = [Link]('testDB'); // Replace 'testDB' with your DB name


const collection = [Link]('users'); // Replace 'users' with your collection name

// Aggregation pipeline
const pipeline = [
{
// Stage 1: Filter out users with age < 25
$match: {
age: { $gte: 25 }
}
},
{
// Stage 2: Group by 'city' and calculate the average age
$group: {
_id: "$city",
averageAge: { $avg: "$age" },
totalUsers: { $sum: 1 }
}
},
{
// Stage 3: Sort by averageAge in descending order
$sort: {
averageAge: -1
}
}
];

// Execute the aggregation pipeline


const result = await [Link](pipeline).toArray();

[Link]("Aggregation Result:", result);

} catch (error) {
[Link]("Error during aggregation:", error);
} finally {
await [Link]();
}
}
runAggregation();

Explanation of the Aggregation Stages:

● $match: Filters the documents by selecting only those users whose age is greater than
or equal to 25.
● $group: Groups the documents by the city field. It calculates:
o The average age ($avg) for each group (city).
o The total number of users ($sum) in each city.
● $sort: Sorts the results by averageAge in descending order.

How to Run the Script:

1. Start your MongoDB service locally or ensure MongoDB Atlas is connected.


2. Run the [Link] script using:

node [Link]
Input: -
Figure: - 8.1: Input Screenshot for developing script using MongoDB's aggregation framework

Output:

Figure: - 8.1: Output Screenshot for developing script using MongoDB's aggregation framework
Experiment No: 9

Objective: 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 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.

Apparatus/Tools Used:
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory: Based on HTML & Servlet

● Create the Login Form ([Link]):


A simple form that takes a username and password as input.
● Create the Servlet ([Link]):
This servlet will handle the login logic, create cookies for storing users and their passwords, and
authenticate users based on cookie values.
Method / Procedure:

<?php

setcookie("uid1","user1");

setcookie("pwd1","pwd1");

setcookie("uid2","user2");

setcookie("pwd2","pwd2");

setcookie("uid3","user3");

setcookie("pwd3","pwd3");

setcookie("uid4","user4");

setcookie("pwd4","pwd4");

?>

Login Page
<!DOCTYPE html>

<html>

<head>

<title>User Authentication</title>

</head>

<body>

<h1 align="center">LOGIN</h1>

<form action="[Link]" method="post">

<table align="center" cellspacing="10">

<tr>

<td><b>User ID</b></td>

<td><input name="uid" type="text"></td>

</tr>

<tr>

<td><b>Password</b></td>

<td><input name="pwd" type="password"></td>

</tr>

<tr>

<td colspan="2" align="center">

<input type="submit" name="submit" value="Login"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="reset" value="Clear">

</td>

</tr>

</table>

</form>

</body>

</html>
[Link]

<!DOCTYPE html>

<html>

<head>

<title>User Authentication</title>

</head>

<body>

<?php

if ($_POST["uid"]==$_COOKIE["uid1"] && $_POST["pwd"]==$_COOKIE["pwd1"]) {

echo "Welcome ".$_POST["uid"];

else if ($_POST["uid"]==$_COOKIE["uid2"] && $_POST["pwd"]==$_COOKIE["pwd2"]) {

echo "Welcome ".$_POST["uid"];

else if ($_POST["uid"]==$_COOKIE["uid3"] && $_POST["pwd"]==$_COOKIE["pwd3"]) {

echo "Welcome ".$_POST["uid"];

else if ($_POST["uid"]==$_COOKIE["uid4"] && $_POST["pwd"]==$_COOKIE["pwd4"]) {

echo "Welcome ".$_POST["uid"];

else{

echo "You are not an authenticated user.";

?>

</body>
</html>

<?php

setcookie("uid1","user1");

setcookie("pwd1","pwd1");

setcookie("uid2","user2");

setcookie("pwd2","pwd2");

setcookie("uid3","user3");

setcookie("pwd3","pwd3");

setcookie("uid4","user4");

setcookie("pwd4","pwd4");

?>

<!DOCTYPE html>

<html>

<head>

<title>User Authentication</title>

</head>

<body>

<h1 align="center">LOGIN</h1>

<form action="[Link]" method="post">

<table align="center" cellspacing="10">

<tr>

<td><b>User ID</b></td>

<td><input name="uid" type="text"></td>

</tr>

<tr>

<td><b>Password</b></td>

<td><input name="pwd" type="password"></td>


</tr>

<tr>

<td colspan="2" align="center">

<input type="submit" name="submit" value="Login"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="reset" value="Clear">

</td>

</tr>

</table>

</form>

</body>

</html>

[Link]

<!DOCTYPE html>

<html>

<head>

<title>User Authentication</title>

</head>

<body>

<?php

if ($_POST["uid"]==$_COOKIE["uid1"] && $_POST["pwd"]==$_COOKIE["pwd1"]) {

echo "Welcome ".$_POST["uid"];

else if ($_POST["uid"]==$_COOKIE["uid2"] && $_POST["pwd"]==$_COOKIE["pwd2"]) {

echo "Welcome ".$_POST["uid"];

}
else if ($_POST["uid"]==$_COOKIE["uid3"] && $_POST["pwd"]==$_COOKIE["pwd3"]) {

echo "Welcome ".$_POST["uid"];

else if ($_POST["uid"]==$_COOKIE["uid4"] && $_POST["pwd"]==$_COOKIE["pwd4"]) {

echo "Welcome ".$_POST["uid"];

else{

echo "You are not an authenticated user.";

?>

</body>

</html>

Explanation of Running and Expected Outputs:

● Login Form ([Link]):


o The form takes a username and password as input and submits them to the
[Link] using the POST method.
o Cookie Creation: The servlet creates a cookie for each of the four users (user1,
user2, user3, and user4) with their corresponding passwords (pwd1, pwd2, pwd3,
pwd4).
o User Authentication: After creating the cookies, it checks if the entered
username and password match the cookie values.
o Success or Failure Response: If authentication is successful, it welcomes the
user. Otherwise, it shows an "Invalid username or password" message.

Testing Scenarios:

1. Successful Login:
○ Input: Username = user1, Password = pwd1
○ Output: Welcome message for user1.
2. Failed Login:
○ Input: Username = user1, Password = wrongpwd
○ Output: "Invalid username or password!" message.
Input: pair of user id and password

Figure: - 9.1: Input Screenshot for Developing Cookies and Adding Cookies
Figure: - 9.2: Input Screenshot for Developing Cookies and Adding Cookies

Output: Results for success and failure displayed on webpage


Figure: - 9.3: Output Screenshot for Developing Cookies and Adding Cookies

Figure: - 9.4: Output Screenshot for Developing Cookies and Adding Cookies
Experiment No: 10

Objective: 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.

Apparatus/Tools Used:
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory: Based on JSP/Servlet

To create a web application using Java Servlet and JSP that allows users to register and display
their details stored in a database, we will follow these steps:

● Create a Database Table: Create a table to store user details.


● Create Registration Form: Design a JSP page for user registration.
● Create Servlet for Registration: Implement a servlet to handle form submissions and
insert user data into the database.
● Create JSP for Displaying User Data: Implement a JSP page that retrieves and displays
all registered users from the database.
Method / Procedure:

Step 1: Create Database and Table using MySQL

-- Create a new database


CREATE DATABASE userdb;

-- Use the created database


USE userdb;

-- Create a table to store user information


CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
phone_number VARCHAR(15) NOT NULL
);

Step 2: Create Registration Form ([Link])

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-


8"%>
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h2>Register User</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="Register">


</form>
</body>
</html>

Step 3: Create Servlet for Registration ([Link])

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

// JDBC URL, username, and password for MySQL database


private static final String DB_URL = "jdbc:mysql://localhost:3306/userdb"; // Replace with
your DB URL
private static final String DB_USER = "root"; // Replace with your DB username
private static final String DB_PASSWORD = "yourpassword"; // Replace with your DB
password

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Retrieve user details from the registration form


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

// Connect to the database and insert user details


try (Connection connection = [Link](DB_URL, DB_USER,
DB_PASSWORD)) {
String sql = "INSERT INTO users (name, password, email, phone_number) VALUES (?,
?, ?, ?)";
try (PreparedStatement statement = [Link](sql)) {
[Link](1, name);
[Link](2, password);
[Link](3, email);
[Link](4, phone);

int rowsInserted = [Link]();


if (rowsInserted > 0) {
[Link]("[Link]"); // Redirect to user list page after registration
}
}
} catch (Exception e) {
[Link]();
[Link](HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error
registering user.");
}
}
}

Explanation of Running and Expected Outputs:

1. Set up MySQL: Ensure your MySQL server is running and the userdb database and
users table are created.
2. Deploy the Project: Deploy the web application to a Java EE server like Apache
Tomcat.
3. Access the Registration Page: Navigate to
[Link]
4. Register a User: Fill in the registration form and submit it.

Input: Required data to be filled in form


Figure: - 10.1: For retrieving data from Table using JSP/Servlets
Output: Display of response of data entry success or failure to be displayed on webpage

Figure: - 10.2: For retrieving data from Table using JSP/Servlets

Figure: - 10.3: For retrieving data from Table using JSP/Servlets


Experiment No: 11

Objective: 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’s
name and password from the database.

Apparatus/Tools Used:
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory: Based on HTML, JSP and Servlet

To create a JSP application that allows users to register and log in, we need to implement the
following components:

1. Database Setup: Create a table to store user details.


2. Registration Form (JSP): Design a JSP page for user registration.
3. Servlet for Registration: Implement a servlet to handle registration and insert user data
into the database.
4. Login Form (JSP): Design a JSP page for user login.
5. Servlet for Authentication: Implement a servlet to authenticate users upon login.
6. User Feedback: Provide feedback on successful registration or authentication.

Method / Procedure:

Step 1: Create Database and Table using MySQL

CREATE DATABASE userdb;

USE userdb;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(100) NOT NULL
);

Step 2: Create Registration Form ([Link])


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h2>Register User</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>

<input type="submit" value="Register">


</form>
<p><a href="[Link]">Already have an account? Login here.</a></p>
</body>
</html>

Step 3: Create Servlet for Registration ([Link])

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static final String DB_URL = "jdbc:mysql://localhost:3306/userdb"; // Update


according to your setup
private static final String DB_USER = "root"; // Update according to your setup
private static final String DB_PASSWORD = "yourpassword"; // Update according to your
setup

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = [Link]("username");
String password = [Link]("password");

try (Connection connection = [Link](DB_URL, DB_USER,


DB_PASSWORD)) {
String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
try (PreparedStatement statement = [Link](sql)) {
[Link](1, username);
[Link](2, password);

int rowsInserted = [Link]();


if (rowsInserted > 0) {
[Link]("[Link]"); // Redirect to login page after registration
}
}
} catch (Exception e) {
[Link]();
[Link](HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error
registering user.");
}
}
}

Step 4: Create Login Form ([Link])

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-


8"%>
<!DOCTYPE html>
<html>
<head>
<title>User Login</title>
</head>
<body>
<h2>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>
<p><a href="[Link]">Don't have an account? Register here.</a></p>
</body>
</html>

Step 5: Create Servlet for Authentication ([Link])

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static final String DB_URL = "jdbc:mysql://localhost:3306/userdb"; // Update


according to your setup
private static final String DB_USER = "root"; // Update according to your setup
private static final String DB_PASSWORD = "yourpassword"; // Update according to your
setup

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = [Link]("username");
String password = [Link]("password");
try (Connection connection = [Link](DB_URL, DB_USER,
DB_PASSWORD)) {
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
try (PreparedStatement statement = [Link](sql)) {
[Link](1, username);
[Link](2, password);

ResultSet resultSet = [Link]();


if ([Link]()) {
// User authenticated successfully
[Link]("[Link]"); // Redirect to welcome page
} else {
// Authentication failed
[Link]("[Link]?error=Invalid username or password");
}
}
} catch (Exception e) {
[Link]();
[Link](HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error
during login.");
}
}
}

Step 6: Create a Welcome Page ([Link])

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-


8"%>
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>Welcome!</h2>
<p>You have successfully logged in.</p>
<p><a href="[Link]">Logout</a></p>
</body>
</html>
Input: Required data to be filled in form

Figure: - 11.1: Input Screenshot for writing JSP for authentication Login Form.
Figure: - 11.2: Input Screenshot for writing JSP for authentication Login Form.

Output: Deploying and Testing the Application

Figure: - 11.3: Output Screenshot for writing JSP for authentication Login Form.
Figure: - 11.4: Output Screenshot for writing JSP for authentication Login Form.
Experiment No: 12

Objective: Design and implement a simple shopping cart example with session tracking API.

Apparatus/Tools Used:
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory: Based on HTML & JSP and Servlet


● Java Development Kit (JDK): Make sure you have JDK installed.
● Apache Tomcat: A servlet container to run your JSP and servlets.
● IDE: An Integrated Development Environment like Eclipse or IntelliJ IDEA.

Method / Procedure:

src
└── [Link]
├── controller
├── model
└── view

Step 1: Create HTML Page ([Link])

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopping Cart</title>
</head>
<body>
<h1>Welcome to Our Shopping Cart</h1>
<h2>Products</h2>
<div>
<h3>Product 1</h3>
<p>Price: $10</p>
<form action="AddToCartServlet" method="POST">
<input type="hidden" name="productId" value="1">
<input type="hidden" name="productName" value="Product 1">
<input type="hidden" name="productPrice" value="10">
<input type="submit" value="Add to Cart">
</form>
</div>
<div>
<h3>Product 2</h3>
<p>Price: $15</p>
<form action="AddToCartServlet" method="POST">
<input type="hidden" name="productId" value="2">
<input type="hidden" name="productName" value="Product 2">
<input type="hidden" name="productPrice" value="15">
<input type="submit" value="Add to Cart">
</form>
</div>
<div>
<h3>Product 3</h3>
<p>Price: $20</p>
<form action="AddToCartServlet" method="POST">
<input type="hidden" name="productId" value="3">
<input type="hidden" name="productName" value="Product 3">
<input type="hidden" name="productPrice" value="20">
<input type="submit" value="Add to Cart">
</form>
</div>
<h2><a href="[Link]">View Cart</a></h2>
</body>
</html>

Step 2: Create Servlet for Adding to Cart ([Link])

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/AddToCartServlet")
public class AddToCartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
String productId = [Link]("productId");
String productName = [Link]("productName");
String productPrice = [Link]("productPrice");

// Create a cart item


CartItem item = new CartItem(productId, productName,
[Link](productPrice));

// Get the current session


HttpSession session = [Link]();
List<CartItem> cart = (List<CartItem>) [Link]("cart");

// If the cart does not exist, create a new one


if (cart == null) {
cart = new ArrayList<>();
}

// Add the new item to the cart


[Link](item);
[Link]("cart", cart);

// Redirect to the products page


[Link]("[Link]");
}
}

Step 3: Create Cart Item Class ([Link])

public class CartItem {


private String productId;
private String productName;
private double productPrice;

public CartItem(String productId, String productName, double productPrice) {


[Link] = productId;
[Link] = productName;
[Link] = productPrice;
}

public String getProductId() {


return productId;
}

public String getProductName() {


return productName;
}

public double getProductPrice() {


return productPrice;
}
}

Step 4: Create Cart JSP Page ([Link])

<%@ page import="[Link]" %>


<%@ page import="[Link]" %>
<%@ page import="[Link]" %> <!-- Change to your package -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopping Cart</title>
</head>
<body>
<h1>Your Shopping Cart</h1>
<table border="1">
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Price</th>
</tr>
<%
List<CartItem> cart = (List<CartItem>) [Link]("cart");
if (cart != null && ![Link]()) {
double total = 0.0;
for (CartItem item : cart) {
%>
<tr>
<td><%= [Link]() %></td>
<td><%= [Link]() %></td>
<td><%= [Link]() %></td>
</tr>
<%
total += [Link]();
}
%>
<tr>
<td colspan="2"><strong>Total:</strong></td>
<td><strong><%= total %></strong></td>
</tr>
<%
} else {
%>
<tr>
<td colspan="3">Your cart is empty.</td>
</tr>
<%
}
%>
</table>
<h2><a href="[Link]">Continue Shopping</a></h2>
</body>
</html>

Step 5: Create Servlet for Removing from Cart ([Link])

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/RemoveFromCartServlet")
public class RemoveFromCartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
String productId = [Link]("productId");

// Get the current session


HttpSession session = [Link]();
List<CartItem> cart = (List<CartItem>) [Link]("cart");

// If the cart exists, remove the item


if (cart != null) {
[Link](item -> [Link]().equals(productId));
[Link]("cart", cart);
}

// Redirect to the cart page


[Link]("[Link]");
}
}

Step 6: Configure [Link]

<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
version="3.1">

<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>

<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>

Input: -

Figure: - 12.1: Input Screenshot for Cart Page of Website that Tracking API
Figure: - 12.2: Input Screenshot for Cart Page of Website that Tracking API
Output: Webpage Display of Webpage

Figure: - 12.3: Output Screenshot for Cart Page of Website that Tracking API

Output: Running the Application

1. Deploy the project to Apache Tomcat.


2. Access the application at [Link]
3. Add products to the cart and view the shopping cart.
Experiment No: 13

Objective: A web application that lists all cookies stored in the browser on clicking “List
Cookies” button. Add cookies if necessary.

Apparatus/Tools Used :
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory: Based on HTML, JSP and Servlet

● HTML Structure:
o A button to list the cookies stored in the browser.
o A form to allow users to add new cookies, which includes input fields for the
cookie name and value.
● CSS: Basic styling is applied for better aesthetics.
● JavaScript:
o listCookies(): This function splits the cookie string into individual cookies, then
displays them in an unordered list. If no cookies are found, it displays a message.
o addCookie(event): This function captures the name and value entered by the
user, sets a cookie with a 7-day expiration time, and prevents the default form
submission behavior.

Method / Procedure:

Step 1: Create the HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Management</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
width: 400px;
background-color: #f9f9f9;
}
h2 {
text-align: center;
}
#cookieList {
margin-top: 20px;
}
</style>
</head>
<body>
<h2>Cookie Management</h2>

<button onclick="listCookies()">List Cookies</button>

<div id="cookieList"></div>

<h3>Add Cookie</h3>
<form onsubmit="addCookie(event)">
<label for="cookieName">Cookie Name:</label>
<input type="text" id="cookieName" required>
<br><br>
<label for="cookieValue">Cookie Value:</label>
<input type="text" id="cookieValue" required>
<br><br>
<button type="submit">Add Cookie</button>
</form>

<script>
// Function to list cookies
function listCookies() {
const cookies = [Link]('; ');
const cookieListDiv = [Link]('cookieList');

// Clear previous cookie list


[Link] = '';
// Check if there are cookies
if (cookies[0] === '') {
[Link] = '<p>No cookies found.</p>';
} else {
// Create a list of cookies
const ul = [Link]('ul');
[Link](cookie => {
const li = [Link]('li');
[Link] = cookie;
[Link](li);
});
[Link](ul);
}
}

// Function to add a cookie


function addCookie(event) {
[Link](); // Prevent form submission
const name = [Link]('cookieName').value;
const value = [Link]('cookieValue').value;
const expires = new Date();
[Link]([Link]() + (7 * 24 * 60 * 60 * 1000)); // Set expiration to 7
days
const expiresString = `expires=${[Link]()};`;

// Add cookie
[Link] = `${name}=${value}; ${expiresString} path=/`;

// Clear input fields


[Link]('cookieName').value = '';
[Link]('cookieValue').value = '';
alert('Cookie added!');
}
</script>
</body>
</html>

Input: -
Figure: - 13.1: Input Screenshot for Creating Cookies and List of Cookies.
Output: -
Figure: - 13.2: Output Screenshot for Creating Cookies and List of Cookies.

Figure: - 13.3: Output Screenshot for Creating Cookies and List of Cookies.
Testing the Application

1. Create a File: Save the above code in an HTML file (e.g., [Link]).
2. Open in Browser: Open the file in any modern web browser.
3. Add Cookies: Use the form to add cookies by entering the name and value.
4. List Cookies: Click the "List Cookies" button to see the stored cookies.
Experiment No: 14

Objective: Write a program in java to print the table of the given number using AJAX.

Apparatus/Tools Used:
Hardware Requirement: - Intel Core i5 8GB RAM, 256 GB SSD, Integrated Graphics Card,
1920 X 1080 Display.

Software Requirement: - VS Code / Notepad++, Apache NetBeans-26.0, Eclipse Version-4.37,


MySQL Community Server 9.3.0, MongoDB, Apache Tomcat 10.

Theory:
● User Input:
● The user enters a number in a text box on an HTML page.
● On clicking the "Generate Table" button, a JavaScript function is triggered.
● AJAX Call:
● The JavaScript function creates an XMLHttpRequest and sends a GET request to the server
(Servlet) with the number as a parameter.

Method / Procedure:

HTML + JavaScript ([Link]):

<!DOCTYPE html>
<html>
<head>
<title>AJAX Table</title>
<script>
function getTable() {
var num =
[Link]("numbe
r").value; var xhr = new
XMLHttpRequest();
[Link] =
function() {
if([Link] == 4 && [Link] == 200) {
[Link]("result").innerHTML =
[Link];
}

};

[Link]("GET",
"TableServlet?num=" + num, true);
[Link]();
}

</script>
</head>
<body>

Enter number: <input type="text" id="number">


<button onclick="getTable()">Get Table</button>
<div id="result"></div>
</body>
</html>

Servlet ([Link]):
import [Link].*;
import [Link].*;
import [Link].*;
public class TableServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException { int num =
[Link]([Link]("num"));
[Link]
Type("text/html");
PrintWriter out =
[Link](
);
[Link]("<h3>Multiplication
Table of " + num + "</h3>");
[Link]("<ul>");
for(int i=1; i<=10; i++) {
[Link]("<li>" + num + " x " + i + " = " + (num*i) + "</li>");
}

[Link]("</ul>");
}

Input: -

Figure: - 14.1: Input Screenshot for Displaying Table of any Number Using AJAX.
Output: -

Figure: - 14.2: Output Screenshot for Displaying Table of any Number Using AJAX.

You might also like