0% found this document useful (0 votes)
58 views59 pages

Library Management System

Uploaded by

nileshsonzari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views59 pages

Library Management System

Uploaded by

nileshsonzari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 59

LIBRARY MANAGEMENT

SYSTEM

Project Title: Library Management System

Technology Used: Java, JSP/Servlet, MySQL

Submitted by: Nilesh Anil Sonzari

Year: 2025
ABSTRACT

The Library Management System (LMS) is designed to


automate and simplify the process of managing a library. It
helps librarians in cataloguing books, maintaining records of
issued/returned books, calculating fines, and managing
student/user details. The system reduces manual work,
increases efficiency, and provides quick access to information
about books and users.

This project eliminates the traditional paper-based record-


keeping process by shifting to a computerized system that
ensures accuracy and consistency. The automation of issuing,
returning, and searching for books reduces errors, saves time,
and provides a user-friendly interface for both librarians and
students. The digital storage of records also minimizes the
chances of data loss and makes it easier to generate reports
and statistics whenever required.

Additionally, the system enhances accessibility by allowing


users to quickly search for books based on title, author, or
subject. With proper authentication and role management, it
ensures data security and prevents unauthorized access. By
offering an efficient way of managing resources, the Library
Management System not only improves day-to-day operations
but also supports the long-term growth of educational
institutions.
INTRODUCTION
Libraries play an essential role in knowledge sharing, but
manual management often leads to inefficiency and errors. This
project aims to computerize library operations such as
managing books, issuing and returning them, and maintaining
user details. By automating these tasks, the system reduces
paperwork and enhances productivity.

The Library Management System provides separate


functionalities for administrators (librarians) and users
(students/teachers). Administrators can manage books, update
user records, and track transactions, while users can search for
books, borrow, and return them. The system ensures that both
parties can interact with the library database seamlessly and
efficiently.

In today’s digital world, speed and accuracy are critical. A


manual library system struggles to provide real-time
information about book availability and transaction history,
which can cause inconvenience for users. The Library
Management System bridges this gap by instantly updating
records whenever a transaction occurs, ensuring that the
information is always accurate and up to date.
Furthermore, the system is scalable and adaptable for different
institutions—ranging from schools and colleges to larger
academic and public libraries. With the possibility of future
enhancements such as barcode scanning, RFID integration, or
online access, the system provides a solid foundation for
modern, technology-driven library management.

Problem Statement

Traditional library management relies heavily on manual record-


keeping, which is time-consuming and prone to human errors.
Librarians often face challenges in maintaining accurate records
of book transactions, including issuing, returning, and tracking
overdue books. Searching for a specific book or verifying its
availability can take a considerable amount of time, especially
in larger libraries with thousands of books.

Another problem arises in calculating fines for overdue books


and maintaining transaction history, which, when done
manually, may result in inconsistencies or data loss. Security is
also a concern, as unauthorized access to records may lead to
misuse of resources. These limitations not only affect the
efficiency of library staff but also create inconvenience for
students and faculty who depend on timely access to
resources.

Proposed Solution
The Library Management System (LMS) addresses these issues
by automating core library functions. By using a centralized
database, the system ensures that records of books, users, and
transactions are accurate, consistent, and easily retrievable.
Librarians can quickly update book inventories, register new
users, and track issued/returned books without relying on
physical records.

The proposed solution also incorporates a fine calculation


feature that automatically determines penalties for overdue
books, thereby reducing errors and saving time. With role-
based authentication, only authorized personnel can modify
records, ensuring data security. The system’s search
functionality provides instant results based on book title,
author, or subject, significantly improving user experience. In
the long term, the LMS can be extended with advanced
features such as online book reservations, barcode/RFID-based
tracking, and mobile app integration, making it a
comprehensive and future-ready solution.
Objectives

Objectives
The primary objectives of the Library Management System are:
1. Efficient Book Management – To maintain accurate and
up-to-date records of all books in the library, including
details such as title, author, publisher, and availability.
2. User-Friendly Transactions – To simplify the process of
issuing, renewing, and returning books for both librarians
and students, ensuring that transactions are quick and
error-free.
3. Automated Fine Calculation – To automatically
calculate and track fines for overdue books, reducing
manual work and avoiding discrepancies.
4. Centralized Database – To store all library-related data
in a single database, ensuring consistency, reliability, and
easy access to records.
5. Secure Access – To provide role-based authentication so
that only authorized users (e.g., librarian/admin) can
manage books and user records, while students can only
perform allowed actions like searching and borrowing.
6. Report Generation – To generate reports such as
available books, issued books, overdue books, and fine
details, which help in better decision-making and
administration.
7. Time and Cost Efficiency – To minimize paperwork,
reduce human errors, and save time for both librarians
and students.
Scope of the Project

The Library Management System (LMS) is designed to cover the


core operations of a library, including book management, user
management, and transaction handling. The system is built to
be flexible enough to handle the requirements of schools,
colleges, universities, and small to medium-sized public
libraries.

 Book Management – Adding, updating, deleting, and


searching for books.

 User Management – Registering and maintaining details


of students, faculty, and other library users.

 Transactions – Issuing, renewing, and returning books,


with real-time updates to availability status.

 Fine Calculation – Automatic calculation of overdue fines


and updating user accounts.

 Reports – Generating reports on available books,


issued/returned books, overdue books, and fines.

 Security – Role-based authentication (e.g., admin/librarian


vs. student) to ensure secure access.

 Search Functionality – Fast and efficient search for books


based on title, author, subject, or ID.

Modules
The Library Management System is divided into several key
modules that work together to provide complete functionality:

1. Login & Authentication Module

 Provides secure access to the system.

 Different login roles: Admin/Librarian and Student/Faculty.

 Ensures unauthorized users cannot access restricted


features.

2. Book Management Module

 Allows librarian to add, update, delete, and search books.

 Maintains details such as Book ID, Title, Author, Publisher,


and Availability.

 Updates availability status automatically when a book is


issued or returned.

3. User Management Module

 Used by the librarian to register new users (students,


teachers, staff).

 Stores user details such as User ID, Name, Email, Type,


and Password.

 Provides option to update or remove user records.

4. Transaction Module (Issue & Return)


 Handles issuing, renewing, and returning of books.

 Records details of each transaction including User ID, Book


ID, Issue Date, Return Date.

 Automatically updates the book’s availability status in the


database.

5. Fine Management Module

 Calculates fines for overdue books based on return dates.

 Updates user account with fine details.

 Generates reports of unpaid fines for follow-up.

6. Report Generation Module

 Generates various reports such as:

o List of available books.

o List of issued books.

o List of overdue books.

o Fine reports (user-wise and book-wise).

 Helps the librarian in making administrative


decisions.
System Requirements

1. Hardware Requirements

The minimum and recommended hardware


specifications for running the Hotel Management
System are as follows:

 Processor: Intel Core i3 or higher (minimum), Intel


Core i5/i7 (recommended)

 RAM: 4 GB (minimum), 8 GB or more


(recommended)

 Hard Disk: 250 GB free space (minimum), 500 GB


or more (recommended)

 Monitor: 15-inch color monitor with 1024x768


resolution or higher

 Input Devices: Standard keyboard and mouse

 Output Devices: Printer (for bills, invoices, and


reports)
2. Software Requirements

The software environment needed to develop and run the


system includes:

 Operating System: Windows 10/11, Linux, or macOS

 Front-End: Java (Swing/JavaFX) or JSP/Servlets (for web


version)

 Back-End: MySQL / SQL Server / Oracle (for database


management)

 Server (if web-based): Apache Tomcat / GlassFish

 Development Tools: Eclipse IDE / NetBeans / IntelliJ IDEA

 Languages Used: Java (core + JDBC), HTML, CSS,


JavaScript (if web-based)

 Other Software:

o JDK 21 (latest stable Java Development Kit)

o XAMPP/WAMP (optional, if using MySQL with


PHPMyAdmin)

o Report generation tools (JasperReports or iText for


PDF bills)
. Implementation

The implementation of the Library Management System


involves developing different modules and integrating them
with a centralized database. The project is implemented using
Java (for backend logic) and MySQL (for data storage), with
JDBC as the connector between the application and the
database.

1. Environment Setup

 Programming Language: Java (JDK 8 or above)

 Database: MySQL 8.0

 Server (if JSP/Servlet used): Apache Tomcat

 IDE Used: Eclipse / NetBeans

 Libraries/Drivers: MySQL Connector (JDBC Driver)

2. Database Implementation

 A relational database is designed to store Books,


Users, and Transactions.

 Tables created:

o books (book_id, title, author, publisher,


available)
o users (user_id, name, email, type, password)

o transactions (trans_id, user_id, book_id,


issue_date, return_date, fine)

SQL Example:

CREATE TABLE books (

book_id INT PRIMARY KEY,

title VARCHAR(100),

author VARCHAR(100),

publisher VARCHAR(100),

available BOOLEAN

);

CREATE TABLE users (

user_id INT PRIMARY KEY,

name VARCHAR(100),

email VARCHAR(100),

type VARCHAR(50),

password VARCHAR(50)

);

CREATE TABLE transactions (


trans_id INT PRIMARY KEY AUTO_INCREMENT,

user_id INT,

book_id INT,

issue_date DATE,

return_date DATE,

fine DECIMAL(5,2),

FOREIGN KEY (user_id) REFERENCES users(user_id),

FOREIGN KEY (book_id) REFERENCES books(book_id)

);

10. Advantages

The Library Management System provides several benefits


compared to traditional manual systems:

1. Time-Saving – Automates routine tasks such as searching


books, issuing, and returning, reducing the workload of
librarians and saving time for users.

2. Accuracy – Eliminates human errors in record-keeping,


ensuring that book transactions, availability, and fines are
always updated correctly.

3. Easy Accessibility – Users can quickly search for books by


title, author, or subject without manually checking shelves
or registers.
4. Centralized Database – Stores all book, user, and
transaction records in one place, ensuring consistency and
reliability of data.

5. Efficient Fine Management – Automatically calculates fines


for overdue books, reducing disputes and manual errors.

6. Security – Role-based authentication prevents


unauthorized access, protecting sensitive data such as
user records and transaction history.

11. Limitations

While the Library Management System provides many benefits,


it also has some limitations in its current version:

1. Single-Library Support – The system is designed for


managing only one library database; it does not support
networking across multiple branches.

2. No Mobile Application – Users cannot access the system


via smartphones or tablets unless a separate mobile app
is developed.

3. Limited to Physical Books – The system currently handles


only physical books; e-books, journals, and digital
resources are not integrated.

4. No Barcode/RFID Integration – Book issue and return


operations must be done manually by entering IDs;
barcode or RFID scanning is not implemented.
5. Basic Security – Passwords are stored as plain text in the
database (in a basic implementation). Advanced
encryption and multi-factor authentication are not
included.

6. Limited User Roles – The system distinguishes mainly


between admin (librarian) and student roles;

12. Future Enhancements

The Library Management System can be further improved and


enhanced in the following ways:

1. Barcode/RFID Integration – Automating the issue and


return process using barcode scanners or RFID tags for
faster and more accurate transactions.

2. Mobile Application – Developing a mobile app for Android


and iOS so that users can search books, reserve them, and
check their transaction history on the go.

3. E-Book Management – Extending the system to handle e-


books, digital journals, and online resources, allowing
users to borrow and read digital content.

4. Online Reservation & Renewal – Providing students and


faculty with the ability to reserve books online and renew
borrowed books without visiting the library physically.

5. Automated Notifications – Sending SMS or email alerts for


book due dates, overdue fines, and reservation
confirmations.
6. Cloud-Based Database – Migrating the system to a cloud
platform for better scalability, accessibility, and data
backup.

7. Advanced Security Features – Adding encrypted password


storage, multi-factor authentication, and role-based
permissions for different types of staff and users.

8. Analytics & Reporting – Generating advanced reports such


as book demand trends, most borrowed books, and user
activity analysis to help librarians improve resource
management.

9. Multi-Library Networking – Enabling integration of multiple


libraries under one system, allowing resource sharing and
inter-library borrowing.

10. AI-Based Search and Recommendations –


Implementing intelligent search and recommendation
systems that suggest books based on user interests and
borrowing history.

13. Conclusion

The Library Management System is an efficient solution for


automating and managing the daily operations of a library. By
computerizing processes such as book management, user
registration, and transaction handling, the system reduces
manual effort, minimizes errors, and ensures accurate record-
keeping. It provides quick access to information, improves time
management, and enhances the overall productivity of both
librarians and users.

This project successfully addresses the key challenges of


traditional library management, including manual record
maintenance, time-consuming searches, and error-prone fine
calculations. With features like secure login, centralized data
storage, automated fine calculation, and report generation, it
ensures smooth functioning of library services.

Although the system has some limitations, it provides a strong


foundation for future development. With enhancements such as
barcode/RFID integration, mobile app support, e-book
management, and cloud-based scalability, the Library
Management System can evolve into a modern, smart, and
comprehensive platform suitable for all types of libraries.
1. Data Flow Diagram (DFD)

Data Flow Diagram for Library Management System

Level 0 DFD (Context Diagram)

Shows the overall system as a single process with


external entities.

External Entities:

 User (Student/Faculty)

 Librarian (Admin)

Process:

 Library Management System

Data Stores:

 Database

Data Flows:

 User requests login → System verifies with database


→ Access granted.

 Librarian updates books → System stores in


database.

 User searches/borrows/returns → System updates


transactions in database.

 System generates reports → Sent to librarian.

Level 1 DFD

Breaks the main process into subsystems.


1. Login & Authentication

o User enters credentials.

o System verifies with Users table.

2. Book Management

o Librarian adds/updates/deletes books.

o System stores data in Books table.

3. User Management

o Admin registers students/faculty.

o System stores in Users table.

4. Transaction Management

o Issue book → Update Transactions table.

o Return book → Calculate fine → Update


Transactions.

5. Report Generation

o System generates daily/weekly/monthly reports


for admin.

Level 2 DFD (Detailed View of Transactions)

Transaction Process → Sub-processes:

 Issue Book

o Check availability in Books table.


o If available → Update issue date in
Transactions.

o Update book status to “Issued.”

 Return Book

o User submits book.

o System calculates fine (if overdue).

o Update Transactions with return date.

o Update Books table → Available.

Level 1 DFD structure:

Customer ---> [Login/Register] ---> (Users DB)

Customer ---> [Browse Products] ---> (Products DB)

Customer ---> [Add to Cart] ---> (Cart DB)

Customer ---> [Checkout] ---> (Orders DB)

Customer ---> [View Orders] ---> (Orders DB)

Admin ---> [Manage Products] ---> (Products DB)

Admin ---> [Manage Orders] ---> (Orders DB)


ERD for Library Management System

Entities & Attributes

1. User

o UserID (PK)

o Name

o Email

o Password

o Role (Student/Faculty/Admin)

2. Book

o BookID (PK)

o Title

o Author

o Publisher

o Category

o Availability (Yes/No)

3. Transaction

o TransID (PK)

o UserID (FK → User)

o BookID (FK → Book)

o IssueDate

o DueDate

o ReturnDate
o Fine

4. Admin (optional, if separated)

o AdminID (PK)

o Name

o Email

o Password

Relationships

 User ↔ Transaction:

o One user can have many transactions.

o (1:N relationship)

 Book ↔ Transaction:

o One book can be involved in many transactions.

o (1:N relationship)

 User ↔ Book (via Transaction):

o Many-to-Many (because multiple users can borrow


multiple books).
Login & Authentication Module (Java + JDBC)
import java.sql.*;

import java.util.Scanner;

public class LoginModule {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter Email: ");

String email = sc.nextLine();

System.out.print("Enter Password: ");

String password = sc.nextLine();

try {

// Database connection

Connection con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/librarydb", "root",
"yourpassword");

String query = "SELECT * FROM users WHERE email=?


AND password=?";

PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, email);

ps.setString(2, password);

ResultSet rs = ps.executeQuery();

if (rs.next()) {

System.out.println("✅ Login Successful! Welcome, " +


rs.getString("name"));

} else {

System.out.println("❌ Invalid Credentials!");

con.close();

} catch (Exception e) {

e.printStackTrace();

sc.close();

📌 2. Book Management Module (Add, View Books)

import java.sql.*;
import java.util.Scanner;

public class BookManagement {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

try {

Connection con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/librarydb", "root",
"yourpassword");

System.out.println("1. Add Book\n2. View Books");

int choice = sc.nextInt();

sc.nextLine();

if (choice == 1) {

System.out.print("Enter Title: ");

String title = sc.nextLine();

System.out.print("Enter Author: ");

String author = sc.nextLine();

System.out.print("Enter Publisher: ");

String publisher = sc.nextLine();


String query = "INSERT INTO books (title, author,
publisher, availability) VALUES (?,?,?,?)";

PreparedStatement ps =
con.prepareStatement(query);

ps.setString(1, title);

ps.setString(2, author);

ps.setString(3, publisher);

ps.setString(4, "Yes");

ps.executeUpdate();

System.out.println("✅ Book Added Successfully!");

else if (choice == 2) {

Statement st = con.createStatement();

ResultSet rs = st.executeQuery("SELECT * FROM


books");

while (rs.next()) {

System.out.println(rs.getInt("bookid") + " | " +

rs.getString("title") + " | " +

rs.getString("author") + " | " +


rs.getString("publisher") + " | " +

rs.getString("availability"));

con.close();

} catch (Exception e) {

e.printStackTrace();

sc.close();

📌 3. Transaction Module (Issue & Return Book)

import java.sql.*;

import java.util.Scanner;

public class TransactionModule {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

try {
Connection con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/librarydb", "root",
"yourpassword");

System.out.println("1. Issue Book\n2. Return Book");

int choice = sc.nextInt();

sc.nextLine();

if (choice == 1) {

System.out.print("Enter UserID: ");

int userId = sc.nextInt();

System.out.print("Enter BookID: ");

int bookId = sc.nextInt();

// Check availability

PreparedStatement check =
con.prepareStatement("SELECT availability FROM books WHERE
bookid=?");

check.setInt(1, bookId);

ResultSet rs = check.executeQuery();
if (rs.next() &&
rs.getString("availability").equals("Yes")) {

PreparedStatement ps = con.prepareStatement(

"INSERT INTO transactions (userid, bookid,


issuedate, duedate) VALUES (?,?,NOW(), DATE_ADD(NOW(),
INTERVAL 7 DAY))");

ps.setInt(1, userId);

ps.setInt(2, bookId);

ps.executeUpdate();

PreparedStatement update =
con.prepareStatement("UPDATE books SET availability='No'
WHERE bookid=?");

update.setInt(1, bookId);

update.executeUpdate();

System.out.println("✅ Book Issued Successfully!");

} else {

System.out.println("❌ Book not available!");

else if (choice == 2) {

System.out.print("Enter TransactionID: ");


int transId = sc.nextInt();

PreparedStatement ps = con.prepareStatement(

"UPDATE transactions SET returndate=NOW()


WHERE transid=?");

ps.setInt(1, transId);

ps.executeUpdate();

// Free the book again

PreparedStatement getBook =
con.prepareStatement("SELECT bookid FROM transactions
WHERE transid=?");

getBook.setInt(1, transId);

ResultSet rs = getBook.executeQuery();

if (rs.next()) {

int bookId = rs.getInt("bookid");

PreparedStatement update =
con.prepareStatement("UPDATE books SET availability='Yes'
WHERE bookid=?");

update.setInt(1, bookId);

update.executeUpdate();

}
System.out.println("✅ Book Returned Successfully!");

con.close();

} catch (Exception e) {

e.printStackTrace();

sc.close();

📌 Database Tables (MySQL)

Run these first in MySQL:

CREATE DATABASE librarydb;

USE librarydb;

CREATE TABLE users (

userid INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(50),

email VARCHAR(50) UNIQUE,

password VARCHAR(50),

role VARCHAR(20)
);

CREATE TABLE books (

bookid INT AUTO_INCREMENT PRIMARY KEY,

title VARCHAR(100),

author VARCHAR(100),

publisher VARCHAR(100),

availability VARCHAR(10)

);

CREATE TABLE transactions (

transid INT AUTO_INCREMENT PRIMARY KEY,

userid INT,

bookid INT,

issuedate DATE,

duedate DATE,

returndate DATE,

fine DECIMAL(10,2),

FOREIGN KEY (userid) REFERENCES users(userid),

FOREIGN KEY (bookid) REFERENCES books(bookid)

);
Source code

User Registration & Login Module

Registration Servlet (RegisterServlet.java)

import jakarta.servlet.*;

import jakarta.servlet.http.*;

import java.io.*;

import java.sql.*;

public class RegisterServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,


HttpServletResponse response)

throws ServletException, IOException {

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

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

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

try {

Connection con = DBConnect.getConnection();

PreparedStatement ps = con.prepareStatement(

"INSERT INTO users(name, email, password, role)


VALUES (?, ?, ?, 'customer')");
ps.setString(1, name);

ps.setString(2, email);

ps.setString(3, password);

int i = ps.executeUpdate();

if (i > 0) {

response.sendRedirect("login.jsp?msg=Registered
Successfully");

} else {

response.sendRedirect("register.jsp?error=Try
Again");

} catch (Exception e) {

e.printStackTrace();

Login Servlet (LoginServlet.java)

import jakarta.servlet.*;

import jakarta.servlet.http.*;

import java.io.*;
import java.sql.*;

public class LoginServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,


HttpServletResponse response)

throws ServletException, IOException {

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

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

try {

Connection con = DBConnect.getConnection();

PreparedStatement ps = con.prepareStatement(

"SELECT * FROM users WHERE email=? AND


password=?");

ps.setString(1, email);

ps.setString(2, password);

ResultSet rs = ps.executeQuery();

if (rs.next()) {

HttpSession session = request.getSession();

session.setAttribute("user_id", rs.getInt("user_id"));
session.setAttribute("user_name",
rs.getString("name"));

response.sendRedirect("home.jsp");

} else {

response.sendRedirect("login.jsp?error=Invalid
Credentials");

} catch (Exception e) {

e.printStackTrace();

✅ 2. Product Management Module (Admin)

Add Product Servlet (AddProductServlet.java)

import jakarta.servlet.*;

import jakarta.servlet.http.*;

import java.io.*;

import java.sql.*;

public class AddProductServlet extends HttpServlet {


protected void doPost(HttpServletRequest request,
HttpServletResponse response)

throws ServletException, IOException {

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

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

double price =
Double.parseDouble(request.getParameter("price"));

int stock =
Integer.parseInt(request.getParameter("stock"));

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

try {

Connection con = DBConnect.getConnection();

PreparedStatement ps = con.prepareStatement(

"INSERT INTO products(name, description, price,


stock, category) VALUES (?, ?, ?, ?, ?)");

ps.setString(1, name);

ps.setString(2, description);

ps.setDouble(3, price);

ps.setInt(4, stock);

ps.setString(5, category);
int i = ps.executeUpdate();

if (i > 0) {

response.sendRedirect("admin_products.jsp?
msg=Product Added");

} else {

response.sendRedirect("admin_products.jsp?
error=Failed");

} catch (Exception e) {

e.printStackTrace();

Display Products (products.jsp)

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

<%@ page import="DBConnect" %>

<html>

<head><title>Products</title></head>

<body>

<h2>Available Products</h2>
<table border="1">

<tr><th>ID</th><th>Name</th><th>Price</
th><th>Action</th></tr>

<%

Connection con = DBConnect.getConnection();

Statement st = con.createStatement();

ResultSet rs = st.executeQuery("SELECT * FROM products");

while(rs.next()){

%>

<tr>

<td><%=rs.getInt("product_id")%></td>

<td><%=rs.getString("name")%></td>

<td><%=rs.getDouble("price")%></td>

<td><a href="AddToCartServlet?id=<
%=rs.getInt("product_id")%>">Add to Cart</a></td>

</tr>

<% } %>

</table>

</body>

</html>
✅ 3. Shopping Cart & Order Module

Add to Cart Servlet (AddToCartServlet.java)

import jakarta.servlet.*;

import jakarta.servlet.http.*;

import java.io.*;

import java.sql.*;

public class AddToCartServlet extends HttpServlet {

protected void doGet(HttpServletRequest request,


HttpServletResponse response)

throws ServletException, IOException {

HttpSession session = request.getSession();

int userId = (int) session.getAttribute("user_id");

int productId =
Integer.parseInt(request.getParameter("id"));

try {

Connection con = DBConnect.getConnection();

// Check if product already in cart

PreparedStatement check = con.prepareStatement(


"SELECT * FROM cart WHERE user_id=? AND
product_id=?");

check.setInt(1, userId);

check.setInt(2, productId);

ResultSet rs = check.executeQuery();

if (rs.next()) {

// Update quantity

PreparedStatement update = con.prepareStatement(

"UPDATE cart SET quantity=quantity+1 WHERE


user_id=? AND product_id=?");

update.setInt(1, userId);

update.setInt(2, productId);

update.executeUpdate();

} else {

// Insert new item

PreparedStatement ps = con.prepareStatement(

"INSERT INTO cart(user_id, product_id, quantity)


VALUES (?, ?, 1)");

ps.setInt(1, userId);

ps.setInt(2, productId);

ps.executeUpdate();
}

response.sendRedirect("cart.jsp");

} catch (Exception e) {

e.printStackTrace();

Checkout Servlet (CheckoutServlet.java)

import jakarta.servlet.*;

import jakarta.servlet.http.*;

import java.io.*;

import java.sql.*;

import java.util.*;

public class CheckoutServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,


HttpServletResponse response)

throws ServletException, IOException {

HttpSession session = request.getSession();

int userId = (int) session.getAttribute("user_id");


try {

Connection con = DBConnect.getConnection();

Statement st = con.createStatement();

ResultSet rs = st.executeQuery("SELECT * FROM cart


WHERE user_id=" + userId);

double total = 0;

// Calculate total

while (rs.next()) {

int productId = rs.getInt("product_id");

int qty = rs.getInt("quantity");

PreparedStatement ps =
con.prepareStatement("SELECT price FROM products WHERE
product_id=?");

ps.setInt(1, productId);

ResultSet pr = ps.executeQuery();

if (pr.next()) {

total += pr.getDouble("price") * qty;

}
// Insert into orders

PreparedStatement orderPs = con.prepareStatement(

"INSERT INTO orders(user_id, total_amount,


order_date, status) VALUES (?, ?, NOW(), 'Placed')",

Statement.RETURN_GENERATED_KEYS);

orderPs.setInt(1, userId);

orderPs.setDouble(2, total);

orderPs.executeUpdate();

ResultSet keys = orderPs.getGeneratedKeys();

int orderId = 0;

if (keys.next()) {

orderId = keys.getInt(1);

// Insert order items

rs = st.executeQuery("SELECT * FROM cart WHERE


user_id=" + userId);

while (rs.next()) {

int productId = rs.getInt("product_id");

int qty = rs.getInt("quantity");


PreparedStatement pr =
con.prepareStatement("SELECT price FROM products WHERE
product_id=?");

pr.setInt(1, productId);

ResultSet priceRs = pr.executeQuery();

double price = 0;

if (priceRs.next()) {

price = priceRs.getDouble("price");

PreparedStatement oi = con.prepareStatement(

"INSERT INTO order_items(order_id, product_id,


quantity, price) VALUES (?, ?, ?, ?)");

oi.setInt(1, orderId);

oi.setInt(2, productId);

oi.setInt(3, qty);

oi.setDouble(4, price);

oi.executeUpdate();

// Clear cart
PreparedStatement clear =
con.prepareStatement("DELETE FROM cart WHERE user_id=?");

clear.setInt(1, userId);

clear.executeUpdate();

response.sendRedirect("orders.jsp?msg=Order Placed
Successfully");

} catch (Exception e) {

e.printStackTrace();

Frontend

1. register.jsp

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


charset=UTF-8" %>

<!DOCTYPE html>

<html>

<head>
<title>Register - E-Commerce</title>

<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/boo
tstrap.min.css">

</head>

<body class="bg-light">

<div class="container mt-5">

<div class="card shadow-lg col-md-6 mx-auto">

<div class="card-body">

<h3 class="text-center text-primary">User


Registration</h3>

<form action="RegisterServlet" method="post">

<div class="mb-3">

<label>Name</label>

<input type="text" name="name" class="form-


control" required>

</div>

<div class="mb-3">

<label>Email</label>

<input type="email" name="email" class="form-


control" required>

</div>

<div class="mb-3">
<label>Password</label>

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


class="form-control" required>

</div>

<button type="submit" class="btn btn-success w-


100">Register</button>

</form>

<p class="mt-3 text-center">Already have an account?

<a href="login.jsp">Login</a>

</p>

</div>

</div>

</div>

</body>

</html>

✅ 2. login.jsp

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


charset=UTF-8" %>

<!DOCTYPE html>

<html>

<head>
<title>Login - E-Commerce</title>

<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/boo
tstrap.min.css">

</head>

<body class="bg-light">

<div class="container mt-5">

<div class="card shadow-lg col-md-5 mx-auto">

<div class="card-body">

<h3 class="text-center text-primary">Login</h3>

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

<div class="mb-3">

<label>Email</label>

<input type="email" name="email" class="form-


control" required>

</div>

<div class="mb-3">

<label>Password</label>

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


class="form-control" required>

</div>

<button type="submit" class="btn btn-primary w-


100">Login</button>
</form>

<p class="mt-3 text-center">Don't have an account?

<a href="register.jsp">Register</a>

</p>

</div>

</div>

</div>

</body>

</html>

✅ 3. cart.jsp

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

<%@ page import="DBConnect" %>

<%@ page session="true" %>

<!DOCTYPE html>

<html>

<head>

<title>My Cart - E-Commerce</title>

<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/boo
tstrap.min.css">

</head>
<body class="bg-light">

<div class="container mt-5">

<h2 class="text-center text-success">My Shopping


Cart</h2>

<table class="table table-bordered shadow">

<thead class="table-dark">

<tr>

<th>Product</th><th>Quantity</th><th>Price</th><th>Tot
al</th><th>Action</th>

</tr>

</thead>

<tbody>

<%

int userId = (int) session.getAttribute("user_id");

Connection con = DBConnect.getConnection();

PreparedStatement ps = con.prepareStatement(

"SELECT c.cart_id, p.name, c.quantity, p.price FROM


cart c JOIN products p ON c.product_id=p.product_id WHERE
c.user_id=?");

ps.setInt(1, userId);

ResultSet rs = ps.executeQuery();

double grandTotal = 0;
while (rs.next()) {

double total = rs.getInt("quantity") *


rs.getDouble("price");

grandTotal += total;

%>

<tr>

<td><%= rs.getString("name") %></td>

<td><%= rs.getInt("quantity") %></td>

<td>₹<%= rs.getDouble("price") %></td>

<td>₹<%= total %></td>

<td><a href="RemoveFromCartServlet?id=<
%=rs.getInt("cart_id")%>" class="btn btn-danger btn-
sm">Remove</a></td>

</tr>

<% } %>

</tbody>

</table>

<h4 class="text-end">Grand Total: ₹<%= grandTotal


%></h4>

<form action="CheckoutServlet" method="post"


class="text-end">

<button type="submit" class="btn btn-success">Proceed


to Checkout</button>
</form>

</div>

</body>

</html>

✅ 4. orders.jsp

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

<%@ page import="DBConnect" %>

<%@ page session="true" %>

<!DOCTYPE html>

<html>

<head>

<title>My Orders - E-Commerce</title>

<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/boo
tstrap.min.css">

</head>

<body class="bg-light">

<div class="container mt-5">

<h2 class="text-center text-primary">My Orders</h2>

<table class="table table-striped shadow">

<thead class="table-dark">
<tr>

<th>Order
ID</th><th>Date</th><th>Total</th><th>Status</th>

</tr>

</thead>

<tbody>

<%

int userId = (int) session.getAttribute("user_id");

Connection con = DBConnect.getConnection();

PreparedStatement ps =
con.prepareStatement("SELECT * FROM orders WHERE
user_id=?");

ps.setInt(1, userId);

ResultSet rs = ps.executeQuery();

while (rs.next()) {

%>

<tr>

<td><%= rs.getInt("order_id") %></td>

<td><%= rs.getDate("order_date") %></td>

<td>₹<%= rs.getDouble("total_amount") %></td>

<td><span class="badge bg-success"><%=


rs.getString("status") %></span></td>
</tr>

<% } %>

</tbody>

</table>

</div>

</body>

</html>

You might also like