Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

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

To retrieve population, area, and region details for a given country using a REST API, we'll need to do the following steps:

  1. Set Up Dependencies: We'll use Spring Boot for the project setup and Spring's RestTemplate to consume a REST API.

  2. Consume REST API: This involves calling a third-party API (or any available API) to get the desired details.

  3. Display in View: Once the details are fetched, we'll display them in a JSP page.

1. Project Setup:

Start with the Spring Initializr or any other means to generate a Spring Boot project. Include spring-boot-starter-web for web capabilities.

2. Consume REST API:

Let's assume you're using a fictional REST API endpoint https://api.example.com/country/{countryName} that returns country details in JSON format:

{
    "name": "CountryName",
    "population": "1234567",
    "area": "12345",
    "region": "RegionName"
}

Create a DTO:

public class Country {
    private String name;
    private String population;
    private String area;
    private String region;
    
    // Getters, setters and other methods...
}

Use RestTemplate to fetch country details:

@Service
public class CountryService {

    private static final String API_URL = "https://api.example.com/country/";

    public Country getCountryDetails(String countryName) {
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.getForObject(API_URL + countryName, Country.class);
    }
}

3. Controller and View:

Now, create a controller to handle requests and responses:

@Controller
@RequestMapping("/country")
public class CountryController {

    @Autowired
    private CountryService countryService;

    @GetMapping("/{countryName}")
    public String getCountryDetails(@PathVariable String countryName, Model model) {
        Country country = countryService.getCountryDetails(countryName);
        model.addAttribute("country", country);
        return "countryDetails";
    }
}

Finally, create a JSP view (countryDetails.jsp) to display the details:

<h1>Details for ${country.name}</h1>
<p><strong>Population:</strong> ${country.population}</p>
<p><strong>Area:</strong> ${country.area}</p>
<p><strong>Region:</strong> ${country.region}</p>

Final Thoughts:

  • Error handling has been omitted for simplicity but should be included (e.g., when the country isn't found).

  • Cache responses when applicable to reduce unnecessary API calls.

  • Don't forget to add exception handling, especially for cases where the third-party API might be down.

  • If the API requires authentication, you'd also have to add relevant headers or authentication methods to your RestTemplate call.

  1. Spring MVC Population, Area, Region Details REST API Example:

    • Description: This is a basic example illustrating how to retrieve population, area, and region details using a REST API in a Spring MVC application.

    • Code Snippet: (Controller)

      @RestController
      @RequestMapping("/demographic")
      public class DemographicController {
      
          @Autowired
          private DemographicService demographicService;
      
          @GetMapping("/details")
          public ResponseEntity<DemographicDetails> getDemographicDetails() {
              DemographicDetails details = demographicService.fetchDemographicDetails();
              return new ResponseEntity<>(details, HttpStatus.OK);
          }
      }
      

      (Service)

      @Service
      public class DemographicService {
      
          @Autowired
          private RestTemplate restTemplate;
      
          public DemographicDetails fetchDemographicDetails() {
              String apiUrl = "https://api.example.com/demographic/details";
              return restTemplate.getForObject(apiUrl, DemographicDetails.class);
          }
      }
      

      (Model)

      public class DemographicDetails {
      
          private long population;
          private double area;
          private String region;
      
          // Getter and Setter
      }
      
  2. Retrieving Data with Spring RestTemplate in Spring MVC:

    • Description: This example illustrates how to retrieve data using Spring RestTemplate in a Spring MVC application.

    • Code Snippet: (Service)

      @Service
      public class DemographicService {
      
          public DemographicDetails fetchDemographicDetails() {
              String apiUrl = "https://api.example.com/demographic/details";
              RestTemplate restTemplate = new RestTemplate();
              return restTemplate.getForObject(apiUrl, DemographicDetails.class);
          }
      }