1. 序章
この短いチュートリアルでは、 Thymeleaf を使用して、Springパス変数を使用してURLを作成する方法を学習します。
URLの一部として値を渡したい場合は、パス変数を使用します。 Springコントローラーでは、@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
これは、URLで式を使用するための標準のThymeleaf構文です。
連結を使用して同じ結果を達成することもできます。
<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クラスを変更してそれらのリストを作成します。
public class Detail {
private int id;
private String description;
// constructor and standard getters and setters
}
次に、詳細のリストをアイテムに追加しましょう。
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を作成する方法を学びました。 まず、1つだけの単純なURLを作成しました。 その後、複数のパス変数を使用するように例を拡張しました。
サンプルコードは、GitHubでから入手できます。