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

WT_LabFile

Web technology file lab practical

Uploaded by

nitishsk110076sm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

WT_LabFile

Web technology file lab practical

Uploaded by

nitishsk110076sm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

WEB TECHNOLOGY LAB

(BCS-552)

DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

LLOYD INSTITUTE OF TECHNOLOGY & ENGINEERING


Knowledge Park II, Greater Noida

SESSION: 2024-25 (ODD)

Course: - B.Tech Year: 3rd /5thSem

SUBMITTED BY: SUBMITTED TO:

Name: Faculty Name: Ms. Ananya Kumar


Roll No: Designa on: Assistant Professor
Sec on:
ti
ti
INDEX

S. Experiment Name Date of Date Facul


No. of ty
Conduc
tion Submis Signat
sion ure
1 Write HTML program for designing your
institute website. Display departmental
information of your institute on the website.
2 Write HTML program to design an entry
form for student details/employee
information/faculty details.
3 Develop a responsive website using CSS
and HTML. Website may be for tutorial/
blogs/commercial website.
4 Write programs using HTML and Java
Script for validation of input data.

5 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.
6 Create a Java Bean for Employee
information (EmpID, Name, Salary,
Designation and Department).
7 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.
8 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.
9 Create a Cookie and add these four user
id’s and passwords to this Cookie.
Read the user id and passwords entered in
the Login form and authenticate with the
values available in the cookies
10 Create a table which should contain at
least the following fields: name,
password, email- id, phone number.
11 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.
12 Design and implement a simple
shopping cart example with session
tracking API.
EXPERIMENT 01

Aim : Write HTML program for designing your ins tute website. Display
departmental informa on of your ins tute on the website.
ti
ti
ti
OUTPUT :
EXPERIMENT 02

Aim : Write HTML program to design an entry form for student


details/employee informa on/faculty details.

Index.htm

<!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 Details</title>
<link rel="StyleSheet" href="Style.css">
</head>
<body>

<div class="container">
<h2>Student Entry Form</h2>
<form action="#" method="post">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" required>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>

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


<input type="tel" id="phone" name="phone" required>

<label for="course">Course:</label>
<select id="course" name="course" required>
<option value="">Select Course</option>
<option value="computer-science">Computer Science</option>
<option value="mechanical-engineering">Mechanical
Engineering</option>
<option value="electrical-engineering">Electrical
Engineering</option>
<option value="civil-engineering">Civil Engineering</option>
</select>
ti
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required>

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


</form>
</div>

</body>
</html>

Style.css

body {
font-family: Arial, sans-
serif; background-color:
#f4f4f4; margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: white;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h2 {
text-align: center;
color: #007BFF;
}
label {
display: block;
margin: 10px 0 5px;
}
input[type="text"],
input[type="email"],
input[type="tel"],
select {
width: 100%;
padding: 10px;
margin: 5px 0
15px;
border: 1px solid
#ccc; border-radius:
5px;
}
input[type="submit"]
{ background-color:
#007BFF; color: white;
border: none;
padding: 10px;
border-radius:
5px; cursor:
pointer; font-
size: 16px;

OUTPUT:
EXPERIMENT 03

Aim : Develop a responsive website using CSS and HTML.


Website may be for tutorial/blogs/commercial website.

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Blog</title>
<link rel="stylesheet" href="style.css">
</head>
<body>

<header>
<h1>My Blog</h1>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#blog">Blog</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>

<main>
<section id="about">
<h2>About Me</h2>
<p>Welcome to my blog! I share my thoughts on technology,
lifestyle, and everything in between.</p>
</section>

<section id="blog">
<h3>Post Title 1</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Integer nec odio. Praesent libero. Sed cursus ante dapibus diam.</p>
</div>
<div class="post">
<h3>Post Title 2</h3>
<p>Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis
sagittis ipsum. Praesent mauris.</p>
</div>
<div class="post">
<h3>Post Title 3</h3>
<p>Fusce nec tellus sed augue semper porta. Mauris massa.
Vestibulum lacinia arcu eget nulla.</p>
</div>
</section>
</main>

<footer>
<p>&copy; 2024 My Blog. All Rights Reserved.</p>
</footer>

</body>

Style.css

* {
box-sizing: border-box;
margin: 0;
padding: 0;
}

body {
font-family: Arial, sans-
serif; line-height: 1.6;
background-color: #f4f4f4;
}
background:#007BFF;
color: whit;
padding: 20px 0;
text-align: center;
}

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

nav ul li {
display: inline;
margin: 0 15px;
}

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

main {
max-width: 800px;
margin: 20px auto;
padding: 20px;
background: white;
border-radius:
8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h2 {
color: #007BFF;
margin-bottom:
10px;
}
.post {margin-bottom: 20px; padding: 15px;border: 1px solid #ccc;
border-radius:5px;}
footer {
text-align: center;
padding: 10px;
background: #333;
color: white;
}

@media (max-width: 600px)


{ nav ul li {
display:
block;
margin: 10px
0;
}

main {
padding: 10px;

OUTPUT:
EXPERIMENT 04

Aim : Write programs using HTML and Java Script for valida on
of input data.

Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Input Validation Form</title>
<link rel="StyleSheet" href="Style.css">
</head>
<body>
<script src="Script.js"></script>
<div class="container">
<h2>Registration Form</h2>
<form id="registrationForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<div class="error" id="usernameError">Please enter a username.</div>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<div class="error" id="emailError">Please enter a valid email.</div>

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


<input type="tel" id="phone" name="phone" required>
<div class="error" id="phoneError">Please enter a valid phone
number.</div>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<div class="error" id="passwordError">Please enter a password.</div>

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


</form>

</div>
</body>
</html>
ti
Style.css
body {
font-family: Arial, sans-
serif; background-color:
#f4f4f4; margin: 0;
padding: 20px;
}
.container {
max-width: 400px;
margin: auto;
padding: 20px;
background:
white; border-
radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
color: #007BFF;
}
label {
display: block;
margin: 10px 0
5px;
}
input[type="text"],
input[type="email"],
input[type="tel"],
input[type="password"] {
width: 100%;
padding: 10px;
margin: 5px 0
15px;
font-size: 0.9em;
display: none;
}
input[type="submit"]
{ background-color:
#007BFF; color: white;
border: none;
padding: 10px;
border-radius:
5px; cursor:
pointer; font-
size: 16px;
width: 100%;
}
input[type="submit"]:hover

Javascript:-

document.getElementById('registrationForm').addEventListener('submit',
function(event) {
let valid = true;

// Clear previous errors


const errorElements = document.querySelectorAll('.error');
errorElements.forEach(error => error.style.display = 'none');

// Validate Username
const username =
document.getElementById('username').value; if (username
=== '') {
document.getElementById('usernameError').style.display =
'block'; valid = false;
}

// Validate Email
const email =
document.getElementById('email').value; const
valid = false;
}

// Validate Phone Number


const phone = document.getElementById('phone').value;
const phonePattern = /^\d{10}$/; // Adjust regex based on your
requirement
if (!phonePattern.test(phone))
{ document.getElementById('phoneError').style.display =
'block'; valid = false;
}

// Validate Password
const password =
document.getElementById('password').value; if
(password === '') {
document.getElementById('passwordError').style.display =
'block'; valid = false;
}

if (!valid) {

OUTPUT:
EXPERIMENT 05

Aim : Write a program in XML for crea on of DTD, which


speci es set of rules. Create a style sheet in CSS/ XSL & display
the document in internet explorer.

Data.xml

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


<!DOCTYPE library SYSTEM "library.dtd">
<library>
<book>
<title>XML Basics</title>
<author>John Doe</author>
<year>2021</year>
<genre>Education</genre>
</book>
<book>
<title>Learning XSLT</title>
<author>Jane Smith</author>
<year>2022</year>
<genre>Education</genre>
</book>
</library>

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


<!DOCTYPE library SYSTEM "library.dtd">
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<library>
<book>
<title>XML Basics</title>
<author>John Doe</author>
<year>2021</year>
<genre>Education</genre>
</book>
<book>

<year>2022</year>
<genre>Education</genre>
</book>
</library>
fi
ti
Library.dtd
<!ELEMENT library (book+)>
<!ELEMENT book (title, author, year, genre)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT genre (#PCDATA)>

Style.xsl

<?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>
<head>
<title>Book Library</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: #007BFF;
}
.book {
border: 1px solid #ccc;
margin: 10px 0;
padding: 10px;
}
</style>
</head>
<body>
<h1>Library Collection</h1>
<xsl:for-each select="library/book">
<div class="book">
<h2><xsl:value-of select="title"/></h2>
<p><strong>Author:</strong> <xsl:value-of
select="author"/></p>
<p><strong>Year:</strong> <xsl:value-of
select="year"/></p>
<p><strong>Genre:</strong> <xsl:value-of
select="genre"/></p>
</div>
</xsl:for-each>
</body>
</html>
</xsl:template>
EXPERIMENT 06

Aim : Create a Java Bean for Employee informa on (EmpID,


Name, Salary, Designa on and Department).

Step1. Create a Employee.java and EmployeeMain.java class

Step2. Go to Employee.java and write the code:-


ti
ti
Step3. Go to EmployeeMain.java and write the code:-
OUTPUT:
EXPERIMENT 07

Aim : Build a command-line u lity using Node.js that performs


a speci c task, such as conver ng text to uppercase,
calcula ng the factorial of a number, or genera ng random
passwords.

Step1. Create le TextToUppercase.js


const readline = require('readline');

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

rl.question("Enter text to convert to uppercase: ",


(input)=> { console.log("Uppercase:

Step 2. Create le FactorialCalulating.js


const readline = require('readline');

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

function factorial(n)
{ if (n === 0
|| n === 1) {
return 1;
} else {
}

rl.question('Enter a number:', (number) => {


console.log(`The factorial of ${number} is ${factorial(number) `);
rl.close();
fi
ti
fi
fi
ti
ti
ti
Step 3. Create a le PasswordGenerator.js
const crypto = require('crypto');

function generatePassword(length) {

const charset =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$
%^&*()_-=';
let password = '';
for (let i = 0; i < length; i++) {
password += charset[crypto.randomInt(0,
charset.length)];
}
return password;
}

const readline = require('readline');

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

rl.question('Enter the desired password


length:', (length) => {
console.log(generatePassword(length));

Output:
fi
Experiment - 08

Aim: Develop a script that uses MongoDB's aggrega on


framework to perform opera ons like grouping, ltering, and
sor ng. For instance, aggregate user data to nd the average
age of users in di erent ci es.

Prerequisites:
1. Install MongoDB Driver: npm install mongodb
2. Have a MongoDB database with a users collection.

Code:
aggregate-users.js:
const { MongoClient } = require('mongodb');
// MongoDB URI and Database/
Collec on Names const uri =
"mongodb+srv://
akadityakumar421:*****@cluster0.6sivg.mongodb.ne t/";
const dbName =
"userDB"; const
collec onName =
"users";

async func on
aggregateUserData() { const
client = new MongoClient(uri);

try {
// Connect to the MongoDB server
await client.connect();
console.log("Connected to MongoDB");
ti
ti
ti
ti
ff
ti
ti
fi
fi
ti
const db = client.db(dbName);
const collec on = db.collection(collectionName);

// Aggrega on
Pipeline const
pipeline = [
{
$group: {
_id: "$city",
averageAge: { $avg: "$age"
}, userCount: { $sum: 1 }
}
},
{ $sort: { averageAge: -1 } }
];

// Execute the aggrega on pipeline


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

console.log("Aggrega on
Result:"); console.log(result);
}
catch (err) {
console.error("Error performing aggrega on:", err);
}
nally {
// Close the
connec on
await
client.close();
console.log("MongoDB connection closed");
}
fi
ti
ti
ti
ti
ti
ti
}

// Run the aggrega on


func on
aggregateUserData();

Output:
ti
ti
Experiment - 09

Aim: Assume four users user1, user2, user3 and user4 having
the passwords pwd1, pwd2, pwd3 and pwd4 respec vely.
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 authen cate with the values available in the cookies.

Code:
LoginServlet.java:
import
java.io.*;
import
javax.servlet.
*;
import javax.servlet.http.*;

public class LoginServlet extends H pServlet {

// Handles HTTP GET requests to set cookies for user


creden als protected void
doGet(HttpServletRequest request,
H pServletResponse response) throws ServletExcep on,
IOExcep on { response.setContentType("text/html");

// Create a cookie for storing user credentials


Cookie user1 = new Cookie("user1",
"pwd1"); Cookie user2 = new
Cookie("user2", "pwd2"); Cookie
user3 = new Cookie("user3",
tt
ti
ti
ti
tt
ti
ti
"pwd3"); Cookie user4 = new
Cookie("user4", "pwd4");

// Set the max age for cookies (op onal, 1 day here)
user1.setMaxAge(24 * 60 * 60);
user2.setMaxAge(24 * 60 * 60);
user3.setMaxAge(24 * 60 * 60);
user4.setMaxAge(24 * 60 * 60);

// Add cookies to the


response
response.addCookie(
user1);
response.addCookie(
user2);
response.addCookie(
user3);
response.addCookie(
user4);

// Respond to the client


PrintWriter out = response.getWriter();
out.println("<h2>Cookies have been set for
users.</h2>"); out.println("<a
href='login.html'>Go to Login</a>");
}

// Handles HTTP POST requests to authen cate user


protected void doPost(HttpServletRequest
request, H pServletResponse response) throws
ServletExcep on, IOExcep on {
tt
ti
ti
ti
ti
response.setContentType("text/html");

// Read user input from the login form


String userId = request.getParameter("userid");
String password = request.getParameter("password");

// Retrieve cookies from the


client Cookie[] cookies =
request.getCookies(); boolean
isAuthen cated = false;

if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(userId)
&& cookie.getValue().equals(password)) {
isAuthen cate
d = true; break;
}
}
}

// Generate the response based on authen ca on


PrintWriter out = response.getWriter();
if (isAuthen cated) {
out.println("<h2>Welcome, " + userId + "!</h2>");
} else {
out.println("<h2>Invalid creden als. Please try again.</h2>");
out.println("<a href='login.html'>Back to Login</a>");
}
}
}
ti
ti
ti
ti
ti
ti
login.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial- scale=1.0">
< tle>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form ac on="LoginServlet" method="post">
<label for="userid">User ID:</label>
<input type="text" id="userid" name="userid" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password"
name="password" required>
<br><br>
<bu on type="submit">Login</button>
</form>
</body>
</html>
ti
tt
ti
Output:
Experiment - 10

Aim: Create a table which should contain at least the following


elds: 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 bu on in the registra on page.

Code:
1. Create the Database Table:
CREATE DATABASE
user_database; USE
user_database;
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY
KEY, name VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT
NULL, email_id VARCHAR(100)
UNIQUE NOT NULL,
phone_number VARCHAR(15) NOT NULL );

2. register.jsp:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
ini al- scale=1.0">
< tle>User Registration</title>
</head>
<body>
fi
ti
ti
tt
ti
<h2>User Registration</h2>
<form ac on="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>
<bu on type="submit">Register</button>
</form>
</body>
</html>

3. RegisterServlet.java:
import
java.io.*;
import
java.sql.*;
import
javax.servlet.
*;
import javax.servlet.http.*;

public class RegisterServlet extends H pServlet {


// Database connec on
tt
ti
ti
tt
details private sta c nal
String JDBC_URL =
"jdbc:mysql://localhost:3306/
user_database"; private sta c nal
String JDBC_USER = "aditya";
private sta c nal String JDBC_PASSWORD = "aditya_eight";

@Override
protected void doPost(H pServletRequest request,
H pServletResponse response) throws ServletExcep on,
IOExcep on {
response.setContentType("text/html");

// Read form data


String name = request.getParameter("name");
String password =
request.getParameter("password"); String email =
request.getParameter("email");
String phone = request.getParameter(“phone");
PrintWriter out = response.getWriter();

try (Connec on connec on =


DriverManager.getConnection(JDBC_URL, JDBC_USER,
JDBC_PASSWORD)) {
// Insert user data into the database
String insertQuery = "INSERT INTO users (name,
password, email_id, phone_number) VALUES (?, ?, ?, ?)";
PreparedStatement preparedStatement =
connection.prepareStatement(insertQuery);
preparedStatement.setString(1,
name);
preparedStatement.setString(2,
tt
ti
ti
ti
fi
ti
fi
ti
tt
ti
fi
ti
password);
preparedStatement.setString(3,
email);
preparedStatement.setString(4,
phone);
int rows = preparedStatement.executeUpdate();

if (rows > 0) {
out.println("<h2>Registration Successful!</h2>");
} else {
out.println("<h2>Registra on Failed. Try again!</h2>");
}
// Display all users
out.println("<h2>Registered
Users:</h2>");
String selectQuery = "SELECT name, email_id,
phone_number FROM users";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectQuery);

out.println("<table border='1'><tr><th>Name</
th><th>Email ID</th><th>Phone Number</th></tr>");
while (resultSet.next()) {
out.println("<tr><td>" + resultSet.getString("name") +
"</td><td>" +
resultSet.getString("email_id") + "</td><td>" +
resultSet.getString("phone_number") + "</td></tr>");
}
out.println("</table>");
} catch (SQLExcep on
e)
{ e.printStackTrace()
ti
ti
;
out.println("<h2>Error: " + e.getMessage() + "</h2>");
}
}
}
Output:
Experiment - 11

Aim: Write a JSP which insert the details of the 3 or 4 users


who register with the web site by using registra on form.
Authen cate the user when he submits the login form using
the user name and password from the database.

Code:

<!-- registra on.jsp -->

<%@ page language="java" contentType="text/html;


charset=UTF-8" pageEncoding="UTF-8" %>

<%@ page import="java.sql.*" %>

<!DOCTYPE html>

<html>

<head>

< tle>User Registra on</ tle>

</head>

<body>

<h1>Register Here</h1>

<form ac on="register.jsp" method="post">

<label for="username">Username:</label>

<input type="text" id="username" name="username"


required><br>
ti
ti
ti
ti
ti
ti
ti
<label for="password">Password:</label>

<input type="password" id="password" name="password"


required><br>

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

<input type="email" id="email" name="email"


required><br>

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

</form>

<h1>Login Here</h1>

<form ac on="login.jsp" method="post">

<label for="loginUsername">Username:</label>

<input type="text" id="loginUsername"


name="username" required><br>

<label for="loginPassword">Password:</label>

<input type="password" id="loginPassword"


name="password" required><br>

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


ti
</form>

</body>

</html>

<!-- register.jsp -->

<%@ page language="java" contentType="text/html;


charset=UTF-8" pageEncoding="UTF-8" %>

<%@ page import="java.sql.*" %>

<%

String username = request.getParameter("username");

String password = request.getParameter("password");

String email = request.getParameter("email");

try {

Class.forName("com.mysql.cj.jdbc.Driver");

Connec on conn =
DriverManager.getConnec on("jdbc:mysql://localhost:3306/
yourdatabase", "root", "password");

String query = "INSERT INTO users (username, password,


email) VALUES (?, ?, ?)";

PreparedStatement stmt =
conn.prepareStatement(query);
ti
ti
stmt.setString(1, username);

stmt.setString(2, password);

stmt.setString(3, email);

stmt.executeUpdate();

out.println("<h1>Registra on Successful</h1>");

} catch (Excep on e) {

out.println("<h1>Error: " + e.getMessage() + "</h1>");

%>

<!-- login.jsp -->

<%@ page language="java" contentType="text/html;


charset=UTF-8" pageEncoding="UTF-8" %>

<%@ page import="java.sql.*" %>

<%

String username = request.getParameter("username");

String password = request.getParameter("password");

try {

Class.forName("com.mysql.cj.jdbc.Driver");

Connec on conn =
DriverManager.getConnec on("jdbc:mysql://localhost:3306/
ti
ti
ti
ti
yourdatabase", "root", "password");

String query = "SELECT * FROM users WHERE username


= ? AND password = ?";

PreparedStatement stmt =
conn.prepareStatement(query);

stmt.setString(1, username);

stmt.setString(2, password);

ResultSet rs = stmt.executeQuery();

if (rs.next()) {

out.println("<h1>Login Successful</h1>");

} else {

out.println("<h1>Invalid Creden als</h1>");

} catch (Excep on e) {

out.println("<h1>Error: " + e.getMessage() + "</h1>");

%>
ti
ti
Output:
Experiment - 12

Aim: Design and implement a simple shopping cart example


with session tracking API.

Code:

package com.example;

import java.io.IOExcep on;

import java.io.PrintWriter;

import java.u l.ArrayList;

import java.u l.List;

import javax.servlet.ServletExcep on;

import javax.servlet.annota on.WebServlet;

import javax.servlet.h p.H pServlet;

import javax.servlet.h p.H pServletRequest;

import javax.servlet.h p.H pServletResponse;

import javax.servlet.h p.H pSession;

@WebServlet("/ShoppingCart")

public class ShoppingCartServlet extends H pServlet {

private sta c nal long serialVersionUID = 1L;

@Override

protected void doGet(H pServletRequest request,


ti
ti
ti
fi
tt
tt
tt
tt
ti
tt
tt
tt
tt
ti
ti
tt
tt
H pServletResponse response) throws ServletExcep on,
IOExcep on {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

H pSession session = request.getSession();

// Retrieve the shopping cart from the session, or create a


new one if it doesn't exist

List<String> cart = (List<String>)


session.getA ribute("cart");

if (cart == null) {

cart = new ArrayList<>();

session.setA ribute("cart", cart);

String item = request.getParameter("item");

if (item != null && !item.trim().isEmpty()) {

cart.add(item);

out.println("<html><head>< tle>Shopping Cart</ tle></


head><body>");

out.println("<h1>Your Shopping Cart</h1>");

if (cart.isEmpty()) {
tt
tt
ti
tt
tt
ti
ti
ti
out.println("<p>Your cart is empty.</p>");

} else {

out.println("<ul>");

for (String cartItem : cart) {

out.println("<li>" + cartItem + "</li>");

out.println("</ul>");

out.println("<h2>Add More Items</h2>");

out.println("<form ac on='ShoppingCart'
method='GET'>");

out.println("<input type='text' name='item'


placeholder='Enter item name'>");

out.println("<input type='submit' value='Add to Cart'>");

out.println("</form>");

out.println("<h2>Session Details</h2>");

out.println("<p>Session ID: " + session.getId() + "</p>");

out.println("</body></html>");

@Override
ti
protected void doPost(H pServletRequest request,
H pServletResponse response) throws ServletExcep on,
IOExcep on {

doGet(request, response);

Output:
tt
ti
tt
ti

You might also like