Problems showing data in the index.jsp with ajax

2

I have a code that does not work for me, I need the index.jsp autorefresque with the query a bd from servlet.

index.jsp

                                                                                    

     <title>WP Não Fechado</title>

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

      <style>
        body {
            padding-top: 70px;
            /* Required padding for .navbar-fixed-top. Remove if using .navbar-static-top. Change if height of navigation changes. */
        }
    </style>

</head>
<body>
       <!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
    <div class="container">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
    </div>
    <!-- /.container -->
</nav>

 <div>
    <div style="text-align:center">
            <img src="img/bar.PNG">
    </div>
</div>
<script type="text/javascript">
  (function() {
window.setInterval(function() {
    $.ajax({
        url: "ServletConsultData", //URL del servlet
        success: function(data) {
            $(data).each(function() {
                $('#tabla tbody').append('<tr></tr>');
                var row = $('#tabla tbody tr').last();
                var objeto = $(this);
                row.append('<td>' + objeto.propiedad + '</td>');
            });
        },
        dataType: "json",
   });
}, 10000);

}) ();     

    <table id="tabla">
    <thead>
        <tr>
            <th>ac</th>
            <th>assmbl</th>
            <th>barcode</th>
            <th>wp name</th>
            <th>loc wp</th>
            <th>status wp</th>
            <th>wp sched end date</th>
            <th>flight no</th>
            <th>sched departure</th>
            <th>loc departure</th>
            <th>sched arrival</th>
            <th>loc arrival</th>
         </tr>
    </thead>
    <tbody>
    <td></td>
    </tbody>

</body>

ServletConsultData.java

 @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try{
    Consulta consulta = new Consulta();
    LinkedList ResultConsult = consulta.getDatos();

    if(!ResultConsult.isEmpty()){
        String json = new Gson().toJson(ResultConsult);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json); 
    }else{  
        response.sendRedirect("test.jsp");     
        processRequest(request, response);
     }
    } catch (Exception e){
        System.out.println(e.getMessage());
    }
}

app-ajax.js

$.get("/ServletConsultData", function(responseJson) {          // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
    var $table = $("<table>").appendTo($("#somediv")); // Create HTML <table> element and append it to HTML DOM element with ID "somediv".
    $.each(responseJson, function(index, product) {    // Iterate over the JSON array.
        $("<tr>").appendTo($table)                     // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
            .append($("<td>").text(product.ac))        // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
       //     .append($("<td>").text(product.name))      // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
       //     .append($("<td>").text(product.price));    // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
    });
});

shows me the next error in the servlet

type Exception report
messageInternal Server Error
descriptionThe server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.1.1 logs.

and in the js

type Status report
messageNot Found
description The requested resource is not available.

the result is

    
asked by elsa 15.06.2016 в 18:46
source

1 answer

1
  • Instead of window#setTimeout use window#setInterval :

    (function() {
        fetch(); // consulta inicial
        // esto se ejecutará cada 30s pero
        // con un delay inicial de 30s
        window.setInterval(function() {
           fetch();
        }, 30000);
    
        function fetch() {
            $.get('/ServletConsultData', function(data) {
                $(data).each(function() {
                    $('#tabla tbody').empty();
                    $('#tabla tbody').append('<tr></tr>');
                    let objeto = $(this)[0];
                    let row = $('#tabla tbody tr').last();
                    row.append('<td>${objeto.ac}</td>');
                    row.append('<td>${objeto.assmbl}</td>');
                    row.append('<td>${objeto.flight_no}</td>');
                    row.append('<td>${objeto.loc_arrival}</td>');
                    // lo mismo con las  demás propiedades
                });
            });
        }
    })();
    

    Note: This is greatly simplified if you use a framework like Angular. The addition of the objects to the table would be automatic.

  • Why do you call processRequest in doGet ? If the GET request should only update and return records, you do not need to call processRequest because it can affect the operation if it has code.

  • Your error is a NullPointerException as indicated by the stack trace:

    java.lang.NullPointerException
    

    However, the tracking you have placed represents very little information. So, with the little code you have put, it could be that:

    • Consulta has not been initialized.
    • ResultConsult is likely to be null.
  • answered by 15.06.2016 / 19:23
    source