如何从jsp列出数据库数据并打印出来?

时间:2019-07-12 05:32:36

标签: javascript java mysql spring

我正处于web开发的初期。

我可以获得DBdata,但不确定如何将其打印为列表

我正在打印此表列表

        SELECT
        seq_no,
        type_big_category,
        body,
        status
        FROM DB_TABLE;

列表输出在 js文件中运行。

$(function() {

    $.ajax({
        url : "/dblistdata",
        type : "GET",
        dataType : "json",
        data: data,
        timeout: 10000
    }).done(function (result) {
        if(result.resultCode == "S000"){
            for (var i = 0; i < result.length; i++) {
                var tableBody =  '<tr>'
                        + '<td>' + result.messagelist[i].type_big_category + '</td>'
                        + '<td>' + result.messagelist[i].type_mid_category + '</td>'
                        + '<td>'
                        + '<label class="checkbox" for="checkbox' + i + '">'
                        + '<input type="checkbox" name="checkbox" id="checkbox' + i + '" checked="checked" />'
                        + '</label>'
                        + '</td>'
                        + '<td>'
                        +   '<textarea class="form-control push-text">"' + result.messagelist[i].body + '"</textarea>'
                        + '</td>'
                        + '<td>'
                        +   '<button type="button" class="btn btn-primary">save</button>'
                        +   '<button type="button" class="btn btn-default" id="deletebutton'+ i + '">delete</button>'
                        + '</td>'
                        + '</tr>';

                $('#tbody').append(tableBody);
                var btn[i] = document.getElementById('deletebutton[i]');
                btn[i].disabled = 'disabled';
            }
        }else{
            alert(result.resultMsg);
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    })

});

我必须在 jsp文件中显示该列表。

<form class="smart-form">
    <table class="tb-regist" id="eeMsg">
        <thead>
            <tr>
                <th>Sortation</th>
                <th>situation</th>
                <th>check</th>
                <th colspan="2">message</th>
            </tr>
        </thead>
        <tbody id="tbody">

        </tbody>
    </table>
</form>

not see

必须以这种方式输出。您如何打印出来?请帮我很多忙。

2 个答案:

答案 0 :(得分:0)

您可以使用for循环将数据提取到表中。您的ajax代码应如下所示。得到所有结果后,它将显示在您的表格中。

$(function() {
    $.ajax({
        url : "/dblistdata",
        type : "GET",
        dataType : "json",
        success : function(result) {
            console.log(result);

            for (var i = 0; i < result.length; i++) {
                var tableBody = "
                    <tr>
                        <td>" + result[i].seq_no + "</td>
                        <td>" + result[i].type_big_category + "</td>
                        <td>
                            <label class="checkbox" for="checkbox01">
                            <input type="checkbox" name="checkbox" id="checkbox01" checked="checked" />
                            </label>
                        </td>
                        <td>
                            <textarea class="form-control push-text">" + result[i].body + "</textarea>
                        </td>
                        <td>
                            <button type="button" class="btn btn-primary">save</button>
                            <button type="button" class="btn btn-default" id="deletebutton">dlete</button>
                        </td>
                    </tr>
                ";

                $('#tbody').append(tableBody);
            }
        }
    })
});

您的HTML代码应如下所示,

<form class="smart-form">
    <table class="tb-regist" id="eeMsg">
        <thead>
            <tr>
                <th>Sortation</th>
                <th>situation</th>
                <th>check</th>
                <th colspan="2">message</th>
            </tr>
        </thead>
        <tbody id="tbody">

        </tbody>
    </table>
</form>

我假设您正在使用JQuery。但是,如果不添加JQuery

答案 1 :(得分:0)

我看到您正在使用Java,所以可能您正在使用类似servlet的请求处理器。因此,至少有两种方法可以提出您的看法,第三种只是我认为有用的建议:

  • 将列表添加为JSP请求的属性,并使用JSTL
  • 通过异步javascript请求(即提取或XHR)获取列表
  • 使用第三方库(例如Boostrap表)

将列表添加为对JSP的请求的属性,并使用JSTL

Servlet

将列表添加到请求属性。

public void doGet( // or doPost
    HttpServletRequest req, 
    HttpServletResponse res
) throws ServletException, IOException  {
    List<Object> myList = new ArrayList<>();
    req.setAttribute("myList", myList);
}

JSP

通过列表遍历JSTL,并为表的每一行的每个单元格调用所需的任何对象属性。

<form class="smart-form">
    <table class="tb-regist" id="eeMsg">
        <thead>
            <tr>
                <th>Sortation</th>
                <th>situation</th>
                <th>check</th>
                <th colspan="2">message</th>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${ myList }" var="object">
                <tr>
                    <td>${ object.seq_no }</td>
                    <td>${ object.type_big_category }</td>
                    <td>
                        <label class="checkbox" for="checkbox01">
                            <input type="checkbox" 
                                   name="checkbox" 
                                   id="checkbox01" 
                                   checked="checked" />
                            <i/>
                        </label>
                    </td>
                    <td>
                        <textarea class="form-control push-text">body</textarea>
                    </td>
                    <td>
                        <button type="button" 
                                class="btn btn-primary">
                            save
                        </button>
                        <button type="button" 
                                class="btn btn-default"
                                id='deletebutton'>
                            delete
                        </button>
                    </td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
</form>

尽管不要忘记JSTL声明!

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

通过异步javascript请求(即提取或XHR)获取列表

Servlet

将列表添加到request属性中,但是可以使用org.json库中的org.json.JSONArray作为JSON格式。

public void doPost( // or doGet
    HttpServletRequest req, 
    HttpServletResponse res
) throws ServletException, IOException  {
    List<Object> myList = new ArrayList<>();
    JSONArray jsonArray = new JSONArray(myList);
    res.setContentType("application/json");
    res.getWriter().print(jsonArray);
    res.getWriter().flush();
    res.getWriter().close();
    res.flushBuffer();
}

JSP

只是静态HTML,表格将使用javascript构建。

<form class="smart-form">
    <table class="tb-regist" id="eeMsg">
        <thead>
            <tr>
                <th>Sortation</th>
                <th>situation</th>
                <th>check</th>
                <th colspan="2">message</th>
            </tr>
        </thead>
    </table>
</form>

JavaScript

将响应解析为JSON并进行迭代,以使用HTMLTableElement构建表。

// XHR post function
var sendXHRPost = void 0;
{
    sendXHRPost = function (url, params, callback) {
        var http = new XMLHttpRequest();
        http.open('POST', url, true);
        http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        http.onreadystatechange = function() {
            if (http.readyState === 4) {
                callback(http.status, http.responseText);
            }
        }
        http.send(params);
    }
}
// get your table data
var fetchTableData = void 0;
{
    fetchTableData = function () {
        sendXHRPost(
            'myURL', 
            // maybe you don't pass parameters to fetch your table?
            'parameterName=parameterValue', 
            function (responseStatus, responseText) {
                makeTable(responseStatus, JSON.parse(responseText);
            }
        );
    }
}
// formatter for your textarea cell
var textAreaCellFormatter = void 0;
{
    textAreaCellFormatter = function (rowId) {
        return '<textarea class="form-control push-text">'
            + rowId 
            + '</textarea>';
    }
}
// formatter for your buttons cell
var buttonsCellFormatter = void 0;
{
    buttonsCellFormatter = function (rowId) { 
        return  '<button type="button" '
            + 'class="btn btn-primary">'
            + 'save'
            + '</button>'
            + '<button type="button" '
            + 'class="btn btn-default" '
            + 'id="deletebutton'+rowId+'">'
            + 'delete'
            + '</button>';
    }
}
// build your table
var makeTable = void 0;
{
    makeTable = function (status, jsonResponse) {
        var table = document.getElementById("eeMsg");
        // Delete table content in case it was already loaded
        for (var i = 1 ; i < table.rows.length ; i++) {
            table.deleteRow(i); 
        }
        for (var i = 0 ; i < table.tBodies.length ; i++) {
            table.removeChild(table.tBodies[i]); 
        }
        // Create tbody
        var tBody = table.createTBody();
        // Handle internal server error
        if (status != 200) {
            var row = tBody.insertRow();
            var cell = row.insertCell(0);
            cell.colSpan = "4";
            cell.innerHTML = "Error while fetching data.";
        }
        // Handle no data found
        else if (jsonResponse.length === 0) {
            var row = tBody.insertRow();
            var cell = row.insertCell(0);
            cell.colSpan = "4";
            cell.innerHTML = "No data found.";
        }
        // All fine, build your table
        else {
            for(var i = 0 ; i < jsonResponse.length ; i++) {
                var row = tBody.insertRow();
                row.insertCell(0).innerHTML = jsonResponse[i].seq_no;
                row.insertCell(1).innerHTML = jsonResponse[i].type_big_category;
                row.insertCell(2).innerHTML = textAreaCellFormatter(i);
                row.insertCell(3).innerHTML = buttonsCellFormatter(i);
            }
        }
    }
}
// Execute your function on page loading.
(function () { fetchTableData(); })();

使用第三方库(例如Boostrap-tables

Servlet

上面也一样。

JSP

<!-- libs and css -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.15.2/dist/bootstrap-table.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/bootstrap-table@1.15.2/dist/bootstrap-table.min.js"></script>
<!-- your table in your body, not builded yet -->
<table id="eeMsg"
       data-toolbar="#toolbar"
       data-toggle="table"
       data-pagination="true"
       data-search="true"
       data-url="yourFetchURLWithJSONResponse">
    <thead>
        <tr>
            <th data-field="seq_no">Sortation</th>
            <th data-field="type_big_category">situation</th>
            <th>check</th>
            <th colspan="2">message</th>
        </tr>
    </thead>
</table>