0% found this document useful (0 votes)
20 views23 pages

Web Technology

The document contains multiple HTML programs, each showcasing different web functionalities such as a welcome page for an institute, an entry form, a responsive website, a form validation script, an XML document for a bookstore, and a Java Bean class for managing employee information. Each program includes structured HTML, CSS for styling, and JavaScript for interactivity or functionality. The content highlights various aspects of web development and programming concepts.

Uploaded by

theparthtomar
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)
20 views23 pages

Web Technology

The document contains multiple HTML programs, each showcasing different web functionalities such as a welcome page for an institute, an entry form, a responsive website, a form validation script, an XML document for a bookstore, and a Java Bean class for managing employee information. Each program includes structured HTML, CSS for styling, and JavaScript for interactivity or functionality. The content highlights various aspects of web development and programming concepts.

Uploaded by

theparthtomar
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

Program No.

1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Institute</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f9;
}
header {
background-color:
#0066cc; color: white;
text-align: center;
padding: 1rem 0;
}
nav {
background: #004080;
color: white;
padding: 1rem;
text-align: center;
}
nav a {
color: white;
text-decoration: none;
margin: 0 10px;
font-weight: bold;
}
nav a:hover {
text-decoration: underline;
}
.container {
margin: 2rem auto;
width: 80%;
text-align: center;
}
.department {
margin-bottom: 2rem;
padding: 1rem;
background: white;
border: 1px solid #ddd;
border-radius: 5px;
}
footer {
background-color:
#004080;
color: white;
text-align: center;
padding: 1rem 0;
margin-top: 2rem;
}
</style>
</head>
<body>
<header>
<h1>Welcome to My Institute</h1>
<p>Your gateway to quality education</p>
</header>
<nav>
<a href="#cse">CSE</a>
<a href="#ece">ECE</a>
<a href="#mech">Mechanical</a>
<a href="#civil">Civil</a>
</nav>
<div class="container">
<section id="cse" class="department">
<h2>Computer Science and Engineering (CSE)</h2>
<p>Learn programming, software development, and AI with our advanced
curriculum.</p>
</section>
<section id="ece" class="department">
<h2>Electronics and Communication Engineering (ECE)</h2>
<p>Explore the world of electronics, microprocessors, and telecommunications.</p>
</section>
<section id="mech" class="department">
<h2>Mechanical Engineering</h2>
<p>Study thermodynamics, robotics, and machine design with expert faculty.</p>
</section>
<section id="civil" class="department">
<h2>Civil Engineering</h2>
<p>Design sustainable infrastructure and study advanced construction
techniques.</p>
</section>
</div>
<footer>
<p>© 2024 My Institute. All rights reserved.</p>
</footer>
</body>
</html>
Output:
Program No. 2
<!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: #f0f8ff;
}
.container {
max-width: 600px;
margin: 2rem auto;
background: white;
padding: 1.5rem;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #333;
}
label {
display: block;
margin: 10px 0 5px;
font-weight: bold;
}
input, select, textarea {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type="submit"] {
background-color: #0066cc;
color: white;
border: none;
cursor: pointer;
font-size: 16px;
font-weight: bold;
}
input[type="submit"]:hover {
background-color: #004080;
}
</style>
</head>
<body>
<div class="container">
<h1>Entry Form</h1>
<form action="#" method="post">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" name="fullName" placeholder="Enter your full
name" required>
<label for="id">ID Number:</label>
<input type="text" id="id" name="id" placeholder="Enter your ID number"
required>
<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>
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" placeholder="Enter your email
address" required>
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" placeholder="Enter your phone
number" required>
<label for="department">Department:</label>
<select id="department" name="department" required>
<option value="">Select Department</option>
<option value="cse">Computer Science</option>
<option value="ece">Electronics</option>
<option value="mech">Mechanical</option>
<option value="civil">Civil</option>
</select>
<label for="address">Address:</label>
<textarea id="address" name="address" rows="4" placeholder="Enter your
address"></textarea>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
Program No. 3
<!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>
/* General Styles */
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
line-height: 1.6;
}
header {
background: #333;
color: #fff;
padding: 1rem 0;
text-align: center;
}
header h1 {
margin: 0;
font-size: 2.5rem;
}
nav {
background: #444;
padding: 0.5rem;
text-align: center;
}
nav a {
color: #fff;
text-decoration: none;
margin: 0 10px;
font-weight: bold;
}
nav a:hover {
text-decoration: underline;
}
.container {
width: 90%;
max-width: 1200px;
margin: 2rem auto;
}
.hero {
background: url('https://via.placeholder.com/1200x400') no-repeat center
center/cover;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
color: white;
text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.8);
font-size: 2rem;
font-weight: bold;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
.card {
background: white;
padding: 1rem;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: center;
}
.card img {
max-width: 100%;
border-radius: 5px;
}
.card h3 {
margin: 1rem 0;
}
.card p {
color: #555;
}
footer {
background: #333;
color: white;
text-align: center;
padding: 1rem 0;
margin-top: 2rem;
}
/* Responsive Styles */
@media (max-width: 768px) {
header h1 {
font-size: 2rem;
}
.hero {
font-size: 1.5rem;
}
}
</style>
</head>
<body>
<header>
<h1>My Responsive Website</h1>
</header>
<nav>
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#services">Services</a>
<a href="#contact">Contact</a>
</nav>
<div class="hero">
Welcome to Our Website!
</div>
<div class="container">
<section id="about">
<h2>About Us</h2>
<p>We are dedicated to providing quality content and services to our users. Our
responsive design ensures a great experience on any device.</p>
</section>
<section id="services" class="grid">
<div class="card">
<img src="https://via.placeholder.com/300" alt="Service 1">
<h3>Service 1</h3>
<p>Learn about our first amazing service and what we offer.</p>
</div>
<div class="card">
<img src="https://via.placeholder.com/300" alt="Service 2">
<h3>Service 2</h3>
<p>Explore our second service, tailored to your needs.</p>
</div>
<div class="card">
<img src="https://via.placeholder.com/300" alt="Service 3">
<h3>Service 3</h3>
<p>Discover our third service and how it benefits you.</p>
</div>
</section>
</div>
<footer>
<p>© 2024 My Website. All rights reserved.</p>
</footer>
</body>
</html>
Program No. 4
<!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;
margin: 0;
padding: 0;
background-color: #f4f4f9;
}
.container {
max-width: 500px;
margin: 2rem auto;
background: white;
padding: 1.5rem;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
}
label {
display: block;
margin: 10px 0 5px;
font-weight: bold;
}
input {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type="submit"] {
background-color: #0066cc;
color: white;
border: none;
cursor: pointer;
font-size: 16px;
font-weight: bold;
}
input[type="submit"]:hover {
background-color: #004080;
}
.error {
color: red;
font-size: 0.9rem;
}
</style>
</head>
<body>
<div class="container">
<h1>Input Validation Form</h1>
<form id="myForm" onsubmit="return validateForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your name">
<div id="nameError" class="error"></div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email">
<div id="emailError" class="error"></div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter your
password">
<div id="passwordError" class="error"></div>
<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone" placeholder="Enter your phone
number">
<div id="phoneError" class="error"></div>
<input type="submit" value="Submit">
</form>
</div>
<script>
function validateForm() {
// Clear previous error messages
document.getElementById("nameError").textContent = "";
document.getElementById("emailError").textContent = "";
document.getElementById("passwordError").textContent = "";
document.getElementById("phoneError").textContent = "";
let isValid = true;
// Get form values
const name = document.getElementById("name").value.trim();
const email = document.getElementById("email").value.trim();
const password = document.getElementById("password").value.trim();
const phone = document.getElementById("phone").value.trim();
// Name validation
if (name === "") {
document.getElementById("nameError").textContent = "Name is required.";
isValid = false;
}
// Email validation
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (email === "" || !emailPattern.test(email)) {
document.getElementById("emailError").textContent = "Valid email is required.";
isValid = false;
}
// Password validation
if (password === "" || password.length < 6) {
document.getElementById("passwordError").textContent = "Password must be at
least 6 characters.";
isValid = false;
}
// Phone validation
const phonePattern = /^[0-9]{10}$/;
if (phone === "" || !phonePattern.test(phone)) {
document.getElementById("phoneError").textContent = "Valid 10-digit phone
number is required.";
isValid = false;
}
return isValid;
}
</script>
</body>
</html>
Program No. 5
XML Document (books.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE bookstore [
<!ELEMENT bookstore (book+)>
<!ELEMENT book (title, author, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ATTLIST book category CDATA #REQUIRED>]>
<bookstore>
<book category="Fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<price>10.99</price>
</book>
<book category="Non-Fiction">
<title>Sapiens: A Brief History of Humankind</title>
<author>Yuval Noah Harari</author>
<price>14.99</price>
</book>
<book category="Science">
<title>Cosmos</title>
<author>Carl Sagan</author>
<price>12.99</price>
</book>
</bookstore>
. CSS for Styling (books.css)
This stylesheet adds a bit of style to the table.
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
color: #333;
margin: 0;
padding: 20px;
}
h1 {
text-align: center;
color: #0066cc;
}
table {
width: 80%;
margin: 20px auto;
border-collapse: collapse;
background: white;
border: 1px solid #ddd;
}
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
}
th {
background: #0066cc;
color: white;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
Program No. 6
Java Bean class for managing Employee Information with properties like EmpID, Name, Salary,
Designation, and Department.
import java.io.Serializable;
public class Employee implements Serializable {
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;
}
// Getters and Setters
public int getEmpID() {
return empID;
}
public void setEmpID(int empID) {
this.empID = empID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
// Override toString() method for better display
@Override
public String toString() {
return "Employee{" +
"empID=" + empID +
", name='" + name + '\'' +
", salary=" + salary +
", designation='" + designation + '\'' +
", department='" + department + '\'' +
'}';
}
}
Serializable Interface:
The class implements Serializable to allow its objects to be serialized for network
transmission or file storage.
Default Constructor:
Ensures the bean can be instantiated without arguments.
Parameterized Constructor:
Convenient for creating objects with initial values.
Getters and Setters:
Provide encapsulated access to the properties.
toString Method:
Useful for debugging or displaying employee information in a readable format.
Main Class: TestEmployee.java
public class TestEmployMainee {
public static void main(String[] args) {
// Create Employee Object
Employee emp = new Employee(101, "John Doe", 75000, "Software Engineer", "IT");
// Display Employee Information
System.out.println(emp);
// Modify Employee Salary
emp.setSalary(80000);
// Display Updated Employee Information
System.out.println("Updated Employee Info: " + emp);
}
}

Output:
Employee{empID=101, name='John Doe', salary=75000.0, designation='Software
Engineer', department='IT'}
Updated Employee Info: Employee{empID=101, name='John Doe', salary=80000.0,
designation='Software Engineer', department='IT'}
Program No. 7
command-line utility built using Node.js that performs three specific tasks:
1. Convert text to uppercase
2. Calculate the factorial of a number
3. Generate a random password
1.Initialize the Node.js Project
Run the following command to initialize a new Node.js project:
npm init –y
2.Install Required Package
Install the commander package to manage command-line arguments:
npm install commander
Create the Utility Script
Save the following code in a file named cli-tool.js
Code: cli-tool.js
#!/usr/bin/env node
const { program } = require('commander');
program
.version('1.0.0')
.description('Command-line utility for text manipulation and calculations');
// Convert text to uppercase
program
.command('uppercase <text>')
.description('Convert text to uppercase')
.action((text) => {
console.log('Uppercase:', text.toUpperCase());
});
// Calculate factorial
program
.command('factorial <number>')
.description('Calculate the factorial of a number')
.action((number) => {
const num = parseInt(number, 10);
if (isNaN(num) || num < 0) {
console.error('Please provide a valid non-negative number');
} else {
const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));
console.log(Factorial of ${num}:, factorial(num));
}
});
// Generate a random password
program
.command('password [length]')
.description('Generate a random password of specified length (default: 12)')
.action((length) => {
const pwdLength = parseInt(length, 10) || 12;
const chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*
()';
let password = '';
for (let i = 0; i < pwdLength; i++) {
password += chars.charAt(Math.floor(Math.random() * chars.length));
}
console.log('Generated Password:', password);
});
// Parse the arguments
program.parse(process.argv);

1..Convert to Uppercase
node cli-tool.js uppercase "hello world"
Output:
Uppercase: HELLO WORLD

2.Calculate Factorial
node cli-tool.js factorial 5
Output:
Factorial of 5: 120

3.Generate Random Password


node cli-tool.js password 16
Output:
Generated Password: aB3$cD5&fG7*HjK8
Program No. 8
Prerequisites
1. Install Node.js: Ensure Node.js is installed on your system.
2. Install MongoDB: You should have MongoDB installed and running.
3. Install Dependencies: npm install mongodb
Sample Data (Insert into MongoDB): Create a collection users in a
database (e.g., test) with sample documents like:
[
{ "name": "Alice", "age": 25, "city": "New York" },
{ "name": "Bob", "age": 30, "city": "San Francisco" },
{ "name": "Charlie", "age": 35, "city": "New York" },
{ "name": "David", "age": 40, "city": "Los Angeles" },
{ "name": "Eve", "age": 28, "city": "San Francisco" },
{ "name": "Frank", "age": 50, "city": "Los Angeles" }
]
Script: aggregateUsers.js:
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017'; // Replace with your
MongoDB connection string
const dbName = 'test'; // Replace with your database name
const collectionName = 'users'; // Replace with your collection name
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" }, // Calculate average age
userCount: { $sum: 1 } // Count the number of users in each
city
}
},
{
$match: { userCount: { $gt: 1 } } // Filter cities with more than 1
user
},
{
$sort: { averageAge: -1 } // Sort by average age in descending
order
}
];
// Execute Aggregation
const results = await collection.aggregate(pipeline).toArray();
// Display Results
console.log('Aggregated User Data:');
results.forEach(result => {
console.log(`City: ${result._id}, Average Age:
${result.averageAge.toFixed(2)}, User Count: ${result.userCount}`);
});
} catch (err) {
console.error('Error performing aggregation:', err);
} finally {
await client.close();
}
aggregateUserData();
Example Output
For the given sample data, the output will look like:
Connected to MongoDB
Aggregated User Data:
City: New York, Average Age: 30.00, User Count: 2
City: San Francisco, Average Age: 29.00, User Count: 2
Explanation
1. Aggregation Pipeline:
$group: Groups documents by city and calculates:
o averageAge: The average age of users.
o userCount: The number of users in each city.
$match: Filters cities with more than 1 user.
$sort: Sorts the cities by average age in descending order.
2. MongoDB Connection:
Connects to a MongoDB instance using the MongoClient.
3. Results:
The results are returned as an array, and each document contains:
o city: The name of the city.
o averageAge: The calculated average age of users in that city.
o userCount: The total number of users in the city.
How to Run the Script
1. Save the script as aggregateUsers.js.
2. Run the script using Node.js
node aggregateUsers.js
Program No. 9
UserAuthServlet.java
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("/UserAuthServlet")
public class UserAuthServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
// Step 1: 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 expiration time for cookies (e.g., 1 day)
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);
response.getWriter().println("Cookies created for users! <a
href='login.html'>Go to Login</a>");
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
// Step 2: Read login credentials from the form
String enteredUserId = request.getParameter("userId");
String enteredPassword = request.getParameter("password");
// Read cookies from the request
Cookie[] cookies = request.getCookies();
boolean authenticated = false;
if (cookies != null) {
for (Cookie cookie : cookies) {
// Check if the entered credentials match any cookie
if (cookie.getName().equals(enteredUserId) &&
cookie.getValue().equals(enteredPassword)) {
authenticated = true;
break;
}
}
}
// Display authentication result
if (authenticated) {
response.getWriter().println("<h1>Login Successful!</h1>");
} else {
response.getWriter().println("<h1>Invalid Credentials!</h1>");
}
}
}
login.html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login Form</h1>
<form action="UserAuthServlet" 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>
<button type="submit">Login</button>
</form>
</body>
</html>
Program No. 10
Steps:
1. Database Setup:
o Create a table with fields: name, password, email, and
phone_number.
2. Create a Registration Page:
o An HTML form for user registration.
3. Servlet to Handle Registration:
o Insert user details into the database when the form is submitted.
4. Servlet to Display Users:
o Fetch and display all user data from the database.

Database Table Creation


CREATE DATABASE user_management;
USE user_management;
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
);
Registration Page (HTML Form)
register.html:
<!DOCTYPE html>
<html>
<head><title>Register</title>
</head>
<body>
<h1>User Registration</h1>
<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:</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>
<button type="submit">Register</button>
</form>
</body>
</html>
Servlet for User Registration (RegisterServlet.java)

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Retrieve user input from form
String name = request.getParameter("name");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone")
try {
// Database connection
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/user_management",
"root", "password");
// Insert user data into table
String query = "INSERT INTO users (name, password, email, phone_number)
VALUES (?, ?, ?, ?)";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, name);
pst.setString(2, password);
pst.setString(3, email);
pst.setString(4, phone);
int rows = pst.executeUpdate();
if (rows > 0) {
out.println("<h1>Registration Successful!</h1>");
out.println("<a href='DisplayUsersServlet'>View All Users</a>");
} else {
out.println("<h1>Registration Failed!</h1>");
} // Close resources
pst.close();
con.close()
} catch (Exception e) {
out.println("<h1>Error: " + e.getMessage() + "</h1>");
}
}
}

You might also like