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 - Get Exchange Rate Values using REST API

Fetching exchange rate values using a REST API in a Spring MVC application involves calling an external API service, parsing the returned data, and presenting it to the user. Here's a basic guide on how to do it:

1. Set up Spring Boot with Spring MVC

Start with the Spring Initializer or add the necessary dependencies to your pom.xml:

<dependencies>
    <!-- Spring Boot Web Starter for Spring MVC -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- For calling REST APIs -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
</dependencies>

2. Create a Service to Fetch Exchange Rate

@Service
public class ExchangeRateService {

    @Autowired
    private WebClient.Builder webClientBuilder;

    public Double getExchangeRate(String baseCurrency, String targetCurrency) {
        String apiUrl = "https://api.exchangeratesapi.io/latest?base=" + baseCurrency;

        // Fetch exchange rates
        Map<String, Object> response = webClientBuilder.build()
            .get()
            .uri(apiUrl)
            .retrieve()
            .bodyToMono(Map.class)
            .block();

        if (response != null && response.containsKey("rates")) {
            Map<String, Double> rates = (Map<String, Double>) response.get("rates");
            return rates.get(targetCurrency);
        }

        return null;
    }
}

Here, I've used WebClient from the spring-boot-starter-webflux module to fetch data from the REST API. This is just an example; the actual API and its parameters might vary.

3. Create a Controller

@Controller
@RequestMapping("/exchange-rate")
public class ExchangeRateController {

    @Autowired
    private ExchangeRateService exchangeRateService;

    @GetMapping
    public String getRateForm() {
        return "rateForm";  // Return your form view
    }

    @PostMapping
    public String fetchRate(@RequestParam String baseCurrency, @RequestParam String targetCurrency, Model model) {
        Double rate = exchangeRateService.getExchangeRate(baseCurrency, targetCurrency);
        model.addAttribute("rate", rate);
        return "rateResult";  // Return your result view
    }
}

4. Create Views (e.g., with Thymeleaf)

rateForm.html:

<form action="/exchange-rate" method="post">
    Base Currency: <input type="text" name="baseCurrency">
    Target Currency: <input type="text" name="targetCurrency">
    <input type="submit" value="Get Rate">
</form>

rateResult.html:

<p>Exchange Rate: <span th:text="${rate}"></span></p>

5. Run & Test

Now, run your Spring Boot application and navigate to /exchange-rate. Enter the base and target currencies to see the exchange rate.

Note: This is a simplified example. In a real-world application, you would need error handling, possibly caching, and other considerations. Also, make sure you understand the terms of use for any external API you are using. Some might have usage limits or require API keys.

  1. Spring MVC Exchange Rate REST API Example:

    • Description: This is a basic example demonstrating how to use a REST API to fetch currency exchange rates in a Spring MVC application. It typically involves making a request to an external API that provides exchange rate information.

    • Code Snippet: (Controller Method with RestTemplate)

      @Controller
      public class ExchangeRateController {
          @GetMapping("/getExchangeRate")
          @ResponseBody
          public String getExchangeRate() {
              // Use RestTemplate to make a request to the exchange rate API
              // Parse the response and return relevant information
              return "Exchange rate: 1 USD to 1.2 EUR";
          }
      }
      
  2. Using REST API to Get Currency Exchange Rates in Spring MVC:

    • Description: This example extends the basic exchange rate example by using a specific REST API to get live currency exchange rates.

    • Code Snippet: (Controller Method with Exchange Rate API)

      @Controller
      public class ExchangeRateController {
          @GetMapping("/getExchangeRate")
          @ResponseBody
          public String getExchangeRate() {
              // Use RestTemplate to make a request to a currency exchange rate API
              // Parse the response and return relevant information
              return "Exchange rate: 1 USD to 1.25 EUR";
          }
      }
      
  3. Consuming Exchange Rate API in Spring MVC:

    • Description: This example focuses on the client-side of consuming an external exchange rate API using Spring's RestTemplate.

    • Code Snippet: (RestTemplate Usage)

      RestTemplate restTemplate = new RestTemplate();
      ResponseEntity<String> response = restTemplate.getForEntity("https://api.exchangerateapi.com/v4/latest/USD", String.class);
      String exchangeRate = response.getBody();
      
  4. RESTful Exchange Rate Endpoint in Spring MVC:

    • Description: This example demonstrates creating a RESTful endpoint in Spring MVC that provides currency exchange rate information.

    • Code Snippet: (RestController)

      @RestController
      public class ExchangeRateRestController {
          @GetMapping("/api/exchangeRate")
          public ResponseEntity<String> getExchangeRate() {
              // Logic to fetch and return exchange rate information
              return ResponseEntity.ok("Exchange rate: 1 USD to 1.3 EUR");
          }
      }
      
  5. Retrieving Exchange Rates with Spring RestTemplate:

    • Description: This example showcases the usage of RestTemplate to retrieve exchange rates from an external API in a Spring MVC application.

    • Code Snippet: (Service Class)

      public class ExchangeRateService {
          private final String exchangeRateApiUrl = "https://api.exchangerateapi.com/v4/latest/USD";
      
          public String getExchangeRate() {
              RestTemplate restTemplate = new RestTemplate();
              ResponseEntity<String> response = restTemplate.getForEntity(exchangeRateApiUrl, String.class);
              return response.getBody();
          }
      }
      
  6. Spring MVC Currency Converter with REST API:

    • Description: This example combines exchange rate information from a REST API with a currency conversion feature in a Spring MVC application.

    • Code Snippet: (Currency Conversion Controller)

      @Controller
      public class CurrencyConverterController {
          @Autowired
          private ExchangeRateService exchangeRateService;
      
          @GetMapping("/convertCurrency")
          @ResponseBody
          public String convertCurrency(@RequestParam("amount") double amount, @RequestParam("targetCurrency") String targetCurrency) {
              // Fetch exchange rate and perform currency conversion
              String exchangeRate = exchangeRateService.getExchangeRate();
              // Convert the amount to the target currency
              return "Converted amount: " + (amount * Double.parseDouble(exchangeRate)) + " " + targetCurrency;
          }
      }
      
  7. External API Integration in Spring MVC:

    • Description: This example illustrates the integration of an external API (exchange rate API) into a Spring MVC application.

    • Code Snippet: (Service Integration)

      public class ExchangeRateService {
          private final String exchangeRateApiUrl = "https://api.exchangerateapi.com/v4/latest/USD";
      
          public String getExchangeRate() {
              RestTemplate restTemplate = new RestTemplate();
              ResponseEntity<String> response = restTemplate.getForEntity(exchangeRateApiUrl, String.class);
              return response.getBody();
          }
      }
      
  8. Fetching Real-Time Exchange Rates in Spring MVC:

    • Description: This example focuses on fetching real-time exchange rates from an external API and displaying them in a Spring MVC application.

    • Code Snippet: (Controller Method)

      @Controller
      public class ExchangeRateController {
          @Autowired
          private ExchangeRateService exchangeRateService;
      
          @GetMapping("/realTimeExchangeRates")
          public String showRealTimeExchangeRates(Model model) {
              String exchangeRates = exchangeRateService.getExchangeRate();
              model.addAttribute("exchangeRates", exchangeRates);
              return "exchangeRates";
          }
      }
      
  9. Building a Currency Converter with Spring MVC and REST:

    • Description: This example combines the features of a currency converter with real-time exchange rates obtained from an external REST API.

    • Code Snippet: (Currency Converter Controller)

      @Controller
      public class CurrencyConverterController {
          @Autowired
          private ExchangeRateService exchangeRateService;
      
          @GetMapping("/currencyConverter")
          public String showCurrencyConverter(Model model) {
              String exchangeRates = exchangeRateService.getExchangeRate();
              model.addAttribute("exchangeRates", exchangeRates);
              return "currencyConverter";
          }
      
          // Additional methods for handling currency conversion
      }