Thymeleaf使用路径变量th:href

use*_*206 25 java spring spring-mvc spring-el spring-boot

这是我正在迭代的代码:

<tr th:each="category : ${categories}">
     <td th:text="${category.idCategory}"></td>
     <td th:text="${category.name}"></td>
     <td>
         <a th:href="@{'/category/edit/' + ${category.id}}">view</a>
     </td>
</tr>
Run Code Online (Sandbox Code Playgroud)

它指向的URL应该是 /category/edit/<id of the category>

它说无法解析表达式:

<tr th:each="category : ${categories}">
     <td th:text="${category.idCategory}"></td>
     <td th:text="${category.name}"></td>
     <td>
         <a th:href="@{'/category/edit/' + ${category.id}}">view</a>
     </td>
</tr>
Run Code Online (Sandbox Code Playgroud)

cra*_*aro 33

嗨,我认为你的问题是一个类型错误

<a th:href="@{'/category/edit/' + ${category.id}}">view</a>
Run Code Online (Sandbox Code Playgroud)

你正在使用category.id,但在你的代码中是iddategory,正如Eddie所说

这对你有用

<a th:href="@{'/category/edit/' + ${category.idCategory}}">view</a>
Run Code Online (Sandbox Code Playgroud)


Mar*_*jas 22

根据Thymeleaf文档,添加参数的正确方法是:

<a th:href="@{/category/edit/{id}(id=${category.idCategory})}">view</a>
Run Code Online (Sandbox Code Playgroud)

  • 这是一个非常被低估的答案。我认为那是最好的。 (3认同)

小智 13

一种更简洁,更简单的方法

<a href="somepage.html" th:href="@{|/my/url/${variable}|}">A Link</a>
Run Code Online (Sandbox Code Playgroud)

我在Thymeleaf文档中找到了关于"4.8 Literal substitutions"的解决方案.


Edd*_*ude 12

您的代码在语法上看起来是正确的,但我认为您的属性不存在来创建 URL。

我刚刚测试了它,它对我来说很好用。

尝试使用category.idCategory而不是category.id,例如...

  <tr th:each="category : ${categories}">
    <td th:text="${category.idCategory}"></td>
    <td th:text="${category.name}"></td>
    <td>
      <a th:href="@{'/category/edit/' + ${category.idCategory}}">view</a>
    </td>
  </tr>
Run Code Online (Sandbox Code Playgroud)


Sha*_*iar 5

我试图浏览一个对象列表,将它们显示为表格中的行,每一行都是一个链接。这对我有用。希望能帮助到你。

// CUSTOMER_LIST is a model attribute
<table>
    <th:block th:each="customer : ${CUSTOMER_LIST}">
        <tr>
            <td><a th:href="@{'/main?id=' + ${customer.id}}" th:text="${customer.fullName}" /></td>
        </tr>
    </th:block>
</table>
Run Code Online (Sandbox Code Playgroud)


Ena*_*que 5

你可以使用像

  1. 我的桌子如下..

    <table>
       <thead>
        <tr>
            <th>Details</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="user: ${staffList}">
            <td><a th:href="@{'/details-view/'+ ${user.userId}}">Details</a></td>
        </tr>
     </tbody>
    </table>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 这是我的控制器..

    @GetMapping(value = "/details-view/{userId}")
    public String details(@PathVariable String userId) { 
    
        Logger.getLogger(getClass().getName()).info("userId-->" + userId);
    
     return "user-details";
    }
    
    Run Code Online (Sandbox Code Playgroud)