Open In App

Spring MVC Project – Retrieving Population, Area and Region Details using Rest API

Improve
Improve
Like Article
Like
Save
Share
Report

REST API is more popular nowadays as we can able to get a variety of information like Population, Area, region, sub-region, etc., One such REST API that we are going to see here is

https://restcountries.com/v3.1/capital/<any capital of a country>

Example:

https://restcountries.com/v3.1/capital/delhi

Corresponding JSON Response:

Corresponding JSON Response

 

As a Maven Spring MVC project, let us see how to get the details and render in screen

Project Structure:

Project Structure

 

pom.xml

Let us see the main configuration as well as the Controller file

AppConfig.java

Java




import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
  
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.country.Country_Rest_API" })
public class AppConfig {
  
    @Bean
    public InternalResourceViewResolver resolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
  
}


SpringMvcDispatcherServletInitializer.java

Java




import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
  
public class SpringMvcDispatcherServletInitializer extends
          AbstractAnnotationConfigDispatcherServletInitializer {
   
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }
   
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { AppConfig.class };
    }
   
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
   
}


CountryController.java

Java




import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
  
@Controller
public class CountryController {
  
    @RequestMapping("/getCountryDetailsByCapital")
    public @ResponseBody
    JsonObject getCountryDetailsByCapital(String capital)
        throws IOException
    {
  
        JsonObject jsonObject = new JsonObject();
        jsonObject = getDetails(capital);
        JsonObject outputJsonObject = new JsonObject();
        capital = jsonObject.get("capital").toString();
        String region = jsonObject.get("region").toString();
        String subRegion
            = jsonObject.get("subregion").toString();
        String area = jsonObject.get("area").toString();
        String population
            = jsonObject.get("population").toString();
  
        outputJsonObject.addProperty("capital", capital);
        outputJsonObject.addProperty("region", region);
        outputJsonObject.addProperty("subRegion",
                                     subRegion);
        outputJsonObject.addProperty("area", area);
        outputJsonObject.addProperty("population",
                                     population);
  
        return outputJsonObject;
    }
  
    private JsonObject getDetails(String capital)
        throws IOException
    {
  
        StringBuilder responseData = new StringBuilder();
        JsonArray jsonArray = null;
        URL url = null;
        url = new URL(
            "https://restcountries.com/v3.1/capital/"
            + capital);
        JsonObject jsonObject = null;
        HttpURLConnection con
            = (HttpURLConnection)url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        int responseCode = con.getResponseCode();
        System.out.println(
            "\nSending 'GET' request to URL : " + url);
        try (BufferedReader in
             = new BufferedReader(new InputStreamReader(
                 con.getInputStream()))) {
  
            String line;
  
            while ((line = in.readLine()) != null) {
                responseData.append(line);
            }
  
            jsonArray = new Gson().fromJson(
                responseData.toString(), JsonArray.class);
            jsonObject = jsonArray.get(0).getAsJsonObject();
        }
        return jsonObject;
    }
}


index.jsp

HTML




<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>CountryDetails</title>
      <style type="text/css">
         .main-form, .profile-area {
         width: 340px;
         }
         .main-form {
         margin: 50px auto 0px;
         }
         .profile-area {
         margin: 10px auto;
         }
         .main-form section, .profile-area section {
         margin-bottom: 15px;
         background: #f7f7f7;
         box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
         }
         .main-form section {
         padding: 30px;
         }
         .profile-area section {
         padding: 30px 30px 30px;
         }
         .profile-area section > div {
         text-align: center;
         }
         .main-form h3 {
         margin: 0 0 15px;
         }
         .form-control, .btn {
         min-height: 38px;
         border-radius: 2px;
         }
         .btn {
         font-size: 15px;
         font-weight: bold;
         }
         .hideElement {
         display: none;
         }
      </style>
   </head>
   <body>
      <div class="main-form" id="main-form">
         <section>
            <h5 class="text-center">Enter your capital</h5>
            <div class="form-group">
               <input id="capital" type="text" class="form-control" placeholder="Enter capital here..." required="required">
            </div>
            <div class="form-group">
               <button onclick="loadData()" class="btn btn-primary btn-block">Find Capital Details</button>
            </div>
         </section>
      </div>
      <div class="profile-area hideElement" id="profile-area">
         <section>
            <div id="loader" class="hideElement">
               <div class="spinner-border" role="status">
                  <span class="sr-only">Loading...</span>
               </div>
            </div>
            <div id="profile" class="hideElement">
               <br><br>
               <p><strong>Region    : </strong><span id="region"></span></p>
               <p><strong>SubRegion : </strong><span id="subRegion"></span></p>
               <p><strong>Area      : </strong><span id="area"></span></p>
               <p><strong>Population: </strong><span id="population"></span></p>
            </div>
         </section>
      </div>
   </body>
   <script>
      function loadData() {
          document.getElementById("profile-area").classList.remove("hideElement");
          document.getElementById("loader").classList.remove("hideElement");
          document.getElementById("profile").classList.add("hideElement");
        
          var capital = document.getElementById("capital").value;
        
      var otherCurrency1,otherCurrency2;
          if(capital != "" && capital != null) {
              var xhttp = new XMLHttpRequest();
              xhttp.onreadystatechange = function() {
                  if (this.readyState == 4 && this.status == 200) {
                      var jsonResponse = JSON.parse(this.responseText);
                      document.getElementById("capital").innerHTML = jsonResponse.capital;
                      document.getElementById("region").innerHTML = jsonResponse.region;
                      document.getElementById("subRegion").innerHTML = jsonResponse.subRegion;
                      document.getElementById("area").innerHTML = jsonResponse.area;
                      document.getElementById("population").innerHTML = jsonResponse.population;
                      
                      document.getElementById("loader").classList.add("hideElement");
                      document.getElementById("profile").classList.remove("hideElement");
                  }
              };
              xhttp.open("GET", "getCountryDetailsByCapital?capital=" + capital, true);
              xhttp.send();
              console.log("done");
          } else {
              console.log("Enter capital...")
          }
      }
   </script>
</html>


On running index.jsp:

On running index.jsp

 

Output:

Output

 

We can find the detail for any capital. Actually, only a few pieces of information are shown here. But as mentioned in the JSON response, the details are retrieved.



Last Updated : 28 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads