Spring MVC Project - Retrieving Population, Area and Region Details using Rest API
Last Updated : 28 Sep, 2022
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:
As a Maven Spring MVC project, let us see how to get the details and render in screen
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:
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.
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