Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring MVC Project - Retrieving Population, Area and Region Details using Rest API
Next article icon

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

Last Updated : 28 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
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>       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">       <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>       <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>       <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.


Next Article
Spring MVC Project - Retrieving Population, Area and Region Details using Rest API

P

priyarajtt
Improve
Article Tags :
  • Java
  • Project
  • Java-Spring
  • Java-Spring-MVC
Practice Tags :
  • Java

Similar Reads

    Spring MVC - Custom Validation
    Validating user input is essential for any web application to ensure the processing of valid data. The Spring MVC framework supports the use of validation API. The validation API puts constraints on the user input using annotations and can validate both client-side and server-side. It provides stand
    8 min read
    Difference Between ApplicationContext and WebApplicationContext in Spring MVC
    Spring MVC framework enables separation of modules namely Model, View, and Controller, and seamlessly handles the application integration. This enables the developer to create complex applications also using plain Java Classes. The model object can be passed between view and controller using maps. W
    3 min read
    Difference Between @Component, @Repository, @Service, and @Controller Annotations in Spring
    Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. Here, we are goi
    4 min read
    Difference Between @Controller and @Service Annotation in Spring
    Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.  Spring @Control
    5 min read
    Difference Between @Controller and @RestController Annotation in Spring
    Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not directly affect the operation of the code they annotate. It does not change the action of the compiled program. Understanding the differ
    3 min read
    Spring MVC - @RequestParam Annotation
    The @RequestParam annotation is one of the most commonly used annotations in Spring MVC for handling HTTP request parameters. @RequestParam annotation enables Spring to extract input data that may be passed as a query, form data, or any arbitrary custom data. Key features of @RequestParam annotation
    5 min read
    Query String and Query Parameter in Spring MVC
    According to Wikipedia "A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML, choosing the appearance of a pag
    6 min read
    How to Make Post Request in Java Spring?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
    4 min read
    How to Make Delete Request in Spring?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
    4 min read
    How to Make get() Method Request in Java Spring?
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences