0

I have created a Spring-boot REST service and It's working as expected and returned JSON array as response.

End Point:

    https://localhost:8081/displayProduct?productId=1234

Output(Example):

{
 "dataSet":[
            { 
              "productName": "mobile", 
              "product_OS":"Android"
            },
            {
              "productName": "Laptop", 
              "product_OS":"Linux"
            }
         ]
 }

Code:

    @ApiOperation(responseContainer = "request", response = HadoopCALDTO.class, value = "shows_component")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @RequestMapping(value = "/displayProduct", produces = MediaType.APPLICATION_JSON, method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> getETLResponse(@RequestParam("productId") String productId)
            throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        Map<String, String> dataError = new HashMap<String, String>();
        String response = Utils.sendGET(ConfigReader.getProperty("getBaseURL")
                + productId);
        data = Utils.getHttpUrl(response, productId);
        System.out.println(data.size());

        if (Utils.getDataError().size() > 0) {
            Utils.getDataError().clear();
        }
        for (Map.Entry<String, String> getValue : data.entrySet()) {
            String tempUrl = Utils.replaceUrl(getValue.getKey());
            System.out.println(tempUrl);
            String tempresponse = Utils.sendGET(tempUrl);
            Utils.getErrorData(tempresponse);
        }

        System.out.println(dataError.size());

        String finalResponse = Utils.buildJSONSkelton(Utils.getDataError());

        System.out.println(finalResponse);

        return new ResponseEntity<String>(finalResponse,HttpStatus.OK);
    }

The above code works perfectly fine. I tested the End point in postman which returned 200 Ok response and proper response body as expected.

The above code I have a JSON that I stored in "finalResponse" string variable and showing it as response body (Sample output mentioned above).

I'm getting the productId is the input from user and getting the result and publishing the data. And I just want to do this from Responsive HTML page. Like I just need a text box where the user needs to enter the product id and click submit button. And the value is pass into the REST client and displaying the JSON array result as table view in HTML page.

Really I don't have any idea how to kick start this. I'm very new to web application development, and not sure how to achieve this. Googled about Spring MVC and some library called xmlhttprequest javascript. But not sure how to get the value from text field and pass it to REST client and wait for respose (It takes close to 20 seconds to fetch all the productID from hadoop) JSON array and display the result as dynamic HTML table as like below.

S.No || Product_Name || Product_OS
1 || Mobile || Android
2 || Laptop || Linux

Please can someone help me on this.

Updates:

I just tried the below steps to hit the REST client and get the response as dynamic html table

<html>
<head>
<script type="text/javascript">
function myFunction() {
var name = document.getElementById("name").value;
var dataString = 'calId=' + name ;

if (name == '') {
alert("Please Fill All Fields");
} else {
 $.ajax({
 url: 'http://localhost:8081/api/displayProduct?',
 data: dataString
 dataType: 'json',
 success: function(data) {
    for (var i=0; i<data.length; i++) {
        var row = $('<tr><td>' + data[i].productName+ '</td><td>' + 
 data[i].product_os + '</td> </tr>');
        $('#myTable').append(row);
    }
 },
 error: function(jqXHR, textStatus, errorThrown){
    alert('Error: ' + textStatus + ' - ' + errorThrown);
 }
 });
}
}
</script>
</head>
<body>
<form id="form" name="form">
<h3>Fill Your Information!</h3>
<div>
<label>Name :</label>
<input id="name" type="text">

<input id="submit" onclick="myFunction()" type="button" value="Submit">

</div>
</form>
</body>
</html>

<table id="myTable">
 <tr>
    <th>Zipcode</th>
    <th>City</th>
    <th>County</th>
 </tr>
</table>

Observed below Error message:

MyTest_sta.html:39 Uncaught ReferenceError: myFunction is not defined
    at HTMLInputElement.onclick (MyTest_sta.html:39)

enter image description here

ArrchanaMohan
  • 2,314
  • 4
  • 36
  • 84

1 Answers1

0

Please find below code snippet, here I am rendering ajax response into a table, you can probably make this ajax call attach to any event/ form submit

HTML:

<form id="form" name="form">
<h3>Fill Your Information!</h3>
<div>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="email" type="text">

<input id="submit" onclick="myFunction()" type="button" value="Submit">
</div>
</form>

<table id="myTable">
 <tr>
    <th>Zipcode</th>
    <th>City</th>
    <th>County</th>
 </tr>
</table>

JS:

function myFunction() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var dataString = 'name1=' + name + '&email1=' + email;

if (name == '' || email == '') {
alert("Please Fill All Fields");
} else {
 $.ajax({
 url: 'https://localhost:8081/displayProduct?productId=1234',
 data: dataString
 dataType: 'json',
 success: function(data) {
    for (var i=0; i<data.length; i++) {
        var row = $('<tr><td>' + data[i].zipcode+ '</td><td>' + 
 data[i].city + '</td> 
 <td>' + data[i].county + '</td></tr>');
        $('#myTable').append(row);
    }
 },
 error: function(jqXHR, textStatus, errorThrown){
    alert('Error: ' + textStatus + ' - ' + errorThrown);
 }
 });
}
}
Sarvesh Mahajan
  • 914
  • 7
  • 16
  • Sorry. My requirement is not just display the JSON array into HTML. I'm not sure how to get the input from HTML and pass it to REST client and display the response in dynamic table. – ArrchanaMohan Dec 17 '19 at 18:45
  • @ArrchanaMohan Please find updated code snippet, I guess now you will get an idea of how to retrieve values from form fields in a simpler way – Sarvesh Mahajan Dec 17 '19 at 18:58
  • Thanks for quick response. Let me check and update you. – ArrchanaMohan Dec 17 '19 at 19:00
  • I just updated my question with latest finds. I'm not able to call the myFunction() js in html. Can you please share some piece of running code. So that I will modify the same as per my requirement. Thanks in advance. – ArrchanaMohan Dec 17 '19 at 19:35
  • Also the 1234 product Id I wish to get it from text field. Because based on that product Id the result will change. – ArrchanaMohan Dec 17 '19 at 19:37
  • then you can also create url dynamically, `var productId = document.getElementById("prodid").value; var url = 'https://localhost:8081/displayProduct?productId='+productId ` and assign this url to url for ajax call – Sarvesh Mahajan Dec 17 '19 at 19:44
  • @ArrchanaMohan Well I added everything you needed to answer in this post, but still you can follow fiddle link for sample code: https://jsfiddle.net/smahajan89/135Lsz8u/6/ – Sarvesh Mahajan Dec 17 '19 at 20:27
  • Getting the below error message when I tried to hit the service "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. " can you please help me – ArrchanaMohan Dec 18 '19 at 23:25
  • This might be a CORS error, please read this article for better understanding: https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-get-a-no-access-control-allow-origin-header-is-pr – Sarvesh Mahajan Dec 20 '19 at 19:41
  • @ArrchanaMohan, appreciate if you can vote, if it solves your problem, thanks – Sarvesh Mahajan Dec 21 '19 at 05:46