Online Shopping System in Java using JSPs & Servlets

Free Java courses with 37 real-time projects - Learn Java

The Online Shopping System has become an essential tool for sellers and also for buyers. The online shopping system in java allows buyers to buy goods/products directly from the seller website and it saves time and money of buyer. There is an advantage of the sellers to attract more customers using online shopping systems and it promotes cashless transactions.

About Online Shopping Project:

We will develop following functionalities in online shopping java project:

  • Seller/Admin can add the product.
  • Seller/Admin can edit the product.
  • Seller/Admin can delete the product.
  • Seller/Admin can view the product.
  • Seller/Admin can view the customers.
  • Seller/Admin can view all orders.
  • Seller/Admin can view pending orders.
  • Seller/Admin have a dashboard to check the number of orders, customers, products.
  • Seller/Admin have basic login and logout functionality.
  • Buyer/Customer have basic login, register and logout functionality.
  • Buyer/Customer can view the products.
  • Buyer/Customer can add the product into the cart.
  • Buyer/Customer can remove the product from the cart.
  • Buyer/Customer can change the quantity of products in the cart.
  • Buyer/Customer can order the product.
  • Buyer/Customer can view all product ordered history.

Project Prerequisites:

  • IDE Used: NetBeans 8.2. (you can also use Eclipse)
  • Java should be installed on the machine.
  • Database Used: MySQL 5.5.
  • To build an online shopping system using java we require basic knowledge of java and also knowledge of the MySQL databases.
  • Java provides the Servlet package for handling http requests and responses. Also, we need two more libraries such as Mysql-JDBC-connector and apache-commons-fileupload.

Download Online Shopping Project Java Code

Please download the java source code of online shopping project: Online Shopping System Java Project Code

Steps to Create Online Shopping Project in Java

These are the step to build Online Shopping System using java:

1) Creating Database
2) Importing packages
3) System files structure
4) Functions used
5) Connection to database
6) Defining new customer registering servlet
7) Defining customer login servlet
8) Defining admin login servlet
9) Defining servlet for adding product in the database
10) Defining add to cart servlet
11) Defining servlet for customer to update product quantity in the cart
12) Defining servlet for admin to get current products status

1) Creating Database (MYSQL):

In this step, we basically create java online shopping system database.

And also we create five tables:

a) Admin table for storing information such as username, password, name and admin table is used for login purposes.
b) Cart table for storing information about the cart such as customer_id, quantity, product_id, etc.
c) Customer table for storing information such as username, password, name and customer table is used for login purposes.
d) Order table for storing information the customer has ordered the product from the website such as custiomer_id, product_id, payment_id, customer name, product name, total amount, quantity, address, etc.
e) Product table for storing information about the product such as product_name, id, image, price, mrp price, category, etc.

1) ADMIN TABLE: (tbladmin)

CREATE TABLE `tbladmin` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `added_date` datetime NOT NULL,
 `email` varchar(100) NOT NULL,
 `password` varchar(100) NOT NULL,
 `name` varchar(100) NOT NULL,
 PRIMARY KEY (`id`)
) ;

2) CART TABLE: (tblcart)

CREATE TABLE `tblcart` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `discount_price` varchar(200) DEFAULT NULL,
 `quantity` int(11) NOT NULL,
 `total_price` varchar(200) DEFAULT NULL,
 `customer_id` bigint(20) NOT NULL,
 `product_id` bigint(20) NOT NULL,
 `mrp_price` varchar(200) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ;

3) CUSTOMER TABLE: (tblcustomer):

CREATE TABLE `tblcustomer` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `address` varchar(255) NOT NULL,
 `added_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `email` varchar(100) NOT NULL,
 `gender` varchar(6) NOT NULL,
 `name` varchar(50) NOT NULL,
 `password` varchar(60) NOT NULL,
 `phone` varchar(200) NOT NULL,
 `pin_code` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
) ;

4) ORDERS TABLE: (tblorders)

CREATE TABLE `tblorders` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `order_no` int(11) DEFAULT NULL,
 `customer_name` varchar(200) DEFAULT NULL,
 `mobile_number` varchar(100) DEFAULT NULL,
 `email_id` varchar(100) DEFAULT NULL,
 `address` varchar(400) DEFAULT NULL,
 `address_type` varchar(100) DEFAULT NULL,
 `pincode` varchar(100) DEFAULT NULL,
 `image` varchar(200) DEFAULT NULL,
 `product_name` varchar(400) DEFAULT NULL,
 `quantity` int(11) DEFAULT NULL,
 `product_price` varchar(100) DEFAULT NULL,
 `product_selling_price` varchar(100) DEFAULT NULL,
 `product_total_price` varchar(100) DEFAULT NULL,
 `order_status` varchar(100) DEFAULT NULL,
 `order_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `payment_mode` varchar(100) DEFAULT NULL,
 `payment_id` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ;

5) PRODUCT TABLE: (tblproduct)

CREATE TABLE `tblproduct` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `active` varchar(100) DEFAULT NULL,
 `code` varchar(5) DEFAULT NULL,
 `create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `description` varchar(255) DEFAULT NULL,
 `image` varchar(100) DEFAULT NULL,
 `image_name` varchar(400) DEFAULT NULL,
 `name` varchar(30) DEFAULT NULL,
 `price` varchar(200) DEFAULT NULL,
 `mrp_price` varchar(200) DEFAULT NULL,
 `product_category` varchar(100) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ;

6) INSERTING VALUE FOR ADMIN:

INSERT INTO tbladmin(email,password,name) VALUES('[email protected]','admin','DataFlair');

2) Importing packages

By default, Servlet packages are installed by JAVA (J2EE).

But, mysql-connector library and apache-commons-fileupload we have to download from the internet and import into our project.

Download mysql-connector library for online shopping system

Download apache-commons-fileupload library

How to import them?

a) Click on Tools > Libraries

add library

b) At bottom left Click on “New Library”

new library

Name your library and click on “OK”.

create new lib

Now Click on Add JAR/Folder and select the downloaded file to add in online shopping java project and click on “ok”.

add jar in java project

Now, add that library on in your project.

3) Project Structure:

online shopping project structure

Files Description:

a) Admin-add-products.jsp: It is used by admin to add new products in the database of the system.
b) Admin-all-orders.jsp: It is used by admin to view all orders from the database of the system.
c) Admin-delete-product.jsp: It is used by admin to delete any specific product from the database of the system.
d) Admin-delivered-products.jsp: It is used by admin to mark the products as delivered which were pending in the system.
e) Admin-edit-product-process.jsp: It is used by admin to update the details of specific products in the database of the system.
f) Admin-edit-product.jsp: It takes input from the admin to update the specific product and after that process is handled by the Admin-edit-product-process.jsp
g) Admin-login.jsp: It checks the authentication of the admin and redirected to the dashboard.jsp page
h) Admin-logout.jsp: It logouts the admin from the session and sends it back to the admin-login.jsp page.
i) Admin-pending-orders.jsp: It is used by admin to view all pending orders from the database of the system.
j) Admin-view-customers.jsp: It is used by admin to view all customers from the database of the system.
k) Admin-view-product.jsp: It is used by admin to view all products from the database of the system.
l) AdminHeader.jsp: This page contains a navigation bar for the admin/seller dashboard in java online shopping project.
m) Checkout.jsp: This page is used by the customer when it checks out his/her orders, all the order entries made in the database of the system.
n) Customer-login.jsp: It checks the authentication of the customer and redirected to the index.jsp page
o) Customer-register.jsp: This page is used by the customer to register the new customer/user.
p) Dashboard.jsp: This page is used by the admin to display all the counts of the customers, products, orders.
q) Footer.jsp: This is a common page that includes footer and used by all the jsp pages in java online shopping system.
r) Header.jsp: This page contains a navigation bar for the customer/user dashboard.
s) Index.jsp: This is a main display page that includes all products.
t) Logout.jsp: It logouts the user/customer from the session and sends it back to the index.jsp page.
u) My-orders.jsp: This page is used by customers and it contains all the order history of the customer.
v) Products.jsp: This is a display page that includes all products and their descriptions.
w) RemoveProductFromTheCart.jsp: This is used by the customer and it removes specific products from the cart provided by the customer.

4) Functions Used:

a) getParameter(“name”): This function will return the value of the name object of the input of the client.
b) getSession(): This function will return the current session object. If the parameter is true, then it will create a new session in java online shopping project.
c) getAttribute(“object_name”): This function will return the stored value of a specified object from the session.
d) setAttribute(“object_name”,object_value): This function will take the parameters as key and value and store it inside the session.
e)sendRedirect(“name_of_the_page”): This function will redirect the current page to the specified page. The specified page can be html or jsp format.
f) invalidate(): This function will invalidate the session. It is used to clear current session values and also for logout.

5) Connection to Database:

In this step, we will create a universal connection method as a reusable method for java online shopping system project project, this method will connect to MySQL database. Make sure that you enter the proper url string of database connection such as port number, username, password, etc.

Function definitions:

a) forName(driverClassName): This function is used to register with the driver of the database.
b) getConnection(url): This function is used to make connections with databases. It takes parameters such as hostname, port number, database, username, password, etc. Generalized form: “jdbc:mysql://hostname:port/dbName”, “username”, “password”. If your mysql does not have a password then enter “” as an empty string.
c) close(): This function will close the connection of mysql database. This function is important to clean the garbage values and to make an optimized system.

Code:

package com.connection;

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

public class DatabaseConnection {

    //Creating database Connection in java online shopping system
    public static Connection connection;

    //Creating universal method to open connect will mysql database
    public static Connection getConnection() {
        try {
            //Registering with mysql Driver
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/shoppingsystem", "root", "yourpassword");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (connection);
    }

    //Creating universal method to close connect will mysql database
    public static void CloseConnection() {
        if (connection != null) {
            try {
                connection.close();
                connection = null;
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    //Creating universal method to query for retrieving information
    public static ResultSet getResultFromSqlQuery(String SqlQueryString) {
        //Creating Resultset object
        ResultSet rs = null;
        try {
            //Checking whether the connection is null or null
            if (connection == null) {
                getConnection();
            }
            //Querying the query
            rs = connection.createStatement().executeQuery(SqlQueryString);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return rs;
    }

    //Creating universal method to query for inserting or updating information in mysql database
    public static int insertUpdateFromSqlQuery(String SqlQueryString) {
        int i = 2;
        try {
            //Checking whether the connection is null or null
            if (connection == null) {
                getConnection();
            }
            //Querying the query
            i = connection.createStatement().executeUpdate(SqlQueryString);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return i;
    }
}

6) Defining new customer registering servlet

In this step of online shopping system, we will take the values from the frontend (customer-register.jsp) values and insert into our tblcustomer table and if data entered successfully then we will send a response that you have been registered successfully and redirecting to the customer-login.jsp page.

Code:

import java.io.IOException;

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 javax.servlet.http.HttpSession;

import com.connection.DatabaseConnection;

@WebServlet("/AddCustomer")
public class AddCustomer extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //Retrieving values from the frontend
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String mobile = request.getParameter("mobile");
        String gender = request.getParameter("gender");
        String address = request.getParameter("address");
        String pincode = request.getParameter("pincode");
        
        //Creating Session
        HttpSession hs = request.getSession();
        
        //Inserting all values inside the database
        try {
            //Connecting database connection and querying in the database
            int addCustomer = DatabaseConnection.insertUpdateFromSqlQuery("insert into tblcustomer(address,email,gender,name,password,phone,pin_code)values('" + address + "','" + email + "','" + gender + "','" + name + "','" + password + "','"
                    + mobile + "','" + pincode + "')");
            
            //If customer registered successfully in java online shopping system
            if (addCustomer > 0) {
                String message = "Customer register successfully.";
                //Passing message via session.
                hs.setAttribute("success-message", message);
                //Sending response back to the user/customer
                response.sendRedirect("customer-register.jsp");
            } else {
                 //If customer fails to register 
                String message = "Customer registration fail";
                //Passing message via session.
                hs.setAttribute("fail-message", message);
                //Sending response back to the user/customer
                response.sendRedirect("customer-register.jsp");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

7) Defining customer login servlet:

In this step, we will take the values from the frontend (customer-login.jsp) values and check credentials via database. If credentials are correct then user/customer will be redirected to index.jsp page else customer-login.jsp page.

Code:

import java.io.IOException;
import java.sql.ResultSet;
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 javax.servlet.http.HttpSession;

import com.connection.DatabaseConnection;

@WebServlet("/CustomerLogin")
public class CustomerLogin extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //Getting all data from user/customer
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        //Creating Session
        HttpSession hs = request.getSession();
        try {
            //Creating Resultset
            ResultSet resultset = null;
            //Query to check Login Details
            resultset = DatabaseConnection.getResultFromSqlQuery("select * from tblcustomer where email='" + email + "' and password='" + password + "'");
            //Checking whether the details of user are null or not
            if (email != null && password != null) {
                if (resultset.next()) {
                    //Storing the login details in session
                    hs.setAttribute("id", resultset.getInt("id"));
                    hs.setAttribute("name", resultset.getString("name"));
                    //Redirecting response to the index.jsp
                    response.sendRedirect("index.jsp");
                } else {
                    //If wrong credentials are entered in java online shopping system
                    String message = "You have enter wrong credentials";
                    hs.setAttribute("credential", message);
                    //Redirecting response to the customer-login.jsp
                    response.sendRedirect("customer-login.jsp");
                }
            } else {
                //If username or password is empty or null
                String message = "User name or Password is null";
                hs.setAttribute("credential", message);
                //Redirecting response to the customer-login.jsp
                response.sendRedirect("customer-login.jsp");
            }

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

8) Defining admin login servlet

In this step, we will take the values from the frontend (admin-login.jsp) values and check credentials via database. If credentials are correct then admin/seller will be redirected to dashboard.jsp page else admin-login.jsp page in online shopping project.

Code:

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

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 javax.servlet.http.HttpSession;

import com.connection.DatabaseConnection;

@WebServlet("/AdminLogin")
public class AdminLogin extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            //Getting all the parameters from the frontend (admin)
            String email = request.getParameter("email");
            String pass = request.getParameter("upass");

            //Retriving our session
            HttpSession hs = request.getSession();

            //Calling Connection method
            Connection con = DatabaseConnection.getConnection();

            //Creating Statement
            Statement st = con.createStatement();

            //Querying inside the database
            ResultSet resultset = st.executeQuery("select * from tbladmin where email='" + email + "' AND password='" + pass + "'");
            //If all the details are correct
            if (resultset.next()) {
                hs.setAttribute("uname", resultset.getString("name"));
                //Redirecting admin to dashboard page
                response.sendRedirect("dashboard.jsp");

            } else {
                //If details are wrong
                String message = "You have enter wrong credentials";
                hs.setAttribute("credential", message);
                //Redirecting admin to admin login page
                response.sendRedirect("admin-login.jsp");
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

9) Defining servlet for adding product in the database

In this step of online shopping project, we will take all the parameters/inputs from the frontend (admin) and all the inputs of the new product such as image, category, product name, price, etc will be saved to the database.

Code:

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;

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 javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.connection.DatabaseConnection;

@WebServlet("/AddProducts")
public class AddProducts extends HttpServlet {

    //Path where all the images are stored
    private final String UPLOAD_DIRECTORY = "ENTER_YOUR_DIRECTORY_PATH";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //Creating session in java online shopping project
        HttpSession session = request.getSession();
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                //Taking all image requests
                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                String imageName = null;
                String productName = null;
                String productQuantity = null;
                String productPrice = null;
                String descrip = null;
                String mrpPrice = null;
                String status = null;
                String category = null;

                //SALTCHARS to generate unique code for product
                String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
                StringBuilder salt = new StringBuilder();
                Random rnd = new Random();
                while (salt.length() < 3) { // length of the random string.
                    int index = (int) (rnd.nextFloat() * SALTCHARS.length());
                    salt.append(SALTCHARS.charAt(index));
                }
                String code = salt.toString();

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        //Getting image name
                        imageName = new File(item.getName()).getName();
                        //Storing in the specified directory
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + imageName));

                        //Retrieving all information from frontend of online shopping system
                        FileItem pName = (FileItem) multiparts.get(0);
                        productName = pName.getString();

                        FileItem price = (FileItem) multiparts.get(1);
                        productPrice = price.getString();

                        FileItem description = (FileItem) multiparts.get(2);
                        descrip = description.getString();

                        FileItem mprice = (FileItem) multiparts.get(3);
                        mrpPrice = mprice.getString();

                        FileItem fstatus = (FileItem) multiparts.get(4);
                        status = fstatus.getString();

                        FileItem pcategory = (FileItem) multiparts.get(5);
                        category = pcategory.getString();

                    }
                }
                try {
                    int id = 0;
                    String imagePath = UPLOAD_DIRECTORY + imageName;
                    //Querying to insert product in the table
                    int i = DatabaseConnection.insertUpdateFromSqlQuery("insert into tblproduct(id,active,code,description,image,image_name,name,price,mrp_price,product_category) values('" + id + "','" + status + "','" + code + "','" + descrip + "','" + imagePath + "','" + imageName + "','" + productName + "','" + productPrice + "','" + mrpPrice + "','" + category + "')");
                    //If product inserted successfully in the database
                    if (i > 0) {
                        String success = "Product added successfully.";
                        //Adding method in session.
                        session.setAttribute("message", success);
                        //Response send to the admin-add-product.jsp
                        response.sendRedirect("admin-add-product.jsp");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception ex) {
                //If any error occurred while uploading product image
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }
        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }
    }
}

10) Defining add to cart servlet

In this section, we will take products (product_id) as input from the user/customer which he/she wants to add the product into the cart of online shopping system. The products which are added in the cart by the user, their details will be added in the table tblcart.

Code:

import java.io.IOException;
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 javax.servlet.http.HttpSession;

import com.connection.DatabaseConnection;

@WebServlet("/AddToCart")
public class AddToCart extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int id = 0;

        //Getting all the parameters from the user
        int productId = Integer.parseInt(request.getParameter("productId"));
        String price = request.getParameter("price");
        String mrp_price = request.getParameter("mrp_price");
        HttpSession hs = request.getSession();
        try {
            //If user session is null user have to re-login
            if ((String) hs.getAttribute("name") == null) {
                response.sendRedirect("customer-login.jsp");
                //Inserting cart details to the database
            } else {
                int customerId = (int) hs.getAttribute("id");
                //Querying to the database.
                int addToCart = DatabaseConnection.insertUpdateFromSqlQuery("insert into tblcart values('" + id + "','" + price + "',1,'" + price + "','" + customerId + "','" + productId + "','" + mrp_price + "')");
                if (addToCart > 0) {
                    response.sendRedirect("index.jsp");
                }
            }

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

11) Defining servlet for customer to update product quantity in the cart

In this section, we will take products as input from user/customer whenever user/customer updates the quantity of product to the cart. The quantity of product details will be updated to the cart table. (tblcart)

Code:

import java.io.IOException;
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 javax.servlet.http.HttpSession;
import java.sql.*;
import com.connection.DatabaseConnection;

@WebServlet("/UpdateProductQuantity")
public class UpdateProductQuantity extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Getting all the data from the user/cutomer
        int quantity = Integer.parseInt(request.getParameter("quantity"));
        int productId = Integer.parseInt(request.getParameter("productId"));
        HttpSession session = request.getSession();
        String discount_price = null;
        Double productPrice = 0.0;
        try {
            //Querying to database
            ResultSet rs = DatabaseConnection.getResultFromSqlQuery("select discount_price from tblcart where customer_id='" + session.getAttribute("id") + "' and product_id='" + productId + "'");
            while (rs.next()) {
                //Getting data
                discount_price = rs.getString("discount_price");
                //Converting into double from string
                productPrice = Double.parseDouble(discount_price);
            }
            productPrice = productPrice * quantity;
            //Update Query for updating product quantity
            int updateQuantity = DatabaseConnection.insertUpdateFromSqlQuery("update tblcart set quantity='" + quantity + "',total_price='" + productPrice + "' where customer_id='" + session.getAttribute("id") + "' and product_id='" + productId + "' ");
            //If cart of online shopping systemis sucessfully updated
            if (updateQuantity > 0) {
                //Sending response back to the user/customer.
                response.sendRedirect("checkout.jsp");
                //If cart is not updated
            } else {
                 //Sending response back to the user/customer.
                response.sendRedirect("checkout.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

12) Defining servlet for admin to get current products status

In this section, admin will provide order id as input to the seller, and by using database servlet will send responses such as ordered completed, pending order, etc.

Code:

import com.connection.DatabaseConnection;
import java.io.IOException;
import java.sql.ResultSet;

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("/CustomerProductsOrderStatus")
public class CustomerProductsOrderStatus extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            int statusMode = 0;
            //Taking input from admin order-id to get the order status from the database of online shopping system in Java
            ResultSet rs = DatabaseConnection.getResultFromSqlQuery("select order_status from tblorders where order_no='" + request.getParameter("orderId") + "'");
            while (rs.next()) {
                if (rs.getString(1).equals("Deliver")) {
                    statusMode = DatabaseConnection.insertUpdateFromSqlQuery("update tblorders set order_status='Pending' where order_no='" + request.getParameter("orderId") + "'");
                } else {
                    statusMode = DatabaseConnection.insertUpdateFromSqlQuery("update tblorders set order_status='Deliver' where order_no='" + request.getParameter("orderId") + "'");
                }
            }
            if (statusMode > 0) {
                //Sending response back to admin-all-orders.jsp page when sql query executed successfully
                response.sendRedirect("admin-all-orders.jsp");
            } else {
                //Sending response back to admin-all-orders.jsp page
                response.sendRedirect("admin-all-orders.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Java Online Shopping System Output

a) Home Screen:

java online shopping system output

b) Admin Login:

admin login

c) Admin Add Product:

admin add products in online shopping system

d) Customer New Registration (Sign-Up):

online shopping customer registration

e) Adding product to cart, you can also modify the quantity of product, can also delete the product

cart

f) Shopping Admin View Orders:

view orders

Java Online Shopping System – Summary

Yayy! We have finally built our Online Shopping System using java and mysql. Now Seller/Admin can add products, edit products, view products, delete products, view orders, view customers. Customers/Users can view products, add the products in the cart, buy the products. From this project we have learned how we can connect a mysql database with java servlet, and also how to query a database via java.

Your opinion matters
Please write your valuable feedback about DataFlair on Google

follow dataflair on YouTube

12 Responses

  1. Kirti says:

    Hey! I loved your project and I wanted to use your code for my final project but it’s showing me “The method getConnection() is undefined for the type DatabaseConnection” error. Also there are similar errors in all the other files as well. Can you please suggest me what to do about it?

  2. Babu Babu says:

    how to add this files in eclipse and run it

  3. Babu says:

    How to add all files in eclipse??

  4. atithi says:

    ” HTTP Status 500 – Internal Server Error
    type Exception report

    message Internal Server Error

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: java.lang.NullPointerException
    root cause

    java.lang.NullPointerException
    note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.1.1 logs.

    GlassFish Server Open Source Edition 4.1.1 ”

    this what is shown when the whole project source is run.

  5. naveed says:

    Sorry – Java newbie here. I have pulled this down but when I go to build the project I get the error that web-inf does not exist and that the deployment descriptor does not exist. Normal? How do I run it?

  6. Pratik Dubey says:

    where are the images file. there is no file of image in your project folder

  7. Tilen Ochieng says:

    How can I download the codes please

  8. harsh kumawat says:

    the option for run on server is not appearing.

  9. nisha desai says:

    thankyou for the project dataFlair i have successfully imported the project, but where are the images ?
    please suggest me with that

  10. Rohit Sunil Jadhav says:

    ServletException error how to solve plz.. reply

  11. Marcel Guedes says:

    Excelente amostra !! Mas infelizmente não está funcionando corretamente !! Tem um erro sendo mostrado toda a vez que o projeto é executado. Seria interessante fazer o pacote de imagens pra gente poder baixar !! Obrigado !

Leave a Reply

Your email address will not be published. Required fields are marked *