簡體   English   中英

從控制器顯示jsp中的數據

[英]Display data's in jsp from controller

我正在一個項目下工作,該項目通過使用Spring Hibernate從數據庫顯示jsp表中的數據。 我成功通過休眠從DB獲取了所有數據,並將它們也發送到javascript函數。 但是問題是,來自控制器的數據是一個對象,並以字符串形式顯示在jsp表中。 我該怎么做?

我的控制器

@RequestMapping(value = "/view_all_record", method = RequestMethod.GET)
public @ResponseBody void getAllRecord(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
{
    JsonArray jsonArray = null;
    List<Customer> list = new ArrayList<Customer>();
    try
    {
        //Fetching data from DB by hibernate
        list = firstService.fetchList();

        Gson gson = new Gson();
        JsonElement element = gson.toJsonTree(list,  new TypeToken<List<Customer>>(){}.getType());
        jsonArray = element.getAsJsonArray();
        response.setContentType("application/json");
        response.getWriter().print(jsonArray);

    }catch(Exception e)
    {
        logger.error(e.getMessage());
    }
}

我的JSP

<input type="button" value="View All" id="showTable" class="showTable" name="showTable">

<div id="tablediv" class="tablediv">
    <table id="customerTable" class="customerTable">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Address</th>
            </tr>
         </thead>
         <tbody class="dataFetching">
         </tbody>
    </table>
</div>

我的劇本

<script type="text/javascript">
$(document).ready(function() {
    $("#tablediv").hide();
    $("#showTable").click(function(event){ 
        $.get('./firstController/view_all_record',function(responseJson) { 
            $("#customerTable").find("tr:gt(0)").remove();
            var table1 = $("#customerTable");
            $.each(responseJson, function(key,value) { 
                var rowNew= $("<tr><td></td><td></td><td></td><td></td></tr>");
                rowNew.children().eq(0).text(JSON.stringify(value['id'])); 
                rowNew.children().eq(1).text(JSON.stringify(value['address']));
                rowNew.children().eq(2).text(JSON.stringify(value['email']));
                rowNew.children().eq(3).text(JSON.stringify(value['name']));
                //rowNew.appenTo(table1);
            });
        });
        $("#tablediv").show();          
    });      
});

但是它在jsp表中沒有顯示任何值。

終於我解決了我的問題

var table1 = $("#customerTable");
$.each(responseJson, function(key,value) { 
    var rowNew = "<tr>"+
    "<td>"+JSON.stringify(value['id'])+"</td>"+
    "<td>"+JSON.stringify(value['name']).replace('"', '').replace('"', '')+"</td>"+
    "<td>"+JSON.stringify(value['email']).replace('"', '').replace('"', '')+"</td>"+
    "<td>"+JSON.stringify(value['address']).replace('"', '').replace('"', '')+"</td>"+
    "</tr>" 
    $(rowNew).appendTo("#customerTable");
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM