Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
Like Article
  • Last Updated : 28 Sep, 2022
Improve Article
Save Article
Like Article

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<any capital of a country>


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



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


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;
@ComponentScan(basePackages = { "" })
public class AppConfig {
    public InternalResourceViewResolver resolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        return resolver;


public class SpringMvcDispatcherServletInitializer extends
          AbstractAnnotationConfigDispatcherServletInitializer {
    protected Class<?>[] getRootConfigClasses() {
        return null;
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { AppConfig.class };
    protected String[] getServletMappings() {
        return new String[] { "/" };


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
public class CountryController {
    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("area", area);
        return outputJsonObject;
    private JsonObject getDetails(String capital)
        throws IOException
        StringBuilder responseData = new StringBuilder();
        JsonArray jsonArray = null;
        URL url = null;
        url = new URL(
            + capital);
        JsonObject jsonObject = null;
        HttpURLConnection con
            = (HttpURLConnection)url.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        int responseCode = con.getResponseCode();
            "\nSending 'GET' request to URL : " + url);
        try (BufferedReader in
             = new BufferedReader(new InputStreamReader(
                 con.getInputStream()))) {
            String line;
            while ((line = in.readLine()) != null) {
            jsonArray = new Gson().fromJson(
                responseData.toString(), JsonArray.class);
            jsonObject = jsonArray.get(0).getAsJsonObject();
        return jsonObject;



<!DOCTYPE html>
<html lang="en">
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <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;
      <div class="main-form" id="main-form">
            <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 class="form-group">
               <button onclick="loadData()" class="btn btn-primary btn-block">Find Capital Details</button>
      <div class="profile-area hideElement" id="profile-area">
            <div id="loader" class="hideElement">
               <div class="spinner-border" role="status">
                  <span class="sr-only">Loading...</span>
            <div id="profile" class="hideElement">
               <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>
      function loadData() {
          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 =;
                      document.getElementById("region").innerHTML = jsonResponse.region;
                      document.getElementById("subRegion").innerHTML = jsonResponse.subRegion;
                      document.getElementById("area").innerHTML = jsonResponse.area;
                      document.getElementById("population").innerHTML = jsonResponse.population;
    "GET", "getCountryDetailsByCapital?capital=" + capital, true);
          } else {
              console.log("Enter capital...")

On running index.jsp:

On running index.jsp





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.

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!