0% found this document useful (0 votes)
6 views

WT LAB FIE[1]

The document outlines a series of programming experiments and tasks, including creating a website for an institute, designing entry forms, validating input data with JavaScript, and working with XML and Java Beans. Each task is accompanied by specific dates and signatures, indicating a structured approach to learning web development and programming concepts. It includes sample HTML, CSS, XML, and Java code snippets for practical implementation.
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)
6 views

WT LAB FIE[1]

The document outlines a series of programming experiments and tasks, including creating a website for an institute, designing entry forms, validating input data with JavaScript, and working with XML and Java Beans. Each task is accompanied by specific dates and signatures, indicating a structured approach to learning web development and programming concepts. It includes sample HTML, CSS, XML, and Java code snippets for practical implementation.
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/ 23

INDEX

S. NO. EXPERIMENT NAME DATE SIGN.


Write html program for designing your institute
1. website. Display departmental information of 19 SEP 2024
your institute on the website ?

Write html program to design an entry form for


2. student details/employee information/faculty 03 OCT 2024
details ?
Write programs using html and java script for 03 OCT 2024
3.
validation of input data ?
Write a program in xml for creation of DTD, which
4. specifies set of rules. Create a style sheet in CSS/ 10 OCT 2024
XSL & display the document in internet explorer?
Create a java bean for employee information
5. (empid, name, salary, designation and 17 OCT 2024
department) ?

Build a command-line utility using node.js that


performs a specific task, such as converting text 14 NOV 2024
6.
to uppercase, calculating the factorial of a
number, or generating random passwords ?

Develop a script that uses MONGODB'S


aggregation framework to perform operations
7. like grouping, filtering, and sorting. For instance, 21 NOV 2024
aggregate user data to find the average age of
users in different cities ?

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 28 NOV 2024
8.
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 ?
Write a JSP which insert the details of the 3 or 4
users who register with the web site by using
9. registration form. Authenticate the user when he 12 DEC 2024
submits the login form using the user name and
password from the database ?
Design and implement a simple shopping cart 19 DEC 2024
10.
example with session tracking API ?

2
1. 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">
<title>KCNIT Website</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f9;
}

header {
background-color: #2c3e50;
color: white;
padding: 15px 0;
text-align: center;
}

nav {
background-color: #34495e;
padding: 10px 0;
text-align: center;
}

nav a {
color: white;
text-decoration: none;
margin: 0 15px;
font-size: 18px;
}

nav a:hover {
text-decoration: underline;
}

.content {
padding: 20px;
max-width: 1000px;
margin: auto;
background: white;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.department {
margin: 20px 0;
}

.department h2 {
color: #2c3e50;
}

footer {
text-align: center;
3
padding: 10px 0;
background-color: #2c3e50;
color: white;
margin-top: 20px;
}
</style>
</head>
<body>

<header>
<h1>Welcome to XYZ Institute</h1>
</header>

<nav>
<a href="#">Home</a>
<a href="#departments">Departments</a>
<a href="#contact">Contact Us</a>
</nav>

<div class="content">
<section id="departments">
<h2>Our Departments</h2>

<div class="department">
<h3>Department of Computer Science</h3>
<p>The Computer Science department offers courses in programming, data science,
artificial intelligence, and more. Our faculty is dedicated to preparing students for careers in the
tech industry.</p>
</div>

<div class="department">
<h3>Department of Electronics</h3>
<p>The Electronics department provides hands-on experience in circuits, communication
systems, and IoT technology, helping students to innovate in modern electronic solutions.</p>
</div>

<div class="department">
<h3>Department of Mechanical Engineering</h3>
<p>Our Mechanical Engineering department focuses on thermodynamics, robotics, and
manufacturing processes, shaping engineers for diverse industries.</p>
</div>

<div class="department">
<h3>Department of Civil Engineering</h3>
<p>Students in the Civil Engineering department learn about sustainable construction,
structural design, and urban planning, contributing to modern infrastructure development.</p>
</div>
</section>
</div>

<footer>
<p>&copy; 2024 KCNIT College. All rights reserved.</p>
</footer>

</body>
</html>

4
2. 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</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f9;
}

.container {
max-width: 600px;
margin: 50px auto;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

h2 {
text-align: center;
color: #2c3e50;
}

form {
display: flex;
flex-direction: column;
}

label {
margin-top: 15px;
font-weight: bold;
}

input, select, textarea {


padding: 10px;
margin-top: 5px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
}

button {
margin-top: 20px;
padding: 10px 15px;
background-color: #2c3e50;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
5
button:hover {
background-color: #34495e;
}
</style>
</head>
<body>

<div class="container">
<h2>Entry Form</h2>
<form action="#" method="POST">
<!-- Personal Information -->
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" required>

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob" required>

<label for="email">Email Address:</label>


<input type="email" id="email" name="email" placeholder="Enter your email" required>

<label for="phone">Phone Number:</label>


<input type="tel" id="phone" name="phone" placeholder="Enter your phone number"
required>

<!-- Role Information -->


<label for="role">Role:</label>
<select id="role" name="role" required>
<option value="">Select Role</option>
<option value="student">Student</option>
<option value="employee">Employee</option>
<option value="faculty">Faculty</option>
</select>

<!-- Address -->


<label for="address">Address:</label>
<textarea id="address" name="address" rows="3" placeholder="Enter your address"
required></textarea>

<!-- Submit Button -->


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

</body>
</html>

6
3. 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>Input Validation</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
margin: 0;
padding: 0;
}

.container {
max-width: 500px;
margin: 50px auto;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

h2 {
text-align: center;
color: #2c3e50;
}

label {
font-weight: bold;
display: block;
margin-top: 15px;
}

input {
width: 100%;
padding: 10px;
margin-top: 5px;
border: 1px solid #ccc;
border-radius: 5px;
}

.error {
color: red;
font-size: 14px;
margin-top: 5px;
}

button {
margin-top: 20px;
padding: 10px;
7
width: 100%;
background-color: #2c3e50;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}

button:hover {
background-color: #34495e;
}
</style>
</head>
<body>

<div class="container">
<h2>Input Validation Form</h2>
<form id="validationForm" onsubmit="return validateForm()">
<!-- Full Name -->
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name">
<span class="error" id="nameError"></span>

<!-- Email -->


<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email">
<span class="error" id="emailError"></span>

<!-- Phone Number -->


<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" placeholder="Enter your phone
number">
<span class="error" id="phoneError"></span>

<!-- Submit Button -->


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

<script>
function validateForm() {
let isValid = true;

// Clear all previous errors


document.getElementById('nameError').innerText = "";
document.getElementById('emailError').innerText = "";
document.getElementById('phoneError').innerText = "";

// Full Name Validation


const name = document.getElementById('name').value;
if (name.trim() === "") {
document.getElementById('nameError').innerText = "Full name is required.";
isValid = false;
}
8
// Email Validation
const email = document.getElementById('email').value;
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
document.getElementById('emailError').innerText = "Invalid email format.";
isValid = false;
}

// Phone Number Validation


const phone = document.getElementById('phone').value;
const phoneRegex = /^[0-9]{10}$/;
if (!phoneRegex.test(phone)) {
document.getElementById('phoneError').innerText = "Phone number must be 10
digits.";
isValid = false;
}

return isValid;
}
</script>

</body>
</html>

9
4. 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 ?

Display in Internet Explorer

1. Save the XML file and the XSL file in the same directory.
2. Open the XML file in Internet Explorer; the browser will apply the XSL stylesheet and
render the content.

This program defines:

1. DTD: Rules for the structure of the XML document.


2. XSL: Styling and transformation rules for displaying the XML data in a user-friendly
format.

Xml Dtd Stylesheet


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE institute [
<!ELEMENT institute (department+)>
<!ELEMENT department (name, head, courses)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT head (#PCDATA)>
<!ELEMENT courses (course+)>
<!ELEMENT course (#PCDATA)>]>
<institute>
<department>
<name>Computer Science</name>
<head>Dr. Smith</head>
<courses>
<course>Artificial Intelligence</course>
<course>Data Science</course>
<course>Software Engineering</course>
</courses>
</department>
<department>
<name>Electronics</name>
<head>Dr. Johnson</head>
<courses>
<course>Embedded Systems</course>
<course>Communication Engineering</course>
</courses>
</department>
</institute>
XSL Stylesheet
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>

10
<head>
<title>Institute Information</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
color: #333;
padding: 20px;
}
h1, h2 {
color: #2c3e50;
}
.department {
margin-bottom: 20px;
}
</style>
</head>
<body>
<h1>Institute Details</h1>
<xsl:for-each select="institute/department">
<div class="department">
<h2><xsl:value-of select="name"/></h2>
<p><strong>Head:</strong> <xsl:value-of select="head"/></p>
<p><strong>Courses:</strong></p>
<ul>
<xsl:for-each select="courses/course">
<li><xsl:value-of select="."/></li>
</xsl:for-each>
</ul>
</div>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Link the Stylesheet to the XML File
<?xml-stylesheet type="text/xsl" href="style.xsl"?>

11
5. Create a Java Bean for Employee information (EmpID, Name, Salary,
Designation and Department) ?

package com.example;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private int empID;
private String name;
private double salary;
private String designation;
private String department;
// Default constructor
public Employee() {
}

// Parameterized constructor
public Employee(int empID, String name, double salary, String designation,
String department) {
this.empID = empID;
this.name = name;
this.salary = salary;
this.designation = designation;
this.department = department;
}

// Getter and Setter for empID


public int getEmpID() {
return empID;
}

public void setEmpID(int empID) {


this.empID = empID;
}

// 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) {


12
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 toString method for easy debugging


@Override
public String toString() {
return "Employee{" +
"empID=" + empID +
", name='" + name + '\'' +
", salary=" + salary +
", designation='" + designation + '\'' +
", department='" + department + '\'' +
'}';
}
}

13
6. 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 ?

Employee Java Bean

package com.example;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private int empID;
private String name;
private double salary;
private String designation;
private String department;

// Default constructor
public Employee() {
}

// Parameterized constructor
public Employee(int empID, String name, double salary, String designation, String
department) {
this.empID = empID;
this.name = name;
this.salary = salary;
this.designation = designation;
this.department = department;
}

// Getter and Setter for empID


public int getEmpID() {
return empID;
}

public void setEmpID(int empID) {


this.empID = empID;
}

// 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 toString method for easy debugging


@Override
public String toString() {
return "Employee{" +
"empID=" + empID +
", name='" + name + '\'' +
", salary=" + salary +
", designation='" + designation + '\'' +
", department='" + department + '\'' +
'}';
}
}
//Command-line Utility in Node.js
const readline = require('readline');
const crypto = require('crypto');

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

function showMenu() {
console.log("\nChoose a task:");
console.log("1. Convert text to uppercase");
console.log("2. Calculate factorial of a number");
console.log("3. Generate random password");
console.log("4. Exit");
rl.question("Enter your choice: ", handleMenu);
}

function handleMenu(choice) {
switch (choice) {
case '1':
rl.question("Enter text: ", text => {
15
console.log("Uppercase: ", text.toUpperCase());
showMenu();
});
break;

case '2':
rl.question("Enter a number: ", num => {
const n = parseInt(num, 10);
if (isNaN(n) || n < 0) {
console.log("Invalid input! Please enter a non-negative integer.");
} else {
console.log(`Factorial of ${n}: `, factorial(n));
}
showMenu();
});
break;

case '3':
rl.question("Enter password length: ", len => {
const length = parseInt(len, 10);
if (isNaN(length) || length <= 0) {
console.log("Invalid input! Please enter a positive integer.");
} else {
console.log("Generated Password: ", generatePassword(length));
}
showMenu();
});
break;

case '4':
console.log("Exiting the utility. Goodbye!");
rl.close();
break;

default:
console.log("Invalid choice. Please try again.");
showMenu();
}
}

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

function generatePassword(length) {
return crypto.randomBytes(length).toString('base64').slice(0, length);
}

// Start the utility


console.log("Welcome to the Command-line Utility!");
showMenu();

16
7. 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?
// Import MongoDB client
const { MongoClient } = require('mongodb');

// MongoDB connection URI and database/collection names


const uri = "mongodb://localhost:27017"; // Replace with your MongoDB URI if different
const dbName = "userDatabase";
const collectionName = "users";

async function runAggregation() {


const client = new MongoClient(uri);

try {
// Connect to the MongoDB server
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" }, // Calculate average age
totalUsers: { $sum: 1 } // Count total users in each city
}
},
{
$sort: { averageAge: -1 } // Sort by average age in descending order
},
{
$match: { totalUsers: { $gte: 5 } } // Filter cities with at least 5 users
}
];

// Execute the aggregation pipeline


const results = await collection.aggregate(pipeline).toArray();

// Print the results


console.log("Aggregation Results:");
results.forEach(result => {
console.log(`City: ${result._id}, Average Age: ${result.averageAge.toFixed(2)}, Total Users:
${result.totalUsers}`);
});

} catch (error) {
console.error("Error running aggregation:", error);
} finally {
// Close the connection
await client.close();
}
}

// Run the aggregation script


runAggregation();
MongoDB collection users
{ "name": "John Doe", "age": 30, "city": "New York" }

17
8. 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 ?

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

@Override
public void init() throws ServletException {
// Create cookies for user credentials
Cookie user1 = new Cookie("user1", "pwd1");
Cookie user2 = new Cookie("user2", "pwd2");
Cookie user3 = new Cookie("user3", "pwd3");
Cookie user4 = new Cookie("user4", "pwd4");

// Set cookie lifespan (e.g., 1 day)


int lifespan = 24 * 60 * 60;
user1.setMaxAge(lifespan);
user2.setMaxAge(lifespan);
user3.setMaxAge(lifespan);
user4.setMaxAge(lifespan);

// Add cookies to the response during servlet initialization


getServletContext().setAttribute("userCookies", new Cookie[]{user1,
user2, user3, user4});
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Get user ID and password from the login form
String userId = request.getParameter("userId");
String password = request.getParameter("password");

// Retrieve cookies from context (simulating cookie addition during init)


Cookie[] userCookies = (Cookie[])
getServletContext().getAttribute("userCookies");
18
boolean isAuthenticated = false;

// Authenticate user with cookies


if (userCookies != null) {
for (Cookie cookie : userCookies) {
if (cookie.getName().equals(userId) &&
cookie.getValue().equals(password)) {
isAuthenticated = true;
break;
}
}
}

// Respond to user
response.setContentType("text/html");
if (isAuthenticated) {
response.getWriter().println("<h1>Welcome, " + userId + "!</h1>");
} else {
response.getWriter().println("<h1>Invalid credentials. Please try
again.</h1>");
}
}
}
HTML

<form method="POST" action="LoginServlet">


<label for="userId">User ID:</label>
<input type="text" name="userId" id="userId" required><br>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required><br>
<button type="submit">Login</button>
</form>

19
9. 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 ?

<!-- Registration.jsp -->


<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h1>Register</h1>
<form action="RegisterUser.jsp" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>
<button type="submit">Register</button>
</form>
</body>
</html>

<!-- RegisterUser.jsp -->


<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Register User</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");

Connection conn = null;


PreparedStatement stmt = null;

try {
Class.forName("com.mysql.cj.jdbc.Driver"); // Load MySQL driver
conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/website", "root",
"password");

String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
20
int rowsInserted = stmt.executeUpdate();

if (rowsInserted > 0) {
out.println("<h1>Registration successful!</h1>");
} else {
out.println("<h1>Registration failed. Please try again.</h1>");
}
} catch (Exception e) {
e.printStackTrace(out);
} finally {
if (stmt != null) try { stmt.close(); } catch (SQLException ignore) {}
if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
}
%>
</body>
</html>

<!-- Login.jsp -->


<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h1>Login</h1>
<form action="AuthenticateUser.jsp" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>
<button type="submit">Login</button>
</form>
</body>
</html>

<!-- AuthenticateUser.jsp -->


<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Authenticate User</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");

Connection conn = null;


PreparedStatement stmt = null;
21
ResultSet rs = null;

try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/website", "root",
"password");

String sql = "SELECT * FROM users WHERE username = ? AND password


= ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
rs = stmt.executeQuery();

if (rs.next()) {
out.println("<h1>Welcome, " + username + "!</h1>");
} else {
out.println("<h1>Invalid credentials. Please try again.</h1>");
}
} catch (Exception e) {
e.printStackTrace(out);
} finally {
if (rs != null) try { rs.close(); } catch (SQLException ignore) {}
if (stmt != null) try { stmt.close(); } catch (SQLException ignore) {}
if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
}
%>
</body>
</html>
MySQL Table
CREATE DATABASE website;
USE website;

CREATE TABLE users (


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

22
10. Design and implement a simple shopping cart example with session
tracking API ?

<!-- ShoppingCart.jsp -->


<%@ page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart</title>
</head>
<body>
<h1>Welcome to the Online Store</h1>
<form action="AddToCart.jsp" method="POST">
<label for="product">Select a product:</label>
<select name="product" id="product">
<option value="Laptop">Laptop</option>
<option value="Smartphone">Smartphone</option>
<option value="Headphones">Headphones</option>
<option value="Camera">Camera</option>
</select>
<button type="submit">Add to Cart</button>
</form>

<h2>Your Cart</h2>
<form action="Checkout.jsp" method="POST">
<ul>
<%
HttpSession session = request.getSession();
List<String> cart = (List<String>) session.getAttribute("cart");
if (cart != null && !cart.isEmpty()) {
for (String item : cart) {
out.println("<li>" + item + "</li>");
}
} else {
out.println("<p>Your cart is empty.</p>");
}
%>
</ul>
<button type="submit">Proceed to Checkout</button>
</form>
</body>
</html>

<!-- AddToCart.jsp -->


<%@ page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Add to Cart</title>
</head>
23
<body>
<%
String product = request.getParameter("product");
HttpSession session = request.getSession();
List<String> cart = (List<String>) session.getAttribute("cart");

if (cart == null) {
cart = new ArrayList<>();
session.setAttribute("cart", cart);
}

if (product != null) {
cart.add(product);
}
%>
<h1>Product added to cart: <%= product %></h1>
<a href="ShoppingCart.jsp">Back to Shopping Cart</a>
</body>
</html>

<!-- Checkout.jsp -->


<%@ page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Checkout</title>
</head>
<body>
<%
HttpSession session = request.getSession();
List<String> cart = (List<String>) session.getAttribute("cart");

if (cart != null && !cart.isEmpty()) {


out.println("<h1>Thank you for your purchase!</h1>");
out.println("<h2>Items purchased:</h2>");
out.println("<ul>");
for (String item : cart) {
out.println("<li>" + item + "</li>");
}
out.println("</ul>");
session.removeAttribute("cart"); // Clear the cart after checkout
} else {
out.println("<h1>Your cart is empty. Please add items to the cart before
checking out.</h1>");
}
%>
<a href="ShoppingCart.jsp">Go back to Shopping</a>
</body>
</html>

24

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