Search code examples
springthymeleaf

Hardcoding of path and how to avoid it?


spring-boot-starter-parent 2.3.5.RELEASE

I'm studying a video course. Thymeleaf it used. The lecturer has hardcoded a part of a path.

<a hredf="#" th:href="@{/recipe/show} + ${recipe.id}}">View</a>

Could you tell me whether such hardcoding is Ok? Why didn't they put this path to a variable and didn't pass it to the context?

Is there a way not to hardcode paths?


Solution

  • this kind of links are usually immutable. like for showing receipts id. and hard coding them aint a problem.

    but if your path can be change, you can change use a variable like what you have done:

    ${recipe.id}
    

    if you had another variable section in your path you could use variable for them too.

    <a hredf="#" th:href="@{/recipe/} + ${actionName} + ${recipe.id}">View</a>
    

    There is some kind of not to hard coding in Spring (JSF) to use ControllerName and Action Name as route name like this:

    <h:commandButton action = "#{receiptController.show}" />
    

    or:

    <h:commandLink action = "#{receiptController.show}" value = "link text">
      <f:param name = "receiptId" value = "${receipt.id}" />
    </h:commandLink>
    

    According to : https://www.thymeleaf.org/doc/articles/standardurlsyntax.html

    thymeleaf has not implement This Feature.

    you can only pass variables to it.

    so you can have an static class of Constant url map.