0% found this document useful (0 votes)
18 views30 pages

Untitled Document

The document outlines five experiments involving HTML, CSS, and JavaScript for creating web pages and forms. Experiment 1 focuses on designing an institute website with departmental information, while Experiment 2 involves creating an entry form for student, employee, and faculty details. Subsequent experiments include developing a responsive tutorial blog, implementing form validation using JavaScript, and creating an XML document with a DTD and stylesheet.
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)
18 views30 pages

Untitled Document

The document outlines five experiments involving HTML, CSS, and JavaScript for creating web pages and forms. Experiment 1 focuses on designing an institute website with departmental information, while Experiment 2 involves creating an entry form for student, employee, and faculty details. Subsequent experiments include developing a responsive tutorial blog, implementing form validation using JavaScript, and creating an XML document with a DTD and stylesheet.
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
You are on page 1/ 30

EXPERIMENT 1

Objective: Write HTML program for designing your institute website. Display departmental
information of your institute on the website.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0"> <title>PSIT</title>
</head>
<body>
<header>
<h1>PSIT</h1>
<p>Welcome to the official website of PSIT</p>
</header>
<nav>
<a href="#home">Home</a>
<a href="#departments">Departments</a>
<a href="#contact">Contact</a>
</nav>
<div class="container">
<section id="departments">
<div class="department">
<h2>Department of Computer Science (CS)</h2>
<p>The Department of Computer Science at PSIT focuses on developing cutting-
edge technologies and providing students with the skills to excel in the ever-evolving tech
industry.</p>
<ul>
<li>Bachelor of Technology in Computer Science</li>
<li>Masters in Computer Science</li>
<li>Research Opportunities</li>
</ul></div>
8 1<div class="department">
<h2>Department of Information Technology (IT)</h2>
<p>The Department of Information Technology at PSIT provides students with a
comprehensive understanding of IT systems, programming, and emerging technologies.</p>
<ul>
<li>Bachelor of Technology in Information Technology</li>
<li>Masters in Information Technology</li>
<li>Innovative IT Solutions and Projects</li>
</ul>
</div>
<div class="department">
<h2>Department of Electronics and Communication Engineering (ECE)</h2>
<p>The ECE Department at PSIT offers students knowledge in designing and
developing advanced electronic systems and communication technologies.</p>
<ul>
<li>Bachelor of Technology in Electronics and Communication Engineering</li>
<li>Masters in Electronics and Communication Engineering</li>
<li>Electronics Research and Development</li>
</ul>
</div>
</section>
</div>
<footer>
<p>&copy; 2024 PSIT. All Rights Reserved.</p>
<center>Shiromani Upadhyay</center>
</footer>

1
EXPERIMENT 2
Objective: Write HTML program to design an entry form for student details/employee information/faculty details.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Entry Form for Student, Employee, and Faculty Details</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f9;
}
header {
background-color: #0044cc;
color: white;
padding: 20px;
text-align: center;
}
.container {
width: 90%;
max-width: 500px;
margin: 20px auto;
padding: 20px;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
h2 {
color: #0044cc;
margin-bottom: 20px;
}
label {
display: block;
margin-top: 10px;
font-weight: bold;
}
input, select, textarea {
width: 100%;
padding: 10px;
margin-top: 5px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 14px;
}
.form-group {
margin-bottom: 15px;
}
button {
background-color: #0044cc;
color: white;
padding: 10px;
border: none;
border-radius: 5px;
cursor: pointer;

2
font-size: 16px;
width: 100%;
}
button:hover {
background-color: #0033aa;
}
.roleDetails {
display: none;
}
input, select, textarea {
width: 100%;
padding: 12px;
margin-top: 5px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
box-sizing: border-box;
}
</style>
</head>
<body>
<header>
<h1>Details Entry Form</h1>
<p>Enter your details below.</p>
</header>
<div class="container">
<h2>Personal Information (Shiromani Upadhyay)</h2>
<form action="#" method="POST">
<!-- Name and Email -->
<div class="form-group">
<label for="name">Full Name</label>
<input type="text" id="name" name="name" required placeholder="Enter Full
Name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" required placeholder="Enter Email
Address">
</div>
<!-- Role Selection -->
<div class="form-group">
<label for="role">Role</label>
<select id="role" name="role" required>
<option value="student">Student</option>
<option value="employee">Employee</option>
<option value="faculty">Faculty</option>
</select>
</div>
<!-- Department Selection -->
<div class="form-group">
<label for="department">Department</label>
<select id="department" name="department">
<option value="cs">Computer Science</option>
<option value="it">Information Technology</option>
<option value="ece">Electronics and Communication Engineering</option>
</select>
</div>
<!-- Additional Role-specific Details -->

3
<div id="studentDetails" class="roleDetails">
<div class="form-group">
<label for="studentId">Student ID</label>
<input type="text" id="studentId" name="studentId" placeholder="Enter Student
ID">
</div>
</div>
<div id="employeeDetails" class="roleDetails">
<div class="form-group">
<label for="employeeId">Employee ID</label>
<input type="text" id="employeeId" name="employeeId" placeholder="Enter
Employee
ID">
</div>
<div class="form-group">
<label for="position">Position</label>
<input type="text" id="position" name="position" placeholder="Enter Position">
</div>
</div>
<div id="facultyDetails" class="roleDetails">
<div class="form-group">
<label for="facultyId">Faculty ID</label>
<input type="text" id="facultyId" name="facultyId" placeholder="Enter Faculty
ID">
</div>
<div class="form-group">
<label for="specialization">Specialization</label>
<input type="text" id="specialization" name="specialization" placeholder="Enter
Specialization">
</div>
</div>
<!-- Submit Button -->
<button type="submit">Submit</button>
</form>
</div>
<script>
document.getElementById("role").addEventListener("change", function() {
var role = this.value;
document.querySelectorAll(".roleDetails").forEach(function(element) {
element.style.display = "none";
});
if (role === "student") {
document.getElementById("studentDetails").style.display = "block";
} else if (role === "employee") {
document.getElementById("employeeDetails").style.display = "block";
} else if (role === "faculty") {
document.getElementById("facultyDetails").style.display = "block";
}
});
// Trigger the event to show the relevant form sections based on the default selection
document.getElementById("role").dispatchEvent(new Event('change'));
</script>
</body>
</html>

4
EXPERIMENT 3
Objective: Develop a responsive website using CSS and HTML. Website may be for
tutorial/blogs/commercial website.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tutorial Blog</title>
<style>
/* General Styles */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f8f8f8;
}
header {
background-color: #333;
color: white;
text-align: center;
padding: 20px 0;
}
nav {
display: flex;
justify-content: center;
background-color: #444;
}
nav a { color: white;
padding: 14px 20px;
text-decoration: none;
text-align: center;
}
nav a:hover {
background-color: #ddd;
color: black;
}
/* Main Content Styles */
.container {
width: 90%;
max-width: 1200px;
margin: 20px auto;
}
.blog-post {
background-color: white;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.blog-post h2 {
color: #333;
}
.blog-post p {
color: #666;
}
.blog-post img {
width: 100%;
height: auto;

5
border-radius: 5px;
}
/* Sidebar Styles */
.sidebar {
background-color: #f4f4f4;
padding: 20px;
margin-top: 20px;
border-radius: 5px;
}
.sidebar h3 {
margin-top: 0;
color: #333;
}
/* Footer Styles */
footer {
background-color: #333;
color: white;
text-align: center;
padding: 10px;
position: relative;
bottom: 0;
width: 100%;
}
/* Form Styles */
form {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
margin-top: 20px;
}
label {
display: block;
margin: 10px 0 5px;
font-weight: bold;
}
input, textarea {
width: 100%;
padding: 12px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
}
button {
width: 100%;
padding: 12px;
background-color: #333;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
}
button:hover {
background-color: #555;
}
/* Responsive Design */
@media (max-width: 768px) {

6
.container {
width: 95%;
}
nav {
flex-direction: column;
}
.blog-post {
padding: 15px;
}
.sidebar {
margin-top: 10px;
padding: 15px;
}
}
@media (max-width: 480px) {
header h1 {
font-size: 24px;
}
nav a {
padding: 12px 16px;
}
}
input, textarea {
width: 100%;
padding: 12px;
margin-top: 5px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
box-sizing: border-box;
}
</style>
</head>
<body>
<!-- Header -->
<header>
<h1>Tutorial Blog</h1>
<p>Your go-to resource for tutorials and tech blogs</p>
</header>
<!-- Navigation -->
<nav>
<a href="#home">Home</a>
<a href="#tutorials">Tutorials</a>
<a href="#blogs">Blogs</a>
<a href="#contact">Contact</a>
</nav>
<!-- Main Content -->
<div class="container">
<div class="main-content">
<div class="blog-post">
<h2>How to Build a Simple Web Page(Shiromani Upadhyayi)</h2>
<p><strong>Posted on:</strong> November 2024</p>
<img src="https://via.placeholder.com/1200x600" alt="Web Design Tutorial">
<p>In this tutorial, we will walk you through the steps of creating a simple web page
using
HTML and CSS...</p>
<a href="#">Read More</a>
</div>

7
<div class="blog-post">
<h2>Understanding CSS Flexbox</h2>
<p><strong>Posted on:</strong> October 2024</p>
<img src="https://via.placeholder.com/1200x600" alt="CSS Flexbox">
<p>CSS Flexbox is a powerful layout tool that helps developers design responsive
web pages
with ease...</p>
<a href="#">Read More</a>
</div>
</div>
<!-- Sidebar -->
<div class="sidebar">
<h3>Recent Posts</h3>
<ul>
<li><a href="#">10 Tips for Responsive Web Design</a></li>
<li><a href="#">JavaScript Basics for Beginners</a></li>
<li><a href="#">Understanding HTML5 Elements</a></li>
</ul>
</div>
<!-- Form Section -->
<form>
<h3>Contact Us</h3>
<label for="name">Name</label>
<input type="text" id="name" name="name" placeholder="Enter your name"
required>
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="Enter your email"
required>
<label for="message">Message</label>
24<textarea id="message" name="message" placeholder="Write your message here..."
rows="5"
required></textarea>
<button type="submit">Submit</button>
</form>
</div>
<!-- Footer -->
<footer>
<p>&copy; 2024 Tutorial Blog. All Rights Reserved.</p>
</footer>
</body>
</html>

8
EXPERIMENT 4
Objective: Write programs using HTML and Java Script for validation of input data.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f8f8f8;
margin: 0;
padding: 20px;
}
form {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
max-width: 400px;
margin: auto;
}
label {
font-weight: bold;
display: block;
margin-bottom: 5px;
}
input, textarea {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
background-color: #333;
color: white;
padding: 10px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
width: 100%;
}
button:hover {
background-color: #555;
}
.error {
color: red;
font-size: 14px;
margin-bottom: 10px;
}
.success {
color: green;
font-size: 14px;
}
input, select, textarea {
width: 100%;

9
padding: 12px;
margin-top: 5px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
box-sizing: border-box;
}
</style>
</head>
<body>
<form id="contactForm">
<h2>Contact Us(Shiromani Upadhyay)</h2>
<div id="errorMessages" class="error"></div>
<label for="name">Name</label>
<input type="text" id="name" placeholder="Enter your name">
<label for="email">Email</label>
<input type="email" id="email" placeholder="Enter your email">
<label for="message">Message</label>
<textarea id="message" placeholder="Write your message here..."
rows="5"></textarea>
<button type="submit">Submit</button>
</form>
<script>
// Select form and error message div
const form = document.getElementById('contactForm');
const errorMessages = document.getElementById('errorMessages');
form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent form submission
let errors = [];
// Get values from inputs
const name = document.getElementById('name').value.trim();
const email = document.getElementById('email').value.trim();
const message = document.getElementById('message').value.trim();
// Validate name
if (name === '') {
errors.push('Name is required.');
}
// Validate email format
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (email === '') {
errors.push('Email is required.');
} else if (!emailPattern.test(email)) {
errors.push('Enter a valid email address.');
}
// Validate message length
if (message === '') {
errors.push('Message is required.');
} else if (message.length < 10) {
errors.push('Message must be at least 10 characters long.');
}
// Display errors or success message
if (errors.length > 0) {
errorMessages.innerHTML = errors.join('<br>');
} else {
errorMessages.innerHTML = '<span class="success">Form submitted
successfully!</span>';
form.reset(); // Clear form inputs
}

10
});
</script>
</body> </html>

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

style sheet in CSS/ XSL & display the document in internet explorer.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE employees
[ <!ELEMENT employees (employee+)>
<!ELEMENT employee (id, name, position, department, salary)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT position (#PCDATA)>
<!ELEMENT department (#PCDATA)>
<!ELEMENT salary (#PCDATA)>
]>
<employees>
<employee>
<id>101</id>
<name>John Doe</name>
<position>Software Engineer</position>
<department>IT</department>
<salary>75000</salary>
</employee>
<employee>
<id>102</id>
<name>Jane Smith</name>
<position>Project Manager</position>
<department>Operations</department>
<salary>85000</salary>
</employee>
<employee>
<id>103</id>
<name>Robert Brown</name>
Objective: Write a program in XML for creation of DTD, which specifies set of rules. Create a
<position>UI/UX Designer</position>
<department>Design</department>
<salary>72000</salary> </employee>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<title>Employee Directory</title>
<style>
body { font-family: Arial, sans-serif; }
h1 { color: #5B84B1FF; text-align: center; }
table { width: 60%; margin: auto; border-collapse: collapse; }
th, td { padding: 10px; border: 1px solid #ddd; text-align: left; }
th { background-color: #f4f4f4; }
</style>
</head>
<body>
<h1>Employee Directory (Anjali Trivedi)</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>

12
<th>Department</th>
<th>Salary</th>
</tr>
<xsl:for-each select="employees/employee">
<tr>
<td><xsl:value-of select="id"/></td>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="position"/></td>
<td><xsl:value-of select="department"/></td>
<td><xsl:value-of select="salary"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
</employees>

13
EXPERIMENT 6
Objective: Build a command-line utility using Node.js that performs a specific task, such as
converting text to uppercase, calculating the factorial of a number, or generating random
passwords.
import java.io.Serializable;
import java.util.Scanner;
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) {
this.empID = empID;
this.name = name;
this.salary = salary;
this.designation = designation;
this.department = department;
}
// Getter and Setter for EmpID
public String getEmpID() {
return empID;
}
public void setEmpID(String empID) {
this.empID = empID;
}
37// Getter and Setter for Name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Getter and Setter for Salary
public double getSalary() {
return salary;
}
public void setSalary(double salary) {

14
this.salary = salary;
}
// Getter and Setter for Designation
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
// Getter and Setter for Department
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
@Override
public String toString() {
return "Employee{" +
"empID='" + empID + '\'' +
", name='" + name + '\'' +
", salary=" + salary +
", designation='" + designation + '\'' +
", department='" + department + '\'' +
'}';
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking input for the first Employee object
System.out.println("Enter details for Employee 1:");
System.out.print("EmpID: ");
String empID1 = scanner.nextLine();
System.out.print("Name: ");
String name1 = scanner.nextLine();
System.out.print("Salary: ");
double salary1 = scanner.nextDouble();
scanner.nextLine(); // consume the newline character
System.out.print("Designation: ");
String designation1 = scanner.nextLine();
System.out.print("Department: ");
String department1 = scanner.nextLine();
// Creating Employee object using the parameterized constructor
Employee emp1 = new Employee(empID1, name1, salary1, designation1, department1);
// Taking input for the second Employee object
System.out.println("\nEnter details for Employee 2:");
System.out.print("EmpID: ");
String empID2 = scanner.nextLine();
39System.out.print("Name: ");
String name2 = scanner.nextLine();
System.out.print("Salary: ");
double salary2 = scanner.nextDouble();
scanner.nextLine(); // consume the newline character
System.out.print("Designation: ");
String designation2 = scanner.nextLine();
System.out.print("Department: ");
String department2 = scanner.nextLine();
// Creating Employee object using the default constructor and setters
Employee emp2 = new Employee();

15
emp2.setEmpID(empID2);
emp2.setName(name2);
emp2.setSalary(salary2);
emp2.setDesignation(designation2);
emp2.setDepartment(department2);
// Displaying the Employee objects using the toString() method
System.out.println("\nEmployee 1: " + emp1);
System.out.println("Employee 2: " + emp2);
// Extra line for displaying a static string
System.out.println("Shiromani Upadhyayi");
scanner.close();
}
}

16
EXPERIMENT 7
Objective: Develop a script that uses MongoDB's aggregation framework to perform
operations like grouping, filtering, and sorting. For instance, aggregate user data to find the
average age of users in different cities.
const readline = require(“readline”);
// Helper function to calculate factorial
function factorial(num) {
if (num < 0) return "Factorial not defined for negative numbers.";
return num === 0 ? 1 : num * factorial(num - 1);
}
// Helper function to generate a random password
function generatePassword(length) {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()";
let password = "";
for (let i = 0; i < length; i++) {
password += chars.charAt(Math.floor(Math.random() * chars.length));
}
return password;
}
// User input interface
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// Display menu
console.log("Choose an option:");
console.log("1. Convert text to UPPERCASE");
console.log("2. Calculate the factorial of a number");
console.log("3. Generate a random password");
rl.question("Enter your choice (1/2/3): ", (choice) => {
if (!["1", "2", "3"].includes(choice)) {
console.log("Invalid choice. Please run the program again.");
rl.close();
return;
}
if (choice === "1") {
rl.question("Enter the text: ", (text) => {
console.log("Uppercase Text: ", text.toUpperCase());
rl.close();
});
} else if (choice === "2") {
rl.question("Enter a number: ", (number) => {
const num = parseInt(number, 10);
if (isNaN(num)) {
console.log("Please enter a valid number.");
} else {

17
console.log(`Factorial of ${num}:`, factorial(num));
}
rl.close();
});
} else if (choice === "3") {
rl.question("Enter password length: ", (length) => {
const len = parseInt(length, 10);
if (isNaN(len) || len <= 0) {
console.log("Please enter a valid positive number.");
} else {
console.log("Generated Password: ", generatePassword(len));
}
rl.close();
});
}
});

18
EXPERIMENT 8
Objective: Create a Java Bean for Employee information (EmpID, Name, Salary, Designation
and Department).
const { MongoClient } = require("mongodb");
// MongoDB connection URI and database/collection details
const uri = "mongodb://localhost:27017";
const dbName = "userDB";
const collectionName = "users";
async function aggregateUserData() {
const client = new MongoClient(uri);
try {
await client.connect();
console.log("Connected to MongoDB");
const db = client.db(dbName);
const collection = db.collection(collectionName);
// Aggregation pipeline
const pipeline = [
{
$group: {
_id: "$city", // Group by city
averageAge: { $avg: "$age" }, // Calculating average age
totalUsers: { $sum: 1 }, // Counting users in each city
},
},
{
$sort: { averageAge: -1 }, // Sorting by average age in descending order
},
];
const result = await collection.aggregate(pipeline).toArray();
console.log("Aggregation Result:");
console.log(result);
} catch (error) {
console.error("Error:", error);
} finally {
await client.close();
console.log("MongoDB connection closed.");
}
}
console.log("Shiromani Upadhyay");
aggregateUserData();

19
EXPERIMENT 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 id’s and passwords to this Cookie. 2. Read the user id and passwords
entered in the Login form and authenticate with the values available in the cookies.
Register.html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<style>
.container {
width: 300px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="text"], input[type="password"] {
width: 100%;
padding: 8px;
margin-bottom: 10px;
}
.submit-btn {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.submit-btn:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h2>User Login</h2>
<form action="LoginServlet" method="post">
<div class="form-group">
<label for="userId">User ID:</label>
<input type="text" id="userId" name="userId" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<input type="submit" value="Login" class="submit-btn">
</form>
</div>

20
</body>
</html>
LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Step 1: Create a single cookie with user IDs and passwords
Cookie usersCookie = new Cookie("users",
"user1:pwd1,user2:pwd2,user3:pwd3,user4:pwd4");
// Set the cookie to expire in 1 hour
usersCookie.setMaxAge(3600);
// Add the cookie to the response
response.addCookie(usersCookie);
// Step 2: Authenticate user based on login form data
String enteredUserId = request.getParameter("userId");
String enteredPassword = request.getParameter("password");
boolean isAuthenticated = false;
// Retrieve the "users" cookie
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("users")) {
// Split the cookie value into individual user-password pairs
String[] userPairs = cookie.getValue().split(",");
for (String pair : userPairs) {
String[] userAndPassword = pair.split(":");
String userId = userAndPassword[0];
String password = userAndPassword[1];
// Check if entered user ID and password match
if (userId.equals(enteredUserId) && password.equals(enteredPassword)) {
isAuthenticated = true;
break;
}
}
}
}
}
// Display authentication result
if (isAuthenticated) {
51out.println("<h2>Login Successful! Welcome, " + enteredUserId + ".</h2>");
} else {
out.println("<h2>Login Failed! Invalid User ID or Password.</h2>");
}
}
}
Register.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"

21
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>

22
EXPERIMENT 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.
Index.html (Homepage)
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>
<a href="RegisterForm.html">Register new user</a><br>
<a href="Display.jsp">Display existing users</a>
</h1>
</body>
</html>
RegisterForm.html (Registration Form)
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Register.jsp" method="post">
54<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="password"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="email" name="email"></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><input type="number" name="phone"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register"></td>
</tr>
</table>
</form>
</body>
</html>
Register.jsp (User Registration Logic)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO88591"%>
<%@ page import="java.sql.Statement" %>
<%@ page import="connection.Connect" %>

23
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name = request.getParameter("name");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
try {
Statement stmt = Connect.conn().createStatement();
String query = "insert into users1 values('" + name + "','" + password + "','" + email + "'," +
phone +
")"; stmt.executeQuery(query);
Connect.conn().close();
stmt.close();
out.println("Registration
Successful");
} catch (Exception e) {
out.println("Registration Unsuccessful!");
System.out.println(e);
} finally {
out.println("<br><a href='index.html'>Go to home page</a>");
}
%>
</body>
</html>
Display.jsp (Display Registered Users)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO88591"%>
<%@ page import="java.sql.*" %>
<%@ page import="connection.Connect" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
try {
Statement stmt = Connect.conn().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("select * from users1");
if (!rs.next()) {
out.println("No users registered!");
} else {
%>
<h1>Users are:</h1><br>
<table border="1">
<thead>
<tr>
<th>Name</th>

24
<th>Password</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<%
rs.previous();
while (rs.next()) {
String name =
rs.getString(1);
String password =
rs.getString(2); String email =
rs.getString(3); int phone =
rs.getInt(4);
%>
<tr>
<td><%= name %></td>
<td><%= password %></td>
<td><%= email %></td>
<td><%= phone %></td>
</tr>
<%
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
out.println("<br><a href='index.html'>Go to home page</a>");
}
%>
</tbody>
</table>
</body>
</html>

EXPERIMENT 11

25
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 name and password from the database.
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home</title>
</head>
<body>
<h1><a href="RegisterForm.html">Register new user</a><br>
<a href="LoginForm.html">Login</a></h1>
</body>
</html>
RegisterForm.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registration Form</title>
</head>
<body>
<form action="Register.jsp" method="post">
<table>
<tr>
<td>Name:</td>
<tr>
<td>Password:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="email" name="email"></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><input type="number" name="phone"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register"></td>
</tr>
</table>
</form>
</body>
</html>
Register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO88591"%>
<%@ page import="java.sql.Statement" %>
<%@ page import="connection.Connect" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration</title>
</head>

26
<body>
<%
String name = request.getParameter("name");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
try {
Statement stmt = Connect.conn().createStatement();
String query = "insert into users values('" + name + "','" + password + "','" + email + "'," +
phone +
")";
stmt.executeUpdate(query);
Connect.conn().close();
stmt.close();
out.println("Registration
Successful");
} catch (Exception e) {
out.println("Registration Unsuccessful!");
System.out.println(e);
} finally {
out.println("<br><a href='index.html'>Go to home page</a>");
}
%>
</body>
</html>
LoginForm.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Form</title>
</head>
<body>
<form action="Login.jsp" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
Login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO88591"%>
<%@ page import="java.sql.*" %>
<%@ page import="connection.Connect" %>
<!DOCTYPE html>
<html>

27
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
boolean authenticated = false;
try {
Statement stmt = Connect.conn().createStatement();
ResultSet rs = stmt.executeQuery("select * from users where username='" + username + "'
and password='" + password + "'");
if (rs.next()) {
authenticated = true;
out.println("Welcome " + username);
} else {
out.println("Invalid username or password");
}
Connect.conn().close();
stmt.close(); } catch
(Exception e) {
out.println("Login
Failed!");
System.out.println(e);
}
%>
</body>
</html>
Connect.java
package connection; import
java.sql.Connection; import
java.sql.DriverManager;
import
java.sql.SQLException;
public class Connect { public static Connection conn() throws
ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"your_db_user", "your_db_password");
return conn;
}
}

28
EXPERIMENT 12
Objective: Design and implement a simple shopping cart example with session tracking API.
// Import required modules
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
// Initialize the app
const app = express();
const PORT = 3000;
// Load environment variables from .env file dotenv.config();
// Middleware setup
app.use(bodyParser.json());
app.use(
session({
secret: process.env.SESSION_SECRET, // Using secret from environment variable
resave: false, saveUninitialized: true,
cookie: { maxAge: 600000 }, //10minutes
})
);
// Mock product catalog
const products = [
{ id: 1, name: 'Laptop', price: 70000 },
{ id: 2, name: 'Smartphone', price: 30000 },
{ id: 3, name: 'Headphones', price: 2000 },
];
// Initialize session cart const
initializeCart = (req) => {
if (!req.session.cart) {
req.session.cart = [];
}
};
// Get all products
app.get('/products', (req, res) => {
res.json(products);
});
// View the shopping cart
app.get('/cart', (req, res) => {
initializeCart(req);
res.json(req.session.cart);
});
// Add item to the cart
app.post('/cart', (req, res) => {
const { productId,quantity}=req.body;
if (!productId || !quantity || quantity <= 0) {
return res.status(400).json({ error: 'Invalid product ID or quantity’});
}
const product = products.find((p) => p.id === productId);
if (!product) {
return res.status(404).json({ error: 'Product not
found'});
}
initializeCart(req);
const existingItem = req.session.cart.find((item) => item.product.id !==
productId);
if (existingItem) {
existingItem.quantity += quantity;
} else {
req.session.cart.push({ product, quantity });

29
}
res.json({ message: 'Product added to cart', cart: req.session.cart });
});
// Remove item from the cart
app.delete('/cart/:productId', (req, res) => {
const productId = parseInt(req.params.productId);
initializeCart(req);
req.session.cart = req.session.cart.filter((item) => item.product.id !== productId);
res.json({ message: 'Product removed from cart', cart: req.session.cart });
});
// Clear the cart
app.delete('/cart',(req, res) => {
req.session.cart = [];
res.json({ message: 'Cart cleared' });
});
// Get cart summary (total cost)
app.get('/cart/summary', (req, res) => {
initializeCart(req);
const total = req.session.cart.reduce((sum, item) => sum + item.product.price * item.quantity, 0);
res.json({ totalItems:
req.session.cart.length,
totalAmount: total,
});
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

30

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy