java 将 html 表从 jsp 页面传递给 servlet

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27221934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:26:04  来源:igfitidea点击:

passing an html table to servlet from a jsp page

javamysqljspservlets

提问by Abdirazack

I have html table in jsp page the loads data from database dynamically then I wan to save all data in the table into database through servlet. now my problem is i am having a jsp page which display a table of data from a servlet with checkbox in it, i have to send that checked contents to the servlet for updating to the database, how to do that.

我在jsp页面中有html表,动态加载数据库中的数据,然后我想通过servlet将表中的所有数据保存到数据库中。现在我的问题是我有一个 jsp 页面,它显示来自带有复选框的 servlet 的数据表,我必须将检查的内容发送到 servlet 以更新到数据库,如何做到这一点。

thanks in advance and this is my table

提前致谢,这是我的桌子

<form action="showKwh" method="POST">

    <input type="submit" value="show"/>

    <table id="adminTable" class="detailsTable">

        <tr class="header">
            <th colspan="4">Kilowat Entry</th>
        </tr>

        <tr class="tableHeading">
            <td></td>
            <td>customer id</td>
            <td>name</td>

            <td>group</td>
            <td>kwh</td>



            <td>kwd</td>

        </tr>

        <c:forEach  var="cust" items="${customerKwh}" varStatus="iter">
            <tr id="${cust.id}" class="${((iter.index % 2) == 1) ? 'lightBlue' : 'white'} tableRow">
                <td><input type="checkbox" name="check1" class="checker" value="ON" /></td>
                <td id="id?${customer.id}">${cust.id}</td>
                <td >${cust.name}</td>
                <td >${cust.type}</td>

                <td >${cust.kwh}</td>



                <td><input type="text" name="txt" size="8" id="kwd${cust.id}" value="${param.value}" class="name1"  /></td>

            </tr>
        </c:forEach>
    </table>
</form>

回答by iTollu

Either you put all data that you need to post back upon submit into form fields and browser sends it, or you use some javascript like jQuery to manipulate your html table's DOM, extract data on the clientside and send it via ajax request in form of JSON or XML to be parsed serverside.

要么将提交时需要回发的所有数据放入表单字段中,然后浏览器将其发送,要么使用诸如 jQuery 之类的 javascript 来操作 html 表的 DOM,在客户端提取数据并通过 ajax 请求以 JSON 的形式发送或要在服务器端解析的 XML。

It's quite strange requirements, though. Since data in the table originates from the same server that processes response, it would be sufficient to respond with a set of row identifiers, by which the server would recognize full row data.

不过,这是很奇怪的要求。由于表中的数据来自处理响应的同一台服务器,因此使用一组行标识符进行响应就足够了,服务器将通过这些标识符识别完整的行数据。

You could pass these identifiers with checkboxes' values: <input type="checkbox" name="check1" class="checker" value="${cust.id}" />. Then, following HTML standard, only checkboxes having checkedor checked="checked"attribute would be included in response. Then your servlet can process all checked checkboxes and get all needed identifiers.

你可以通过这些标识符与复选框的价值观:<input type="checkbox" name="check1" class="checker" value="${cust.id}" />。然后,按照 HTML 标准,只有具有checkedchecked="checked"属性的复选框才会包含在响应中。然后您的 servlet 可以处理所有选中的复选框并获取所有需要的标识符。

Extracting form data with jQuery.First, add to your <td>'s with data classes that would mark contained data, so we can select it with jQuery:

使用 jQuery 提取表单数据。首先,<td>将标记包含数据的数据类添加到您的's 中,以便我们可以使用 jQuery 选择它:

<td class="customerName">${cust.name}</td>
<td class="customerType">${cust.type}</td>
...and so on.

Include jQuery into JSP with element <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>added before closing tag. Then add another script element on the page containing our script. Here is an example:

将 jQuery 包含到 JSP 中,<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>并在关闭标记之前添加元素。然后在包含我们脚本的页面上添加另一个脚本元素。下面是一个例子:

<html>
<head>

</head>
<body>

<form action="showKwh" method="POST">

    <input type="submit" value="show"/>

    <table id="adminTable" class="detailsTable">

        <tr class="header">
            <th colspan="4">Kilowat Entry</th>
        </tr>

        <tr class="tableHeading">
            <td></td>
            <td>customer id</td>
            <td>name</td>

            <td>group</td>
            <td>kwh</td>


            <td>kwd</td>

        </tr>

        <tr id="123" class="lightBlue tableRow">
            <td><input type="checkbox" name="check1" class="checker" value="123"/></td>
            <td id="id?123" class="customerId">123</td>
            <td class="customerName">Ivan</td>
            <td class="customerType">Person</td>

            <td class="customerKWH">54321</td>


            <td><input type="text" name="txt" size="8" id="kwd123" value="98765" class="name1"/></td>

        </tr>
    </table>
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () { //launch this code after the whole DOM is loaded
        $("form").submit(function (event) { // function to process submitted table
                    var tableData = []; // we will store rows' data into this array
                    $("#adminTable") // select table by id
                            .find(".tableRow") // select rows by class
                            .has(":checked") // select only rows with checked checkboxes
                            .each(function () { // for each selected row extract data               
                                var tableRow = {};
                                var jRow = $(this);
                                tableRow.customerId = jRow.find('td.customerId').text();
                                tableRow.customerType = jRow.find('td.customerType').text();
                                tableRow.customerKWH = jRow.find('td.customerKWH').text();
                                tableRow.costomerKWD = jRow.find('input.name1').val();
                                tableData.push(tableRow);
                            });

                    $.post(
                            "http://google.com", /*url of consuming servlet*/
                            {tableData: tableData}, /*data*/
                            function () {
                                alert("Success!");
                            }, /*function to execute in case of success*/
                            "json" /* data type */
                    );
                    event.preventDefault(); //Prevent sending form by browser
                }
        );


    });
</script>
</body>
</html>

To process table values submitted by form in browser,you can consider the following approach.

在浏览器中处理表单提交的表值,可以考虑以下方法。

HttpServletRequest inherits from ServletRequest method getParameterMap() which returns Map. ( http://docs.oracle.com/javaee/7/api/javax/servlet/ServletRequest.html#getParameterMap()). You could parse it using some parameter names convention. For example:

HttpServletRequest 继承自 ServletRequest 方法 getParameterMap(),它返回 Map。(http://docs.oracle.com/javaee/7/api/javax/servlet/ServletRequest.html#getParameterMap())。您可以使用一些参数名称约定来解析它。例如:

Map<String, String[]> tableData = getParameterMap();
String[] idsToUpdate = tableData.get("selectedIds");
for (String id : idsToUpdate){
    String kwdParamName = "kwd"+id;
    String kwd = tableData.get(kwdParamName)[0];
}

One way or the other, you should parse request data somehow. Both (JSON-based and form-based) have their pro et contra. You should chose which one produces more clean and robust solution. Maybe, more pleases you aesthetically. And last, but not least, what is your client context: doest it have javascript enabled, is it single-page application or round-trip. In single-page it is more usual way to pass data back and forth via JSON. In round-trip - maybe form-based would be more practical.

一种或另一种方式,您应该以某种方式解析请求数据。两者(基于 JSON 和基于表单)都有其优点和缺点。您应该选择哪一种能产生更清洁、更可靠的解决方案。也许,在美学上更让你满意。最后但并非最不重要的是,您的客户端上下文是什么:它是否启用了 javascript,它是单页应用程序还是往返。在单页中,通过 JSON 来回传递数据是更常见的方式。在往返中 - 也许基于形式会更实用。

回答by Sudhir Dhumal

As your input field (checkbox) is in for loop so all checkboxes will have the same name attribute. So you can get values for input fields having same name using following method available in HttpServletRequest.

由于您的输入字段(复选框)处于 for 循环中,因此所有复选框都将具有相同的名称属性。因此,您可以使用以下方法获取具有相同名称的输入字段的值HttpServletRequest

String[] getParameterValues(String name)

In your case you can fetch all values using following statement-

在您的情况下,您可以使用以下语句获取所有值-

request.getParameterValues("check1");