简体   繁体   中英

JSP retrieve data from API

I am new in jsp, and I have a spring boot API on server, how can I retrieve data from api to jsp? the link is something like: http://111.111.1.111:8080/user/getallusers this is what i get from postman: image

Just treat it the same as any HTTP network request you make using java. You can use Java's built in HTTP client library.

Here is an example. (For JSP you can always enclose the code in scriptlet tags <% %> but I would recommend making the call using servlet and then sending the response to jsp)

URL url = new URL("http://111.111.1.111:8080/user/getallusers ");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");

if (conn.getResponseCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "
            + conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
    (conn.getInputStream())));

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
    System.out.println(output);
}

For more insight you can refer to this link https://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/

Hope it helps.

You can make use of Java script to invoke API:

var request = new XMLHttpRequest();

request.open('GET', 'http://111.111.1.111:8080/user/getallusers', true);
request.onload = function () {

 var data = JSON.parse(this.response);

  if (request.status >= 200 && request.status < 400) {
    data.forEach(user => {
      console.log(user.name_en);// Alternatively manipulate DOM with record
    });
  } else {
    console.log('error occurred. Please try again');
  }
}

request.send();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM