0% found this document useful (0 votes)
28 views51 pages

70 FalguniDabhi PA2

Uploaded by

Falguni Dabhi
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)
28 views51 pages

70 FalguniDabhi PA2

Uploaded by

Falguni Dabhi
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/ 51

Name : Dabhi Falguni Rameshbhai

Roll No : 70
Sem : 8th
Subject : java
M.sc (it)

_____________________________________
Practical Assignment-1
1) Provide an attractive home page . The home page
must have facility to login, register new user and
remember password and recover forgot password
facility.
Registration.jsp :-

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


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
tofit=no">
<title>User Registration</title>
<!-- Include Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
> </head>
<body>

<div class="container mt-5">


<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h4>User Registration</h4>
</div>
<div class="card-body">
<form action="RegisterServlet" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username"
name="username" required>
</div>
<div class="form-group">
<label for="loginId">Login ID</label>
<input type="text" class="form-control" id="loginId" name="loginId"
required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password"
name="password" required>
</div>
<div class="form-group">
<label for="passwordQuestion">Password Question</label>
<input type="text" class="form-control" id="passwordQuestion"
name="passwordQuestion" required>
</div>
<div class="form-group">
<label for="passwordAnswer">Password Answer</label>
<input type="text" class="form-control" id="passwordAnswer"
name="passwordAnswer" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email"
required>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" class="form-control" id="phone" name="phone"
required>
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" id="address"
name="address" required>
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" class="form-control" id="city" name="city"
required>
</div>
<div class="form-group">
<label for="state">State</label>
<input type="text" class="form-control" id="state" name="state"
required>
</div>
<div class="form-group">
<label for="country">Country</label>
<input type="text" class="form-control" id="country"
name="country" required>
</div>
<div class="form-group">
<label for="pin">PIN</label>
<input type="text" class="form-control" id="pin" name="pin"
required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
</div>
</div>
</div>

<!-- Include Bootstrap JS and jQuery -->


<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
></ script> <script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></
script>

</body>
</html>
Login.jsp :-

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


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
tofit=no">
<title>Login Page</title>
<!-- Include Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
> </head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h4>Login</h4>
</div>
<div class="card-body">
<form action="LoginServlet" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username"
name="username" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password"
name="password" required>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input"
id="rememberMe" name="rememberMe">
<label class="form-check-label" for="rememberMe">Remember
Me</label>
</div>
<div class="form-group">
<a href="forgot-password.jsp">Forgot Password?</a>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
</div>
</div>
</div>

<!-- Include Bootstrap JS and jQuery -->


<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
></ script> <script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></
script>
</body>
</html>

forgot-password.jsp :-

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


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
tofit=no">
<title>Forgot Password</title>
<!-- Include Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
> </head>
<body>

<div class="container mt-5">


<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h4>Forgot Password</h4>
</div>
<div class="card-body">
<form action="ResetPasswordServlet" method="post">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email"
required>
</div>
<div class="form-group">
<label for="newPassword">New Password</label>
<input type="password" class="form-control" id="newPassword"
name="newPassword" required>
</div>
<div class="form-group">
<label for="confirmPassword">Confirm Password</label>
<input type="password" class="form-control" id="confirmPassword"
name="confirmPassword" required> </div>
<button type="submit" class="btn btn-primary">Reset
Password</button>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- Include Bootstrap JS and jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js
"></ script> <script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></
script>

</body>
</html>

Conn.java :-

/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt
to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit
this template
*/
// conn.java
// conn.java
package Conn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class conn {


private Connection con;

// Constructor to establish the connection


public Connection connect() {
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish the connection


con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/FashionDB", "root",
"root");
System.out.println("Connected to the database!");
return con;
} catch (ClassNotFoundException | SQLException e) {
// Handle exceptions
// e.printStackTrace();
System.out.println(" Not Connected to the database!");

return null; // Return null if connection fails


}
}
}

LoginServlet.java

:package servlets;

import Conn.conn;

import java.io.IOException; import


java.sql.Connection; import
java.sql.PreparedStatement;
import java.sql.ResultSet; import
java.sql.SQLException;

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(name = "LoginServlet", urlPatterns = {"/LoginServlet"})


public class LoginServlet extends HttpServlet { private static final
long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
// Get form data
String username = request.getParameter("username"); String password
= request.getParameter("password"); boolean rememberMe =
"on".equals(request.getParameter("rememberMe"));

// Database connection
conn myConnection = new conn();
Connection con = myConnection.connect();

if (con != null) {
try {
// SQL query to check login credentials
String sql = "SELECT * FROM UserTB WHERE username = ? AND password =
?";
try (PreparedStatement pstmt = con.prepareStatement(sql))
{ pstmt.setString(1, username);
pstmt.setString(2, password);

try (ResultSet rs = pstmt.executeQuery()) {


if (rs.next()) { // Login successful
String message = "Welcome, " + username + "!";
if (rememberMe) {
message += " (Remember Me checked)";
// Implement remember me functionality if needed
}
response.getWriter().println(message);
} else {
// Login failed
response.getWriter().println("Invalid username or password.");
}
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close the database connection
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} else {
response.getWriter().println("Failed to connect to the database.");
}
}
}

RegisterServlet.java :-

// RegisterServlet.java
package servlets;
import Conn.conn;

import java.io.IOException; import


java.sql.Connection; import
java.sql.PreparedStatement;
import java.sql.SQLException;

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(name = "RegisterServlet", urlPatterns = {"/RegisterServlet"})


public class RegisterServlet extends HttpServlet { private static final long
serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

// Get form data


String username = request.getParameter("username");
String loginId = request.getParameter("loginId");
String password = request.getParameter("password");
String passwordQuestion = request.getParameter("passwordQuestion");
String passwordAnswer = request.getParameter("passwordAnswer");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
String address = request.getParameter("address");
String city = request.getParameter("city");
String state = request.getParameter("state");
String country = request.getParameter("country");
String pin = request.getParameter("pin");

// Database connection
conn myConnection = new conn();
Connection con = myConnection.connect();

if (con != null) {
try {
// SQL query to insert into UserTB
String sql = "INSERT INTO UserTB (username, login_id, password,
password_question, password_answer, email, phone, address, city, state, country,
pin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

// Create a PreparedStatement
try (PreparedStatement pstmt = con.prepareStatement(sql)) {
// Set parameters
pstmt.setString(1, username);
pstmt.setString(2, loginId);
pstmt.setString(3, password);
pstmt.setString(4, passwordQuestion);
pstmt.setString(5, passwordAnswer);
pstmt.setString(6, email);
pstmt.setString(7, phone);
pstmt.setString(8, address);
pstmt.setString(9, city); pstmt.setString(10,
state); pstmt.setString(11, country);
pstmt.setString(12, pin);
// Execute the insert statement
int rowsAffected = pstmt.executeUpdate();

// Check if the insertion was successful


if (rowsAffected > 0) {
response.getWriter().println("Registration successful!");
} else {
response.getWriter().println("Registration failed.");
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close the database
connection try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} else {
response.getWriter().println("Failed to connect to the database.");
}
}
}

ResetPasswordServlet.java

:package servlets; import

Conn.conn;

import java.io.IOException; import


java.sql.Connection; import
java.sql.PreparedStatement;
import java.sql.SQLException;
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(name = "ResetPasswordServlet", urlPatterns =


{"/ResetPasswordServlet"}) public class
ResetPasswordServlet extends HttpServlet { private
static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

// Get form data


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

// Validate if new password and confirm password match


if (!newPassword.equals(confirmPassword)) {
response.getWriter().println("New Password and Confirm
Password do not match.");
return;
}

// Database connection
conn myConnection = new conn();
Connection con = myConnection.connect();

if (con != null) {
try {
// SQL query to update the password in UserTB
String sql = "UPDATE UserTB SET password = ? WHERE email = ?";
try (PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setString(1, newPassword);
pstmt.setString(2, email);
// Execute the update statement
int rowsAffected = pstmt.executeUpdate();

// Check if the update was successful


if (rowsAffected > 0) {
response.getWriter().println("Password reset successful!");
} else {
response.getWriter().println("Invalid email or password reset failed.");
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close the database connection
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} else {
response.getWriter().println("Failed to connect to the database.");
}
}
}
Output :-
4) Present data entry links and forms to administrators to
enter data for new items with facility of add delete , update
and find. ( Give the interface for Product Master and category
Master)

category.jsp :-

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


pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Category Management</title>
<!-- Include Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>

<div class="container mt-5">


<h2>Category Management</h2>
<a href="CategoryServlet?action=add" class="btn btn-primary mb-3">Add
Category</a>
<table class="table">
<thead class="thead-dark">
<tr>
<th>Category ID</th>
<th>Category Name</th>
<th>Parent Category ID</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<c:forEach var="category" items="${categories}">
<tr>
<td>${category.categoryId}</td>
<td>${category.categoryName}</td>
<td>${category.parentCategoryId}</td>
<td>
<a href="CategoryServlet?action=edit&id=${category.categoryId}"
class="btn btn-warning btn-sm">Edit</a>
<a href="CategoryServlet?action=delete&id=${category.categoryId}"
class="btn btn-danger btn-sm">Delete</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>

<!-- Include Bootstrap JS and jQuery -->


<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
></ script> <script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></
script>

</body>
</html>

addCategory.jsp :-

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


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Category</title>
<!-- Include Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>

<div class="container mt-5">


<div class="card">
<div class="card-header">
<h2>Add Category</h2>
</div>
<div class="card-body">
<form action="CategoryServlet" method="post">
<input type="hidden" name="action" value="add">
<div class="form-group">
<label for="categoryName">Category Name</label>
<input type="text" class="form-control" id="categoryName"
name="categoryName" required>
</div>
<div class="form-group">
<label for="parentCategoryId">Parent Category ID</label>
<input type="number" class="form-control" id="parentCategoryId"
name="parentCategoryId" required>
</div>
<button type="submit" class="btn btn-primary">Add Category</button>
</form>
</div>
</div>
</div>

<!-- Include Bootstrap JS and jQuery -->


<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
></ script> <script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></
script>

</body>
</html>
editCategory.jsp :-

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


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Category</title>
<!-- Include Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<div class="card">
<div class="card-header">
<h2>Edit Category</h2>
</div>
<div class="card-body">
<form action="CategoryServlet" method="post">
<input type="hidden" name="action" value="edit">
<input type="hidden" name="categoryId" value="$
{category.categoryId}">
<div class="form-group">
<label for="categoryName">Category Name</label>
<input type="text" class="form-control" id="categoryName"
name="categoryName" value="${category.categoryName}" required>
</div>
<div class="form-group">
<label for="parentCategoryId">Parent Category ID</label>
<input type="number" class="form-control" id="parentCategoryId"
name="parentCategoryId" value="${category.parentCategoryId}" required>
</div>
<button type="submit" class="btn btn-primary">Update
Category</button>
</form>
</div>
</div>
</div>

<!-- Include Bootstrap JS and jQuery -->


<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
></ script> <script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></
script>

</body>
</html>
product.jsp :-

<%@ page import="java.util.List" %>


<%@ page import="Conn.Product" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Product Management</title>
<!-- Include Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
body {
padding: 20px;
}
h2 {
margin-bottom: 20px;
} table { width:
100%; margin-bottom:
20px; border-collapse:
collapse;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
} th, td {
text-align: left;
padding: 12px;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f8f9fa;
font-weight: bold;
}
.action-links a {
margin-right: 10px;
color: #007bff;
}
.action-links a:hover {
text-decoration: underline;
}
a{
color: #007bff;
} a:hover {
color: #0056b3;
text-decoration: none;
}
</style>
</head>
<body>

<div class="container mt-5">


<h2>Product Management</h2>
<a href="ProductServlet?action=add" class="btn btn-primary">Add Product</a>
<table class="table table-bordered">
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Price</th>
<th>Unit</th>
<th>Discount</th>
<th>Image</th>
<th>Category ID</th>
<th>Stock</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- Assuming 'products' is the attribute name containing your list of products
-->
<c:forEach var="product" items="${products}">
<tr>
<td>${product.productId}</td>
<td>${product.productName}</td>
<td>${product.price}</td>
<td>${product.unit}</td>
<td>${product.discount}</td>
<td>${product.image}</td>
<td>${product.categoryId}</td>
<td>${product.stock}</td>
<td class="action-links">
<a href="ProductServlet?action=edit&id=${product.productId}"
class="btn btn-warning btn-sm">Edit</a>
<a href="ProductServlet?action=delete&id=${product.productId}"
class="btn btn-danger btn-sm">Delete</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>

<!-- Include Bootstrap JS and jQuery -->


<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
></ script> <script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></
script>

</body>
</html>

addProduct.jsp :-

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


<html>
<head>
<meta charset="UTF-8">
<title>Add Product</title>
<!-- Include Bootstrap CSS for styling -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
body {
padding: 20px;
}
h1 {
margin-bottom: 20px;
} form {
width: 50%;
margin: auto; }
input {
margin-bottom: 10px;
} button {
padding: 10px 20px;
background-color: #007bff;
color: #fff; border: none;
cursor: pointer;
}
a{
display: block;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="container">
<h1>Add New Product</h1>
<form action="ProductServlet" method="post">
<input type="hidden" name="action" value="add">
<div class="form-group">
<label for="productName">Product Name:</label>
<input type="text" class="form-control" id="productName"
name="productName" required>
</div>
<div class="form-group">
<label for="price">Price:</label>
<input type="text" class="form-control" id="price" name="price" required>
</div>
<div class="form-group">
<label for="unit">Unit:</label>
<input type="text" class="form-control" id="unit" name="unit" required>
</div>
<div class="form-group">
<label for="discount">Discount:</label>
<input type="text" class="form-control" id="discount" name="discount"
required>
</div>
<div class="form-group">
<label for="image">Image:</label>
<input type="text" class="form-control" id="image" name="image"
required>
</div>
<div class="form-group">
<label for="categoryId">Category ID:</label>
<input type="text" class="form-control" id="categoryId"
name="categoryId" required>
</div>
<div class="form-group">
<label for="stock">Stock:</label>
<input type="text" class="form-control" id="stock" name="stock" required>
</div>
<button type="submit" class="btn btn-primary">Add Product</button>
</form>
<a href="ProductServlet" class="btn btn-secondary">Back to Product List</a>
</div>

<!-- Include Bootstrap JS and jQuery -->


<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"><
/ script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js
"></ script> </body> </html>

editProduct.jsp :-

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


<html>
<head>
<meta charset="UTF-8">
<title>Edit Product</title>
<!-- Include Bootstrap CSS for styling -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
body {
padding: 20px;
}
h1 {
margin-
bottom:
20px;
} form {
width: 50%;
margin: auto;
}
input {
margin-bottom: 10px;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: #fff; border: none;
cursor: pointer;
}
a{
display: block;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="container">
<h1>Edit Product</h1>
<form action="ProductServlet" method="post">
<input type="hidden" name="action" value="edit">
<input type="hidden" name="productId" value="${product.productId}">
<div class="form-group">
<label for="productName">Product Name:</label>
<input type="text" class="form-control" id="productName"
name="productName" value="${product.productName}" required>
</div>
<div class="form-group">
<label for="price">Price:</label>
<input type="text" class="form-control" id="price" name="price" value="$
{product.price}" required>
</div>
<div class="form-group">
<label for="unit">Unit:</label>
<input type="text" class="form-control" id="unit" name="unit" value="$
{product.unit}" required>
</div>
<div class="form-group">
<label for="discount">Discount:</label>
<input type="text" class="form-control" id="discount" name="discount"
value="${product.discount}" required>
</div>
<div class="form-group">
<label for="image">Image:</label>
<input type="text" class="form-control" id="image" name="image"
value="${product.image}" required>
</div>
<div class="form-group">
<label for="categoryId">Category ID:</label>
<input type="text" class="form-control" id="categoryId"
name="categoryId" value="${product.categoryId}" required>
</div>
<div class="form-group">
<label for="stock">Stock:</label>
<input type="text" class="form-control" id="stock" name="stock"
value="${product.stock}" required>
</div>
<button type="submit" class="btn btn-primary">Update Product</button>
</form>
<a href="ProductServlet" class="btn btn-secondary">Back to Product List</a>
</div>

<!-- Include Bootstrap JS and jQuery -->


<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"><
/ script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js
"></ script> </body>
</html>
Conn.java :-

/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt
to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit
this template
*/
// conn.java
// conn.java
package Conn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class conn {


private Connection con;

// Constructor to establish the connection


public Connection connect() {
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish the connection


con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/FashionDB", "root",
"root");
System.out.println("Connected to the database!");
return con;
} catch (ClassNotFoundException | SQLException e) {
// Handle exceptions
// e.printStackTrace();
System.out.println(" Not Connected to the database!");

return null; // Return null if connection fails


}
}
}
Category.java :-

/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to
change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Other/File.java to edit this
template
*/
package Conn;

/**
*
* @author root
*/
public class Category {

private int categoryId;


private String categoryName;
private int parentCategoryId;

// Constructors
public Category() {
}

public Category(int categoryId, String categoryName, int parentCategoryId) {


this.categoryId = categoryId; this.categoryName = categoryName;
this.parentCategoryId = parentCategoryId;
}
// Getters and Setters
public int getCategoryId() {
return categoryId;
}

public void setCategoryId(int categoryId) {


this.categoryId = categoryId;
}

public String getCategoryName() {


return categoryName;
}

public void setCategoryName(String categoryName) {


this.categoryName = categoryName;
}

public int getParentCategoryId() {


return parentCategoryId;
}

public void setParentCategoryId(int parentCategoryId) {


this.parentCategoryId = parentCategoryId;
}

// toString method for debugging or logging


@Override
public String toString() {
return "Category{" +
"categoryId=" + categoryId +
", categoryName='" + categoryName + '\'' +
", parentCategoryId=" + parentCategoryId +
'}';
}
}
Product.java :-

/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to
change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this
template
*/
package Conn;

/**
*
* @author root
*/
public class Product {
private int productId;
private String productName;
private double price;
private String unit;
private double discount;
private String image;
private int categoryId;
private int stock;

public int getProductId() {


return productId;
}

public void setProductId(int productId) {


this.productId = productId;
}

public String getProductName() {


return productName;
}

public void setProductName(String productName) {


this.productName = productName;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}

public String getUnit() {


return unit;
}

public void setUnit(String unit) {


this.unit = unit;
}

public double getDiscount() {


return discount;
}

public void setDiscount(double discount) {


this.discount = discount;
}
public String getImage() {
return image;
}

public void setImage(String image) {


this.image = image;
}

public int getCategoryId() {


return categoryId;
}

public void setCategoryId(int categoryId) {


this.categoryId = categoryId;
}
public int getStock() {
return stock;
}

public void setStock(int stock) {


this.stock = stock;
}

@Override public String


toString() { return "Product{" +
"productId=" + productId +
", productName='" + productName + '\'' +
", price=" + price +
", unit='" + unit + '\'' +
", discount=" + discount +
", image='" + image + '\'' +
", categoryId=" + categoryId +
", stock=" + stock +
'}';
}
}
CategoryDAO.java :- package

dao;

import Conn.Category;
import Conn.conn;

import java.sql.Connection;
import
java.sql.PreparedStatement;
import java.sql.ResultSet; import
java.sql.SQLException; import
java.util.ArrayList; import
java.util.List;

public class CategoryDAO { public List<Category>


getAllCategories() { List<Category> categories =
new ArrayList<>(); conn myConnection = new
conn();
try (Connection con = myConnection.connect();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM
CategoryTB");
ResultSet rs = pstmt.executeQuery()) {

while (rs.next()) {
Category category = new Category();
category.setCategoryId(rs.getInt("Category_id"));
category.setCategoryName(rs.getString("Category_name"));
category.setParentCategoryId(rs.getInt("Parent_c_id"));
categories.add(category);
}

} catch (SQLException e) {
e.printStackTrace();
}

return categories;
}

public void addCategory(Category category) {


conn myConnection = new conn();
try (Connection con = myConnection.connect();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO
CategoryTB (Category_name, Parent_c_id) VALUES (?, ?)")) {
pstmt.setString(1, category.getCategoryName());
pstmt.setInt(2, category.getParentCategoryId());
pstmt.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}

public Category getCategoryById(int categoryId) {


Category category = new Category();
conn myConnection = new conn();
try (Connection con = myConnection.connect();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM
CategoryTB WHERE Category_id = ?")) {

pstmt.setInt(1, categoryId);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
category.setCategoryId(rs.getInt("Category_id"));
category.setCategoryName(rs.getString("Category_name"));
category.setParentCategoryId(rs.getInt("Parent_c_id"));
}
}

} catch (SQLException e) {
e.printStackTrace();
}

return category;
}

public void updateCategory(Category category) {


conn myConnection = new conn();
try (Connection con = myConnection.connect();
PreparedStatement pstmt = con.prepareStatement("UPDATE CategoryTB SET
Category_name = ?, Parent_c_id = ? WHERE Category_id = ?")) {

pstmt.setString(1, category.getCategoryName());
pstmt.setInt(2, category.getParentCategoryId());
pstmt.setInt(3, category.getCategoryId());
pstmt.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}

public void deleteCategory(int categoryId) {


conn myConnection = new conn();
try (Connection con = myConnection.connect();
PreparedStatement pstmt = con.prepareStatement("DELETE FROM
CategoryTB WHERE Category_id = ?")) {

pstmt.setInt(1, categoryId);
pstmt.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}
}

ProductDAO.java :-

package dao;

import Conn.conn;
import Conn.Product;

import java.sql.Connection;
import
java.sql.PreparedStatement;
import java.sql.ResultSet; import
java.sql.SQLException; import
java.util.ArrayList; import
java.util.List;

public class ProductDAO { public List<Product>


getAllProducts() { List<Product> products =
new ArrayList<>(); conn myConnection = new
conn();
try (Connection con = myConnection.connect();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM
ProductTB");
ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
Product product = new Product();
product.setProductId(rs.getInt("Product_id"));
product.setProductName(rs.getString("Product_name"));
product.setPrice(rs.getDouble("Price"));
product.setUnit(rs.getString("Unit"));
product.setDiscount(rs.getDouble("Discount"));
product.setImage(rs.getString("Image"));
product.setCategoryId(rs.getInt("Category_id"));
product.setStock(rs.getInt("Stock"));
products.add(product);
}

} catch (SQLException e) {
e.printStackTrace();
}

return products;
}

public void addProduct(Product product) {


conn myConnection = new conn();
try (Connection con = myConnection.connect();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO
ProductTB (Product_name, Price, Unit, Discount, Image, Category_id, Stock) VALUES
(?, ?, ?, ?, ?, ?, ?)")) {

pstmt.setString(1, product.getProductName());
pstmt.setDouble(2, product.getPrice());
pstmt.setString(3, product.getUnit());
pstmt.setDouble(4, product.getDiscount());
pstmt.setString(5, product.getImage());
pstmt.setInt(6, product.getCategoryId());
pstmt.setInt(7, product.getStock());
pstmt.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}

public Product getProductById(int productId) {


Product product = new Product();
conn myConnection = new conn();
try (Connection con = myConnection.connect();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM
ProductTB WHERE Product_id = ?")) {

pstmt.setInt(1, productId);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
product.setProductId(rs.getInt("Product_id"));
product.setProductName(rs.getString("Product_name"));
product.setPrice(rs.getDouble("Price"));
product.setUnit(rs.getString("Unit"));
product.setDiscount(rs.getDouble("Discount"));
product.setImage(rs.getString("Image"));
product.setCategoryId(rs.getInt("Category_id"));
product.setStock(rs.getInt("Stock"));
}
}

} catch (SQLException e) {
e.printStackTrace();
}

return product;
}

public void updateProduct(Product product) {


conn myConnection = new conn();
try (Connection con = myConnection.connect();
PreparedStatement pstmt = con.prepareStatement("UPDATE ProductTB SET
Product_name = ?, Price = ?, Unit = ?, Discount = ?, Image = ?, Category_id = ?,
Stock = ? WHERE Product_id = ?")) {
pstmt.setString(1, product.getProductName());
pstmt.setDouble(2, product.getPrice());
pstmt.setString(3, product.getUnit());
pstmt.setDouble(4, product.getDiscount());
pstmt.setString(5, product.getImage());
pstmt.setInt(6, product.getCategoryId());
pstmt.setInt(7, product.getStock());
pstmt.setInt(8, product.getProductId());
pstmt.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}

public void deleteProduct(int productId) {


conn myConnection = new conn();
try (Connection con = myConnection.connect();
PreparedStatement pstmt = con.prepareStatement("DELETE FROM
ProductTB WHERE Product_id = ?")) {

pstmt.setInt(1, productId);
pstmt.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}
}

CategoryServlet.java :package

servlets;

import Conn.Category;
import dao.CategoryDAO;
import javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;
import java.io.IOException; import static
java.lang.System.out; import java.util.List;

@WebServlet("/CategoryServlet") public class


CategoryServlet extends HttpServlet { private
static final long serialVersionUID = 1L; private
CategoryDAO categoryDAO;

public void init() {


categoryDAO = new CategoryDAO();
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException { String action =
request.getParameter("action");

if (action != null) {
switch (action) {
case "add":
// Show add category form
request.getRequestDispatcher("addCategory.jsp").forward(request,
response);
break;
case "edit":
// Show edit category form int categoryId =
Integer.parseInt(request.getParameter("id")); Category category
= categoryDAO.getCategoryById(categoryId);
request.setAttribute("category", category);
request.getRequestDispatcher("editCategory.jsp").forward(request,
response);
break;
case "delete":
// Perform delete category operation
int deleteCategoryId =
Integer.parseInt(request.getParameter("id"));
categoryDAO.deleteCategory(deleteCategoryId);
response.sendRedirect("CategoryServlet"); break; default:
break;
}
} else {
// Display the list of categories
List<Category> categories = categoryDAO.getAllCategories();
request.setAttribute("categories", categories);
request.getRequestDispatcher("category.jsp").forward(request, response);
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException { // Handle add/update
category form submission String action = request.getParameter("action");
if (action=="add") {
String categoryName = request.getParameter("categoryName");
int parentCategoryId =
Integer.parseInt(request.getParameter("parentCategoryId"));

Category newCategory = new Category();


newCategory.setCategoryName(categoryName);
newCategory.setParentCategoryId(parentCategoryId);

if (action=="add") {
categoryDAO.addCategory(newCategory);
} else if ("edit".equals(action)) {
int categoryId = Integer.parseInt(request.getParameter("categoryId"));
newCategory.setCategoryId(categoryId);
categoryDAO.updateCategory(newCategory);
}
}

response.sendRedirect("CategoryServlet");
}
}

ProductServlet.java :package

servlets;

import dao.ProductDAO;
import Conn.Product;

import javax.servlet.ServletException; import


javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;
import java.io.IOException; import
java.util.List;

@WebServlet("/ProductServlet") public class


ProductServlet extends HttpServlet { private
static final long serialVersionUID = 1L; private
ProductDAO productDAO;
public void init() {
productDAO = new ProductDAO();
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException { String action =
request.getParameter("action");

if (action != null) {
switch (action) {
case "add":
// Show add product form
request.getRequestDispatcher("addProduct.jsp").forward(request,
response);
break;
case "edit":
// Show edit product form int productId =
Integer.parseInt(request.getParameter("id")); Product
product = productDAO.getProductById(productId);
request.setAttribute("product", product);
request.getRequestDispatcher("editProduct.jsp").forward(request,
response);
break;
case "delete":
// Perform delete product operation
int deleteProductId = Integer.parseInt(request.getParameter("id"));
productDAO.deleteProduct(deleteProductId);
response.sendRedirect("ProductServlet");
break; default: break;
}
} else {
// Display the list of products
List<Product> products = productDAO.getAllProducts();
request.setAttribute("products", products);
request.getRequestDispatcher("product.jsp").forward(request, response);
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException { // Handle add/update
product form submission
String action = request.getParameter("action");
if ("add".equals(action) || "edit".equals(action)) {
String productName = request.getParameter("productName");
double price = Double.parseDouble(request.getParameter("price"));
String unit = request.getParameter("unit");
double discount = Double.parseDouble(request.getParameter("discount"));
String image = request.getParameter("image");
int categoryId = Integer.parseInt(request.getParameter("categoryId"));
int stock = Integer.parseInt(request.getParameter("stock"));
Product newProduct = new Product();
newProduct.setProductName(productName);
newProduct.setPrice(price);
newProduct.setUnit(unit);
newProduct.setDiscount(discount);
newProduct.setImage(image);
newProduct.setCategoryId(categoryId);
newProduct.setStock(stock);

if ("add".equals(action)) {
productDAO.addProduct(newProduct);
} else if ("edit".equals(action)) {
int productId = Integer.parseInt(request.getParameter("productId"));
newProduct.setProductId(productId);
productDAO.updateProduct(newProduct);
}
}

response.sendRedirect("ProductServlet");
}
}
Output :-

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