5.5 Create an HTML Page to Display Results

This section describes the steps to create a HTML page that displays the list of employees retrieved from the database.

Class Name:src/main/webapp/listAll.html

Github Location: listAll.html

Steps to create the HTML page:

  1. Create the title, stylesheet, and body for the HTML page.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>List all Employees</title>
    <link rel="stylesheet" type="text/css" href="css/app.css" >
    </head>
  2. Inside the <script> tag, declare few variables for the URL and HTTPRequest.
    <script>
    var xmlhttp = new XMLHttpRequest();
    var url = "WebController";
  3. Define the action to be performed when the requests are sent, that is, when the links for each one of the functionalities is selected.
    
    xmlhttp.onreadystatechange=function() {
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
           processResponse(xmlhttp.responseText);
         }
       }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
    
  4. Create the function processResponse() to display JSON results on HTML page.
    
    function processResponse(response) {
    // Process the JSON response into an array.   
    var arr = JSON.parse(response);
    var i;
    var out - "<table>";
    keys = Object.keys(arr[0]);
    //Print headers
    out += "<tr>"
    for(i = 0; i < keys.length; ++i) {
      out += "<th>"+keys [i]+"</th>"
    }
    out += "</tr>";
    // Print values
    for(j = 0; j < arr.length; j++) {  
      out += "<tr>"
      for(i = 0; i < keys.length; ++i) {
        out += "<td>"+arr[j][keys[i]]+"</td>"
      }
    out += "</tr>"
    }
    out += "</table>";
    document.getElementById("id-emp").innerHTML = out;
    }