知識庫 / Spring / Spring MVC RSS 訂閱

Spring Path Variables 與 Thymeleaf

Spring MVC
HongKong
10
01:09 PM · Dec 06 ,2025

1. 簡介

在本簡短教程中,我們將學習如何使用 Thymeleaf 創建 URL,並使用 Spring 路徑變量。

我們使用路徑變量,以便將值作為 URL 的一部分傳遞。在 Spring 控制器中,我們使用 <em @PathVariable 註解訪問這些值。

2. 使用路徑變量

首先,讓我們通過創建簡單的 Item 類來設置我們的示例:

public class Item {
    private int id;
    private String name;

    // Constructor and standard getters and setters
}

現在,讓我們創建我們的控制器:

@Controller
public class PathVariablesController {

    @GetMapping("/pathvars")
    public String start(Model model) {
        List<Item> items = new ArrayList<Item>();
        items.add(new Item(1, "First Item"));
        items.add(new Item(2, "Second Item"));
        model.addAttribute("items", items);
        return "pathvariables/index";
    }
    
    @GetMapping("/pathvars/single/{id}")
    public String singlePathVariable(@PathVariable("id") int id, Model model) {
        if (id == 1) {
            model.addAttribute("item", new Item(1, "First Item"));
        } else {
            model.addAttribute("item", new Item(2, "Second Item"));
        }
        
        return "pathvariables/view";
    }
}

在我們的 index.html 模板中,讓我們遍歷我們的項目並創建鏈接,調用 singlePathVariable 方法:

<div th:each="item : ${items}">
    <a th:href="@{/pathvars/single/{id}(id = ${item.id})}">
        <span th:text="${item.name}"></span>
    </a>
</div>

我們剛剛創建的代碼生成如下 URL:

http://localhost:8080/pathvars/single/1

這是一種標準的 Thymeleaf 語法,用於在 URL 中使用表達式。

我們還可以使用字符串拼接來實現相同的結果:

<div th:each="item : ${items}">
    <a th:href="@{'/pathvars/single/' + ${item.id}}">
        <span th:text="${item.name}"></span>
    </a>
</div>

3. 使用多個路徑變量

現在我們已經瞭解了在 Thymeleaf 中創建路徑變量 URL 的基本知識,接下來快速介紹如何使用多個路徑變量。

首先,我們將創建一個 Detail 類並修改我們的 Item 類,使其包含一個 Detail 列表:

public class Detail {
    private int id;
    private String description;

    // constructor and standard getters and setters
}

接下來,我們添加一個從“Detail”到“Item”的列表:

private List<Detail> details;

現在,讓我們更新我們的控制器以添加使用多個 @PathVariable 註解的方法:

@GetMapping("/pathvars/item/{itemId}/detail/{dtlId}")
public String multiplePathVariable(@PathVariable("itemId") int itemId, 
  @PathVariable("dtlId") int dtlId, Model model) {
    for (Item item : items) {
        if (item.getId() == itemId) {
            model.addAttribute("item", item);
            for (Detail detail : item.getDetails()) {
                if (detail.getId() == dtlId) {
                    model.addAttribute("detail", detail);
                }
            }
        }
    }
    return "pathvariables/view";
}

最後,讓我們修改我們的 index.html 模板以為每個詳細記錄創建 URL:

<ul>
    <li th:each="detail : ${item.details}">
        <a th:href="@{/pathvars/item/{itemId}/detail/{dtlId}(itemId = ${item.id}, dtlId = ${dtl.id})}">
            <span th:text="${detail.description}"></span>
        </a>
    </li>
</ul>

4. 結論

在本快速教程中,我們學習瞭如何使用 Thymeleaf 創建帶有路徑變量的 URL。我們首先創建了一個僅包含一個路徑變量的簡單 URL。之後,我們擴展了示例,以使用多個路徑變量。

發佈 評論

Some HTML is okay.