Home Servlet Inventory Management Servlet Jsp with Ajax

Inventory Management Servlet Jsp with Ajax

33 min read
0
0
1,269

This tutorial will teach you how to make a Inventory Management System in Servlet Jsp with Ajax step by step. This system will helpful you to learn Inventory Management System.this system helpful for you learn sales handling process of Servlet Jsp mvc with ajax.

In order to create the project download the following Jar Files

gson-2.2.2.jar
json-simple-1.1.jar
mysql-connector-java.jar

Sales.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Inventory Management System in Jsp Servlet Ajax</title>
       
        <link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
        
        
</head>
<body>
   
</br>
<div class="container-fluid bg-2 text-center">
<div class="row">
    <div class="col-sm-8">
        <form class="form-horizontal" id="frmInvoice">

            <table class="table table-bordered">
                <caption> Add Products  </caption>
                <tr>
                    <th>Product Code</th>
                    <th>Product Name</th>
                    <th>Price</th>
                    <th>Qty</th>
                   
                    <th>Amount</th>
                    <th>Option</th>
                </tr>
                <tr>
                    
                
                    
                    
                    <td>
                        
                       
                        
                        <input type="text" class="form-control" placeholder="barcode" id="barcode" name="barcode"  size="25px"  required>
                    </td>
                    <td>
                      
                        <label id="pname" name="pname"></label>
                        
                    </td>
                    <td>
                          <label id="pro_price" name="pro_price"></label>
                        
                    </td>
                   <td>
                    <input type="number" class="form-control pro_price" id="qty" name="qty"
                           placeholder="qty" min="1" value="1"  required>
                </td>
                <td>
                    <input type="text" class="form-control" placeholder="total_cost" id="total_cost" name="total_cost" disabled>
                </td>
                    <td>
                           <div class="focusguard" id="focusguard-2" tabindex="8"></div>
                            
                        <button class="btn btn-success" type="button" onclick="addproduct()">Add
                        </button>
            
                    
                    
                    
                </tr>
            </table>
        </form>
            <table class="table table-bordered" id="product_list">
                <caption> Products</caption>
                <thead>
                <tr>
                    <th style="width: 40px">Remove</th>
                    <th>Product Code</th>
                    <th>Product Name</th>
                    <th>Unit price</th>
                    <th>Qty</th>
                  
                    <th>Amount</th>
                    
                </tr>
                </thead>

                <tbody>
                    
                </tbody>
            </table>
    </div>

    <div class="col-sm-4">
      
        <div class="col s12 m6 offset-m4">
    
                     <td>
                        <input type="hidden"  id="uname" name="uname" value =" <%= username %> " >
                    </td>
            
            

            <div class="form-group" align="left">
                <label class="form-label">Total</label>
                <input type="text" class="form-control" placeholder="Total" id="subtotal" name="subtotal" size="30px" required >
            </div>

            <div class="form-group" align="left">
                <label class="form-label">Pay</label>
                <input type="text" class="form-control" placeholder="Pay" id="pay" name="pay" size="30px" required>
            </div>

            <div class="form-group" align="left">
                <label class="form-label">Balance</label>
                <input type="text" class="form-control" placeholder="Balance" id="balance" name="balance" size="30px"  >
            </div>
        </form>

         
         
            <div class="form-group" align="left">
                <label class="col-sm-2 control-label">Status</label>
                <select class="form-control" id="payment" name="payment"
                        placeholder="Project Status" required>
                    <option value="">Please Select</option>
                    <option value="1">Cash</option>
                    <option value="2">Cheque</option>
                </select>
            </div>


            <div align="right">
                <div class="focusguard" id="focusguard-2" tabindex="8"></div>
                <button id="btnadd" type="button" id="save" class="btn btn-info" onclick="addProject()">Print Invoice
                </button>
            
                
                <button type="button" id="clear" class="btn btn-warning" onclick="reSet()">Reset</button>

            </div>
        </div>
           
    </div>

</div>

<br><br>
        
        <script src="component/jquery/jquery.js" type="text/javascript"></script>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        
        
        <script src="component/shortcut.js" type="text/javascript"></script>
        
        
        <script src="component/jquery.validate.min.js" type="text/javascript"></script>
         <script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js" type="text/javascript"></script>
        
        
        
        <script>
            
          //  getall();
            var isNew = true;
            var catid = null;
            
            var item = null;
         
         var newval = null;
            getCategory();




function getCategory(){
    
    
    $.ajax({

        type: "GET",
        url: "product/get_category.jsp" ,
        dataType: "JSON",
        
         success: function(msg)
        {
            console.log(msg);

            for (var i = 0; i < msg.length; i++) {
                $('#category').append($("<option/>", {
                    value: msg[i].id,
                    text: msg[i].catname ,
                }));
            }             
        },
        
       
        error: function (xhr, status, error) {
            alert(xhr.responseText);
//
        }

    });
}



   $('#barcode').on('input', function (e) 
    {
       getProductcode();
    });


    function getProductcode() {

            $.ajax({
                type: "POST",
                url: "product/get_id.jsp",
                dataType: "JSON",
                data: {"a": $("#barcode").val()},
                
                success: function(data) {

                  console.log(data);
                    
                    $('#pname').html(data[0].prodname);
                    $("#pro_price").html(data[0].retailprice);
                    $("#qty").focus();
                    current_stock=Number(data[0].qty);

                    


                    console.log(data.qty);
                },
                error: function(xhr, status, error) {

                }
            });
       
    }
    
     function single_product_total()
    {
        var qty = $('#qty').val();
        total = Number($('#pro_price').html()) * qty;
        $("#total_cost").val(total);
    }

    $('#qty').on('input keydown keyup click', function (e)
    {
            single_product_total();
    });
    
    
    
    

    $('#qty').on('input keydown keyup click', function (e)
    {
            single_product_total();
    });
    


 $(function() {
        $("#subtotal, #pay").on("keydown keyup", per);

        function per() {
            var totalamount = (
            Number($("#pay").val()) - Number($("#subtotal").val())
            );
            $("#balance").val(totalamount);
        }
    });


 var total = 0;
 function addproduct() 
 {
        var barcode = $('#barcode').val();   
        var pname = $('#pname').html();
        var pro_price = $('#pro_price').html();
        var qty = $('#qty').val();
        var total_cost = $('#total_cost').val();
       
            var table1 =
                "<tr>" +
                "<td><button type='button' name='record' class='btn btn-warning' onclick='deleterow(this)'>Delete </td>" +
                 "<td>" + barcode + "</td>" +
                "<td>" + pname + "</td>" +
                "<td>" +  pro_price +  "</td>" +
                "<td>" +  qty +  "</td>" +
                "<td>" +  total_cost +  "</td>" +
                "</tr>" ;

        
            $("#product_list tbody").append(table1);
            
   
            total += Number(total_cost);
            

            $('#subtotal').val(total);
            $('#barcode').val('');
            $('#total').val(total);
            $('#qty').val("1");
            $('#pname').html('');
            $('#pro_price').html('');
            $('#qty').val("1");
            $('#total_cost').val('');
            $('#barcode').focus();            
}

    function deleterow(e)
    {
        total_cost = parseInt($(e).parent().parent().find('td:last').text(),10);
        total -= total_cost;
        $('#total').val(total);
        $(e).parent().parent().remove();
    }

           
    $(function() {
    $("#subtotal, #pay").on("keydown keyup", per);

    function per() {
        var totalamount = (
        Number($("#subtotal").val()) - Number($("#pay").val())
        );
        $("#due").val(totalamount);
    }
});
            
            
           
 
            function get_details(id)
            {
                $.ajax({
                    type: "POST",
                    url : "product/edit_return.jsp",
                    data : {"id": id},
                    success: function(data)
                    {
                        isNew = false
                        var obj = JSON.parse(data);
                        catid = obj[0].id
                        $('#category').val(obj[0].catname);
                         $('#status').val(obj[0].status);
                    }
                });
   
            }

            function get_delete(id)
            {   
                $.ajax({
                    type: 'POST',
                    url: 'product/delete.jsp',
                    dataType: 'JSON',
                    data:{"id": id},
                    success:function(data)
                    {
                        alert("Record Deletedddd");
                        getall();
                    } 
                });  
            }

   function addProject()
   {
      var table_data = new Array();
        $('#product_list tbody tr').each(function (row, tr)
       {
   
         var sum = {
             //these records i am going to add into sales table
                    'barcode': parseInt($(tr).find('td:eq(1)').text()),
                    'pname': $(tr).find('td:eq(2)').text(),
                    'pro_price': $(tr).find('td:eq(3)').text(),
                    'qty': $(tr).find('td:eq(4)').text(),
                    'total': $(tr).find('td:eq(5)').text()
                };
                table_data.push(sum);
            });
            //these records i am going to add into sales
              var subtotal =  $('#subtotal').val();
              var pay =  $('#pay').val();
              var balance =  $('#balance').val();
              var uname =  $('#uname').val();
              
              var data1 =  JSON.stringify(table_data) +  "&pay=" + pay +  "&subtotal=" + subtotal  +   "&balance=" + balance  +   "&uname=" + uname ;
              var total =  $('#total').val();
                       
           
              
              console.log(data1);
              
    $.ajax({
        type: 'POST',
        url: 'salesadd',
        dataType: 'JSON',
        data: 'data1=' + data1,
        
        success: function (data)
        {
            
            console.log(data);
            newval = data[0].newval
            
           
           
         window.location.href = "print.jsp?lastinsetid=" + newval ;
            
        },
        error: function (xhr, status, error)
        {
            console.log(xhr.responseText);
        }
    });
}


//    keyboard shortcuts
    shortcut.add("f8",function() {
       $('#pay').focus();
        $('#pay').select();
    });
    shortcut.add("f6",function() {
        $('#barcode').focus();

    });
    $(document).keypress(function(e) {
        if(e.which == 13 && $('#pay').is(":focus")) {
            addProject();
        }
    });
    
   function cancel(){
        $('#frmCustomer')[0].reset();
        $('#mdlCustomer').modal('hide');
        $('#cusDetails').html('');
        $('#selectCus').hide();
        $('#cusErr').html('');
        $('#cusphonesearch').val('');
    }
    
    
     $('#focusguard-2').on('focus', function() {
        $('#barcode').focus();
    });

    $('#focusguard-1').on('focus', function() {
        $('#btnadd').focus();
    });
    
        </script>

    </body>
</html>

make inside the product folder

get_id.jsp

<%@page import="java.sql.*" %>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.parser.JSONParser"%>
<%@page import="org.json.simple.parser.ParseException"%>

<%
     JSONArray list = new JSONArray();
     Connection con;
            PreparedStatement pst;
            ResultSet rs;
            Class.forName("com.mysql.jdbc.Driver");
            String a1 = request.getParameter("a");
           con = DriverManager.getConnection("jdbc:mysql://localhost/jsppos","root","");
            pst = con.prepareStatement("select * from product where barcode = ?");
            pst.setString(1, a1);
            rs = pst.executeQuery();

            if(rs.next() == true)
            {
                 String prodname   = rs.getString("prodname");
                 String price     = rs.getString("retailprice");
                 JSONObject obj = new JSONObject();
                 obj.put("prodname", prodname);
                 obj.put("retailprice", price); 
                 list.add(obj);
            }
            
           out.print(list.toJSONString());
           out.flush(); 

%>

salesadd.java

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
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 org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@WebServlet("/salesadd")
public class salesadd extends HttpServlet 
{
       @Override
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
        
           response.setContentType("text/html;charset=UTF-8");
           PrintWriter out = response.getWriter();
           Connection con;
           PreparedStatement pst; 
           PreparedStatement pst1; 
           PreparedStatement pst2; 
           
           
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDateTime now = LocalDateTime.now();
            String date = dtf.format(now);
            

           
           
            String jsonData = request.getParameter("data1");
            String uname = request.getParameter("uname");
            
            
            String subtotal = request.getParameter("subtotal");
            String pay = request.getParameter("pay");
            String balance = request.getParameter("balance");
            int lastinsetid  = 0;
           
           try
           {
           JSONArray list = new JSONArray();
           JSONObject obj = new JSONObject();
           Class.forName("com.mysql.jdbc.Driver");
           con = DriverManager.getConnection("jdbc:mysql://localhost/jsppos", "root", ""); 
           String query = "insert into sales(casier,date,subtotal,pay,bal)values(?,?,?,?,?)";          
           pst1 = con.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);        
           pst1.setString(1, uname);
           pst1.setString(2, date);
           pst1.setString(3, subtotal);
           pst1.setString(4, pay);
           pst1.setString(5, balance);
           pst1.executeUpdate();
           ResultSet genteratedKeyResult = pst1.getGeneratedKeys();
           
           if(genteratedKeyResult.next())
            {
                lastinsetid =genteratedKeyResult.getInt(1);
            }
           
           String newval = String.valueOf(lastinsetid);
           obj.put("newval",newval);
           
           list.add(obj);
           out.print(list.toJSONString());
           out.flush(); 
           Gson gson = new Gson();
           List<Product> objectList = getObjectList(jsonData, Product.class);
           
           
         for (Product product : objectList) 
         {

           try
           { 
             
            Class.forName("com.mysql.jdbc.Driver");
            int barcode = product.get_barcode();
            int qty     =  product.getQty();
            pst2 = con.prepareStatement("update product set qty =qty-? where id =?  ");
            pst2.setInt(1, qty);
            pst2.setInt(2, barcode);
            pst2.executeUpdate();    

           pst = con.prepareStatement("insert into sales_product(sales_id,prod_id,price,qty,total)values(?,?,?,?,?) ");
           pst.setInt(1, lastinsetid);
           pst.setInt(2, product.get_barcode());
           pst.setInt(3, product.getPrice());
           pst.setInt(4, product.getQty());
           pst.setInt(5, product.getTotal());
           pst.executeUpdate(); 
           
           } 
           
           catch (SQLException ex) 
           {
           ex.printStackTrace(); 
           }      
           catch (ClassNotFoundException ex) 
           {
                ex.printStackTrace(); 
           }
        
      }
           } 
           catch (SQLException ex)
           {
            ex.printStackTrace(); 
           } catch (ClassNotFoundException ex) {
               ex.printStackTrace(); 
           }
    }
    public static <T> List<T> getObjectList(String jsonString,Class<T> cls){
    List<T> list = new ArrayList<>();
    try {
        Gson gson = new Gson();
        JsonArray arry = new JsonParser().parse(jsonString).getAsJsonArray();
        for (JsonElement jsonElement : arry) 
        {
            list.add(gson.fromJson(jsonElement, cls));
        }
    } catch (Exception e) 
    {
        e.printStackTrace();
    }
    return list;
}
   
}
    
    
    
    

 

Print.jsp

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="org.json.simple.JSONObject"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="java.sql.*" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>


<%
Connection con;
PreparedStatement pst;
ResultSet rs;

String lastid = request.getParameter("lastinsetid");
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/jsppos","root","");
pst = con.prepareStatement("select sales.id,sales.subtotal,sales.pay,sales.bal, salesp.price,salesp.qty,salesp.total, prod.barcode,prod.prodname from sales_product salesp, sales sales, product prod where sales.id = salesp.sales_id and salesp.prod_id = prod.barcode and salesp.sales_id =?");
pst.setString(1, lastid);
rs = pst.executeQuery();


 if(rs.next()== true)                                   
{
    String id = rs.getString(1);
    String subtotal = rs.getString(2);
    String pay = rs.getString(3);
    String bal = rs.getString(4);
    String price = rs.getString(5);
    String qty = rs.getString(6);
    String total = rs.getString(7);
    String pid = rs.getString(8);
    String pname = rs.getString(9);
    
 %>

    <html>
    <head>
        <title></title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">


        <style>
            @media print
            {
                .button
                {
                    display: none;
                }
            }

            @media print
            {
                @page {
                    margin-top: 0;
                    margin-bottom: 0;
                }
                body  {
                    padding-top: 72px;
                    padding-bottom: 72px ;
                }
            }

        </style>

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>


    </head>
    <body style='background: #f9f9f9'>


    <div class="container">
        <div class="row">
            <div class="col-xs-12">
                <div class='print' style="border: 0px solid #a1a1a1; font-family:monospace; font-size: 14px; width: 88mm; background: white; padding: 10px; margin: 0 auto; text-align: center; ">
                    <div class="invoice-title" align="center">
                        <h3>               
                            <img src="image/tit1.jpg" width="200px" height="100px" alt=""/></h3>
                    </div>

                    <div class="invoice-title" align="left">
                        Order #  &nbsp; &nbsp;<b> <%=id %></b>
                    </div>
                    <div class="invoice-title" align="left">
                        Date #  &nbsp; &nbsp;  <b>  
                        <%java.text.DateFormat df = new java.text.SimpleDateFormat("dd/MM/yyyy"); %>
                       <%= df.format(new java.util.Date()) %> 
                        </b>
                    </div>

                    
                   
                    </br>

                    <div>
                        <div>
                            <table class="table table-condensed">
                            <thead>
                                <tr>
                                    <td class="text-center"><strong>No</strong></td>
                                    <td class="text-center"><strong>Pname</strong></td>
                                    <td class="text-center"><strong>Qty</strong></td>
                                    <td class="text-center"><strong>Price</strong></td>
                                    <td class="text-right"><strong>Total</strong></td>
                                </tr>
                               
                                
                                
                                
                                <%       
                                    Class.forName("com.mysql.jdbc.Driver");
                                    con = DriverManager.getConnection("jdbc:mysql://localhost/jsppos","root","");

                                    pst = con.prepareStatement("select sales.id,sales.subtotal,sales.pay,sales.bal, salesp.price,salesp.qty,salesp.total, prod.barcode,prod.prodname from sales_product salesp, sales sales, product prod where sales.id = salesp.sales_id and salesp.prod_id = prod.barcode and salesp.sales_id =?");
                                    pst.setString(1, lastid);
                                    rs = pst.executeQuery();
                                     int x = 1;
                                     while(rs.next())
                                     {
                                 %>
                
                                    <tr>
                                        <td class="text-center">
                                             <%= x %>
                                        </td >
                                        
                                        <td class="text-center"> 
                                           <%=rs.getString("prod.prodname") %>
                                        </td >
                                        <td class="text-center">
                                             <%=rs.getString("salesp.qty") %>
                                            
                                        </td >
                                        
                                        <td class="text-center">
                                           <%=rs.getString("salesp.price") %>
                                        </td>
                                     
                                        <td class="text-center">
                                            <%=rs.getString("salesp.total") %>
                                        </td>
                                    </tr>

                                <% x= x + 1; %>      
                                <% } %>      
                                    
                            </table>

                        </div>
                    </div>
                    <div  align="right">
                        Sub Total &nbsp;&nbsp;<b> <%=subtotal  %></b>
                    </div>
                    <div align="right">
                        Pay  &nbsp;&nbsp; <b> <%=pay  %></b>
                    </div>
                    <div align="right">
                        Due &nbsp;&nbsp;   <b> <%=bal  %></b>
                    </div>

                    <div align="center">
                        <i>60 b bank road India</i>
                    </div>
                </div>
           </div>
            <div>
                <div>
                </div>

                <center>

   
     <script src="component/jquery/jquery.js" type="text/javascript"></script>
        <script src="component/jquery/jquery.min.js" type="text/javascript"></script>
        <script src="component/jquery.validate.min.js" type="text/javascript"></script>

    <script>

       myFunction();
        window.onafterprint = function(e)
        {
         closePrintView();
        };
        function myFunction()
        {
           window.print();
        }
        function closePrintView()
        {
           window.location.href = 'sales.jsp';
        }

    </script>
    
 </body>
    </html>


<% } %>

Download the full Source code

Download

i have attached the video link below. which will do this tutorials step by step

 

Load More Related Articles
Load More By admin
Load More In Servlet

Leave a Reply

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

Check Also

Laravel 11 CRUD Mastering RESTful API MVC with Repository Pattern

In this tutorial will teach Laravel 11 Api MVC with Repository Pattern Crud Application st…