【问题标题】:create relative links with Thymeleaf使用 Thymeleaf 创建相对链接
【发布时间】:2021-06-05 15:33:56
【问题描述】:

我有以下代码循环遍历国家列表并创建 href 链接

<div class="container" th:each="country: ${countryList}">
    <a th:href="${country.countryAbbr}"><div clss="row" th:text="${country.country}"></div></a>
</div>

当前页面url为“localhost:8080/directory”,生成的url显示为

“本地主机:8080/us”

如何让网址显示为“localhost:8080/directory/us”

我希望将“我们”添加到页面的当前 url。

【问题讨论】:

    标签: thymeleaf


    【解决方案1】:

    尝试在您的 Controller 类中创建以下代码。

    @RequestMapping(value="/", method=RequestMethod.GET)
    public String rootGet() {
        return "redirect:/directory";
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用ServletUriComponentsBuilder:

      <div th:with="urlBuilder=${T(org.springframework.web.servlet.support.ServletUriComponentsBuilder)}"
      class="container" th:each="country: ${countryList}">
          <a th:href="${urlBuilder.fromCurrentRequest().path(${country.countryAbbr}).toUriString()}">
            <div clss="row" th:text="${country.country}"></div>
          </a>
      </div>
      

      【讨论】:

        【解决方案3】:

        试试这个

        <div class="container" th:each="country: ${countryList}">
            <a th:href="@{${country.countryAbbr}}"><div clss="row" th:text="${country.country}"></div></a>
        </div>
        

        使用@ 通常会解析默认上下文,但我不知道您的环境。

        例如,如果您有 Tomcat .war 文件,并且您的应用程序将托管在 localhost:8080/myApp,您将需要结果 /myApp/us 而不是 /us@ 会做到这一点。

        如果以上内容与您无关,请使用以下内容:

        <div class="container" th:each="country: ${countryList}">
            <a th:href="@{'/directory/' + ${country.countryAbbr}}"><div clss="row" th:text="${country.country}"></div></a>
        </div>
        

        【讨论】:

          猜你喜欢
          • 2015-07-01
          • 2017-11-28
          • 1970-01-01
          • 2018-03-03
          • 2015-06-28
          • 2021-03-12
          • 2017-03-01
          • 2018-10-29
          • 1970-01-01
          相关资源
          最近更新 更多