简体   繁体   中英

Sending data(Objects) from Servlet to BootStrap Modal in the same page of JSP

In my application built on Java, JSP with BootStrap, and Servlet, there is the issue to send the data from Servlet to BootStrap Modal.

Based on my project, a user clicks the 'check button' in each table container and that table_id is caught in javascript and send it to Servlet with that value. Then Servlet operates on grabbing the data from the database based on its table_id. The result( orders in the code and results are displayed properly when printing out them ) of the operation needed to send to the BootStrap modal section.

TableMonitor.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<meta name="viewport"
    content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">

<title>Migarock Table Monitoring System</title>

<link rel="canonical"
    href="https://getbootstrap.com/docs/4.0/examples/pricing/">

<!-- Bootstrap core CSS -->
<link href="../../dist/css/bootstrap.min.css" rel="stylesheet">

<!-- Custom styles for this template -->
<link href="pricing.css" rel="stylesheet">
<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">
<link href="./css/tableMonitor.css" rel="stylesheet">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
</head>

<body>

    <!-- 
    <div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom box-shadow">
        <h3 class="my-0 mr-md-auto font-weight-normal">Migarock Table Monitoring System</h3>
        <a class="btn btn-outline-primary" href="#">Lock</a>
    </div> -->
    <div class="row">
        <div class="col-2">
            <div class="container">
                <div class="card-deck mb-3 text-center ">
                    <div class="card mb-4 box-shadow ">
                        <div class="card-header status1">
                            <h3 class="my-0 font-weight-normal ">
                                <strong>Table_01</strong>
                            </h3>
                        </div>
                        <div class="card-body">
                            <a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
                                data-toggle="modal" href="#tableModal" data-table-id="1">Check</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-2">
            <div class="container">
                <div class="card-deck mb-3 text-center">
                    <div class="card mb-4 box-shadow">
                        <div class="card-header">
                            <h3 class="my-0 font-weight-normal">
                                <strong>Table_02</strong>
                            </h3>
                        </div>
                        <div class="card-body">
                            <a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
                                data-toggle="modal" href="#tableModal" data-table-id="2">Check</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-2">
            <div class="container">
                <div class="card-deck mb-3 text-center">
                    <div class="card mb-4 box-shadow">
                        <div class="card-header status2">
                            <h3 class="my-0 font-weight-normal">
                                <strong>Table_03</strong>
                            </h3>
                        </div>
                        <div class="card-body">
                            <a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
                                data-toggle="modal" href="#tableModal" data-table-id="3">Check</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-2">
            <div class="container">
                <div class="card-deck mb-3 text-center">
                    <div class="card mb-4 box-shadow">
                        <div class="card-header">
                            <h3 class="my-0 font-weight-normal">
                                <strong>Table_04</strong>
                            </h3>
                        </div>
                        <div class="card-body">
                            <a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
                                data-toggle="modal" href="#tableModal" data-table-id="4">Check</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-2">
            <div class="container">
                <div class="card-deck mb-3 text-center">
                    <div class="card mb-4 box-shadow">
                        <div class="card-header">
                            <h3 class="my-0 font-weight-normal">
                                <strong>Table_05</strong>
                            </h3>
                        </div>
                        <div class="card-body">
                            <a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
                                data-toggle="modal" href="#tableModal" data-table-id="5">Check</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-2">
            <div class="container">
                <div class="card-deck mb-3 text-center">
                    <div class="card mb-4 box-shadow ">
                        <div class="card-header status3">
                            <h3 class="my-0 font-weight-normal">
                                <strong>Table_06</strong>
                            </h3>
                        </div>
                        <div class="card-body">
                            <a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
                                data-toggle="modal" href="#tableModal" data-table-id="6">Check</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div class="modal fade" id="tableModal" tabindex="1" role="dialog"
        aria-labelledby="modal" aria-hidden="true">

        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title" id="modal">Table Status</h2>
                    <button type="button" class="close" data-dismiss="modal"
                        aria-label="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="controlBar">
                    <div class="row">
                        <div class="col-8" style="text-align: left;">
                            <button type="button" class="btn btn-outline-success btn-lg"
                                data-dismiss="modal">Add item</button>
                            <button type="button" class="btn btn-outline-secondary btn-lg"
                                data-dismiss="modal">Change Status</button>

                        </div>
                        <div class="col-4" style="text-align: right; padding-right: 10%;">
                            <button type="button" class="btn btn-outline-warning btn-lg"
                                data-dismiss="modal">Help</button>
                            <button type="button" class="btn btn-outline-info btn-lg"
                                data-dismiss="modal">Bill</button>
                        </div>
                    </div>
                    <div>


                        <div class="modal-body">
                            <h3>My name is ${test}</h3>
                            <!-- <form action="./evaluationRegisterAction.jsp" method="post"> -->
                            <div class="scrollbar scrollbar-primary">
                                <!-- <div> -->
                                <table class="table">
                                    <thead>
                                        <tr style="text-align: center;">
                                            <th scope="col"><input type="checkbox"
                                                class="select-all checkbox" name="select-all" /></th>
                                            <th scope="col">OrderTime</th>
                                            <th scope="col">Item</th>
                                            <th scope="col">QTY</th>
                                            <th scope="col">Price</th>
                                            <th scope="col">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <c:out value="${requestScope.orders}">
                                            <c:forEach items="${orders}" var="order">
                                                <tr style="text-align: center;">
                                                    <td style="text-align: center;">
                                                        <div class="form-check">
                                                            <input type="checkbox" class="select-item checkbox"
                                                                name="select-item">

                                                        </div>
                                                    </td>

                                                    <td><span id="orders"></span> ${order.getTimeStamp()}</td>
                                                    <td>{order.getOrderItem()}</td>
                                                    <td>{order.getOrderQty()}</td>
                                                    <td>{order.getOrderPrice()}</td>
                                                    <td>{order.getOrderStatus()}</td>

                                                    <td><a class="btn btn-light btn-sm mx-1 mt-2"
                                                        data-toggle="modal" href="#changeStatus">Ordered</a> <!-- <a class="btn btn-dark btn-sm mx-1 mt-2" data-toggle="modal"
                                                href="#changeStatus">Delivered</a> -->
                                                    </td>
                                                </tr>
                                            </c:forEach>
                                        </c:out>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div>
                            <table class="table">
                                <tr style="text-align: center;">
                                    <td colspan="3">
                                        <h4>Total</h4>
                                    </td>
                                    <td colspan="3">
                                        <h4>(total)</h4>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="controlBar">
                            <div class="row">
                                <div class="col-6" style="text-align: left;">
                                    <button type="button" class="btn btn-danger btn-lg"
                                        data-dismiss="modal">Close Session</button>
                                </div>
                                <div class="col-6"
                                    style="text-align: right; padding-right: 10%;">

                                    <button type="button" class="btn btn-outline-danger btn-lg"
                                        data-dismiss="modal">Close Window</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- </form> -->
                </div>
            </div>
        </div>

    </div>


    <footer class="pt-4 my-md-5 pt-md-5 border-top"> </footer>
    </div>


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
        crossorigin="anonymous"></script>
    <script>
        window.jQuery
                || document
                        .write('<script src="../../assets/js/vendor/jquery-slim.min.js"><\/script>')
    </script>
    <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>
    <script>
        Holder.addTheme('thumb', {
            bg : '#55595c',
            fg : '#eceeef',
            text : 'Thumbnail'
        });
    </script>
    <script>
        $(function() {

            //button select all or cancel
            $("#select-all").click(function() {
                var all = $("input.select-all")[0];
                all.checked = !all.checked
                var checked = all.checked;
                $("input.select-item").each(function(index, item) {
                    item.checked = checked;
                });
            });

            //button select invert
            $("#select-invert").click(function() {
                $("input.select-item").each(function(index, item) {
                    item.checked = !item.checked;
                });
                checkSelected();
            });

            //button get selected info
            $("#selected").click(
                    function() {
                        var items = [];
                        $("input.select-item:checked:checked").each(
                                function(index, item) {
                                    items[index] = item.value;
                                });
                        if (items.length < 1) {
                            alert("no selected items!!!");
                        } else {
                            var values = items.join(',');
                            console.log(values);
                            var html = $("<div></div>");
                            html.html("selected:" + values);
                            html.appendTo("body");
                        }
                    });

            //column checkbox select all or cancel
            $("input.select-all").click(function() {
                var checked = this.checked;
                $("input.select-item").each(function(index, item) {
                    item.checked = checked;
                });
            });

            //check selected items
            $("input.select-item").click(function() {
                var checked = this.checked;
                console.log(checked);
                checkSelected();
            });

            //check is all selected
            function checkSelected() {
                var all = $("input.select-all")[0];
                var total = $("input.select-item").length;
                var len = $("input.select-item:checked:checked").length;
                console.log("total:" + total);
                console.log("len:" + len);
                all.checked = len === total;
            }
        });

        $('#tableModal')
                .on(
                        'show.bs.modal',
                        function(e) {
                            var tableID = $(e.relatedTarget).data('table-id');
                            console.log("test: ", tableID)
                            $(e.currentTarget).find('input[name="tableID"]')
                                    .val(tableID);
                            var xhttp = new XMLHttpRequest();
                            xhttp.onreadystatechange = function() {
                                if (this.readyState == 4 && this.status == 200) {
                                    // Typical action to be performed when the document is ready:
                                    document.getElementById("response").value = xhttp.responseText;
                                }
                            };
                            xhttp.open("POST", "TableMonitor", true);
                            xhttp.setRequestHeader("Content-type",
                                    "application/x-www-form-urlencoded");
                            xhttp.send("tableId=" + tableID);

                            var orders = $(this).data('orders');
                            $('#orders').html(orders);
                        });
    </script>
</body>

</html>

TableMonitor.java(Servlet)

package servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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 brokers.TableBrokder;
import model.Order;

/**
 * Servlet implementation class TableMonitor
 */
@WebServlet("/TableMonitor")
public class TableMonitor extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public TableMonitor() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        getServletContext().getRequestDispatcher("/TableMonitor.jsp").forward(request, response);
    }
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String table_id = request.getParameter("tableId");
        String action = request.getParameter("action");

        System.out.println("servlet: " + table_id);

        List<Order> orders = null;
        TableBrokder tb = new TableBrokder();
        try {
            orders = tb.getOrderAll(Integer.parseInt(table_id));
        } catch (NumberFormatException | SQLException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < orders.size(); i++) {
            orders.get(i).toString();
        }
//      response.sendRedirect("TableMonitor");

        RequestDispatcher dispatcher = request.getRequestDispatcher("/TableMonitor.jsp");
        request.setAttribute("orders", orders);
        request.setAttribute("test", "test");
        dispatcher.forward(request, response);
    }

}

Even though I google it but didn't get clear answers. Could you help me with this issue?

Looks like you are making an ajax call in your js but in your servlet you are not returning the response. I highly recommend checking out this answer on how to make ajax calls with servlets.

   protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String table_id = request.getParameter("tableId");
        String action = request.getParameter("action");

        System.out.println("servlet: " + table_id);

        List<Order> orders = null;
        TableBrokder tb = new TableBrokder();
        try {
            orders = tb.getOrderAll(Integer.parseInt(table_id));
        } catch (NumberFormatException | SQLException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < orders.size(); i++) {
            orders.get(i).toString();
        }

       //convert your list of orders to json 
       String json = new Gson().toJson(orders);

       //add json to response
       response.setContentType("application/json");
       response.setCharacterEncoding("UTF-8");
       response.getWriter().write(json);
    }

When you make ajax calls you won't be able to do things like this:

 request.setAttribute("orders", orders);
 request.setAttribute("test", "test");

Because when you call this servlet url through ajax, you are not loading the jsp page again so the HttpServletRequest won't be passed to the jsp page. Hope this helps understand it some more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM