在JSP的同一页面中从Servlet发送数据(对象)到BootStrap模态

问题描述 投票:0回答:1

在我的基于Java,带有BootStrap的JSP和Servlet上构建的应用程序中,存在将数据从Servlet发送到BootStrap Modal的问题。

基于我的项目,用户单击每个表容器中的“检查按钮”,并且table_id被javascript捕获,并使用该值将其发送到Servlet。然后,Servlet根据其table_id从数据库中获取数据。发送到BootStrap模态部分所需的操作的结果(代码中的顺序和结果在打印时会正确显示)。

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);
    }

}

尽管我用谷歌搜索,但没有得到明确的答案。您能帮我解决这个问题吗?

java jsp servlets twitter-bootstrap-3
1个回答
0
投票

好像您在js中进行ajax调用,但是在servlet中,您没有返回响应。我强烈建议您查看this answer如何使用servlet进行Ajax调用。

   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);
    }

当您拨打ajax电话时,您将无法执行以下操作:

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

因为当您通过ajax调用此servlet URL时,您不会再次加载jsp页面,因此HttpServletRequest不会传递到jsp页面。希望这有助于更多地了解它。

© www.soinside.com 2019 - 2024. All rights reserved.