Friday, April 20, 2018

How to construct dynamic URL using Thymeleaf

While creating a web application, it's very common to sends parameters in the request as query string or as the path variables. Recently, I have tried to achieve the same using Thymeleaf but faced some problem because I was new to Thymeleaf. But later found that Thymeleaf provides very simple and straightforward way to create dynamic URLs. Today we would see How? As it could be useful to anyone who would come across the same problem.

We would be using link expressions, a type of Thymeleaf Standard Epression: @{...} to create URLs in our web application.
  1. Passing parameters as Query String
    O/P : <a href="/orderdetails?id=3">
    <a th:href="@{/orderdetails(id=3)}"> 
    <a th:href="@{/orderdetails(id=${})}" th:text="${}">Order ID</a>
    Would like to pass several parameters,
    O/P: <a href="/orderdetails?id=3&amp;action=show_all">
    <a th:href="@{/orderdetails(id=3,action='show_all')}">
  2. Passing parameters as Path Variables
    O/P : <a href="/orderdetails/3">
    <a th:href="@{/orderdetails/{id}(id=3)}"> 
    <a th:href="@{/orderdetails/{id}(id=${})}" th:text="${}">Order ID</a>
    Alternative way:
    <a th:with="id=${}" th:href="@{${'/orderdetails/' + id}}" th:text="${id}">Order ID</a>
    <a th:href="@{${'/orderdetails/' +}}" th:text="${}">Order ID</a>
If you would like to know about how to fetch the data [passed as Query String or as Path Variable using Thymeleaf] from incoming request in your Controller in Sprig MVC then you could checkout my post that describes the Differences between @RequestParam and @PathVariable annotations in Spring MVC? Happy Learning!!

1 comment: