1. 序章

記事SpringでのThymeleafの使用の概要では、ユーザー入力をオブジェクトにバインドする方法を説明しました。

Thymeleafテンプレートではth:objectth:field を使用し、コントローラーでは @ModelAttribute を使用して、データをJavaオブジェクトにバインドしました。 この記事では、Springアノテーション@RequestParamをThymeleafと組み合わせて使用する方法を見ていきます。

2. フォームのパラメータ

まず、4つのオプションのリクエストパラメーターを受け入れる単純なコントローラーを作成しましょう。

@Controller
public class MainController {
    @RequestMapping("/")
    public String index(
        @RequestParam(value = "participant", required = false) String participant,
        @RequestParam(value = "country", required = false) String country,
        @RequestParam(value = "action", required = false) String action,
        @RequestParam(value = "id", required = false) Integer id,
        Model model
    ) {
        model.addAttribute("id", id);
        List<Integer> userIds = asList(1,2,3,4);
        model.addAttribute("userIds", userIds);
        return "index";
    }
}

Thymeleafテンプレートの名前はindex.htmlです。 次の3つのセクションでは、ユーザーがデータをコントローラーに渡すために、さまざまなHTMLフォーム要素を使用します。

2.1. 入力要素

まず、テキスト入力フィールドとフォームを送信するためのボタンを備えた簡単なフォームを作成しましょう。

<form th:action="@{/}">
<input type="text" th:name="participant"/> 
<input type="submit"/> 
</form>

属性th:name =”参加者” は、入力フィールドの値をコントローラーのパラメーター参加者にバインドします。 これを機能させるには、パラメーターに@RequestParam(value =“ participant”))という注釈を付ける必要があります。

2.2. 要素を選択

HTMLのselect要素についても同様です。

<form th:action="@{/}">
    <input type="text" th:name="participant"/>
    <select th:name="country">
        <option value="de">Germany</option>
        <option value="nl">Netherlands</option>
        <option value="pl">Poland</option>
        <option value="lv">Latvia</option>
    </select>
</form>

選択したオプションの値は、 @RequestParam(value =“ country”)で注釈が付けられたパラメーターcountryにバインドされます。

2.3. ボタン要素

th:name を使用できるもう1つの要素は、ボタン要素です。

<form th:action="@{/}">
    <button type="submit" th:name="action" th:value="in">check-in</button>
    <button type="submit" th:name="action" th:value="out">check-out</button>
</form>

フォームを送信するために最初のボタンと2番目のボタンのどちらが押されたかに応じて、パラメーターactionの値はcheck-inまたはcheck-outのいずれかになります。

3. ハイパーリンクのパラメータ

要求パラメーターをコントローラーに渡す別の方法は、ハイパーリンクを使用することです。

<a th:href="@{/index}">

そして、括弧内にパラメータを追加できます。

<a th:href="@{/index(param1='value1',param2='value2')}">

Thymeleafは上記を次のように評価します。

<a href="/index?param1=value1¶m2=value2">

Thymeleaf式を使用してハイパーリンクを生成することは、変数に基づいてパラメーター値を割り当てる場合に特に便利です。たとえば、ユーザーIDごとにハイパーリンクを生成しましょう。

<th:block th:each="userId: ${userIds}">
    <a th:href="@{/(id=${userId})}"> User [[${userId}]]</a> <br/>
</th:block>

ユーザーIDのリストをプロパティとしてテンプレートに渡すことができます。

List<Integer> userIds = asList(1,2,3);
model.addAttribute("userIds", userIds);

結果のHTMLは次のようになります。

<a th:href="/?id=1"> User 1</a> <br/>
<a th:href="/?id=2"> User 2</a> <br/>
<a th:href="/?id=3"> User 3</a> <br/>

ハイパーリンクのパラメーターidは、パラメーター id にバインドされ、 @RequestParam(value =“ id”)の注釈が付けられます。

4. 概要

この短い記事では、SpringリクエストパラメーターをThymeleafと組み合わせて使用する方法を説明しました。

まず、リクエストパラメータを受け入れるシンプルなコントローラを作成しました。 次に、Thymeleafを使用して、コントローラーを呼び出すことができるHTMLページを生成する方法を確認しました。

この記事のすべての例の完全なソースコードは、GitHubにあります。