Building a Currency Exchange App with Spring Boot, Thymeleaf and Bootstrap

Prerequest

Read part 1 here first: https://nerdic-coder.com/2024/06/06/seamlessly-integrate-a-currency-exchange-api-into-your-spring-boot-application/

Step 1: Setting Up the Currency Exchange Form

In this tutorial, we’ll be building a currency exchange application using Spring BootThymeleaf and Bootstrap.

First, let’s set up the form in our Thymeleaf template. We’ll start with a basic form structure, including input fields for the “from” and “to” currencies.

  1. Create a form element in your Thymeleaf template.
  2. Create two dropdown menus (select elements) for the “from” and “to” currencies, using a loop to populate the options from a list of available currencies.
  3. Add labels for each input field to improve the user experience.

Your form should now look something like this:

<form>
  <div class="form-group">
    <label for="from">From</label>
    <select class="form-control" id="from" name="from">
      <option th:each="quote : ${quotes}" th:value="${quote}">[[${quote}]]</option>
    </select>
  </div>
  <div class="form-group">
    <label for="to">To</label>
    <select class="form-control" id="to" name="to">
      <option th:each="quote : ${quotes}" th:value="${quote}">[[${quote}]]</option>
    </select>
  </div>
  <button type="submit" class="btn btn-primary">Convert</button>
</form>

Step 2: Implementing the Currency Conversion Logic

Now that we have the form set up, let’s create the backend logic to handle the currency conversion. We’ll need to create a new method in our currency service to perform the conversion, and then a controller method to handle the form submission.

  1. In your currency service, add a new method to perform the currency conversion. This method should take the “from” currency, “to” currency, and return the converted value.
  2. In your controller, create a new method that will handle the form submission. This method should:
    • Retrieve the “from” currency, “to” currency from the form submission.
    • Call the currency conversion method in the service to get the converted value.
    • Add the converted value to the model, so it can be displayed in the Thymeleaf template.

Your currency service method might look something like this:

public String getQuote(String from, String to, double amount) throws IOException {
    AsyncHttpClient client = new DefaultAsyncHttpClient();
    try {
        Response response = client.prepare("GET", "https://currency-exchange.p.rapidapi.com/exchange?from=" + from + "&to=" + to + "&q=" + amount)
.setHeader("X-RapidAPI-Key", "c0e2c8b545msh80ba37bc0f8ec71p1d8f85jsn897bd31f95e6")
.setHeader("X-RapidAPI-Host", "currency-exchange.p.rapidapi.com")
.execute()
.toCompletableFuture()
.join();

client.close();
String responseBody = response.getResponseBody();
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(responseBody, String.class);
} finally {
client.close();
} }

And your controller method might look like this:

@GetMapping("/")
public String getQuotesPage(
@RequestParam(value = "from", required = false) String fromCurrency,
@RequestParam(value = "to", required = false) String toCurrency,
Model model) throws IOException { String quote = null; if (amount != null && fromCurrency != null && toCurrency != null) { quote = currencyService.getQuote(fromCurrency, toCurrency, amount);
}
final List<String> quotes = currencyService.listQuotes();
model.addAttribute("quotes", quotes);
model.addAttribute("quote", quote);
model.addAttribute("from", fromCurrency);
model.addAttribute("to", toCurrency);
return "index"; }

Step 3: Displaying the Converted Value

Now that we have the backend logic set up, we can update our Thymeleaf template to display the converted value. We’ll add a new section to the template that will only be shown if a conversion has been performed.

  1. In your Thymeleaf template, add a new section that will display the converted value, if it exists.
  2. Use a Thymeleaf condition to only show this section if the “convertedValue” attribute has been set in the model.

Your updated Thymeleaf template might look like this:

<form>
  ...
</form>

<div th:if="${quote != null}">
  Converted value is <span th:text="${quote}"></span>
</div>

Step 4: Styling the Currency Exchange App

To make our currency exchange app look more polished, let’s add some styling using Bootstrap. We’ll apply Bootstrap classes to our form elements and the converted value section.

  1. Add the Bootstrap CSS to your Thymeleaf template.
  2. Apply Bootstrap classes to your form elements, such as `form-group`, `form-control`, and `btn btn-primary`.
  3. Wrap your form and converted value sections in a Bootstrap container or row/column layout to improve the overall appearance.

Your final Thymeleaf template might look something like this:

<div class="container mt-5">
  <h1>Currency Exchange</h1>
  <form>
    <div class="form-group">
      <label for="from">From</label>
      <select class="form-control" id="from" name="from">
        <option th:each="quote : ${quotes}" th:value="${quote}">[[${quote}]]</option>
      </select>
    </div>
    <div class="form-group">
      <label for="to">To</label>
      <select class="form-control" id="to" name="to">
        <option th:each="quote : ${quotes}" th:value="${quote}">[[${quote}]]</option>
      </select>
    </div>
    <button type="submit" class="btn btn-primary">Convert</button>
  </form>

  <div th:if="${quote != null}" class="alert alert-primary" role="alert">
    Converted value is <span th:text="${quote}"></span>
  </div>
</div>

With these steps, you’ve now built a basic currency exchange application using Spring Boot and Thymeleaf. Users can select the currencies they want to convert between, and see the converted value displayed. You can further enhance the application by adding more features, such as error handling, currency exchange rate caching, and more advanced styling.

Check out the final project on GitHub: https://github.com/nerdic-coder/currency-exchange-demo

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at WordPress.com

Up ↑