1. 引言
在本文“使用 Thymeleaf 在 Spring 中的入門”中,我們瞭解到如何將用户輸入綁定到對象上。
我們使用了 Thymeleaf 模板中的 <em th:object</em> 和 <em th:field</em>,以及控制器中的 <em @ModelAttribute</em> 將數據綁定到 Java 對象上。 在本文中,我們將探討如何使用 Spring 註解 <em @RequestParam</em> 與 Thymeleaf 結合使用。
2. 表單中的參數
首先,讓我們創建一個簡單的控制器,該控制器接受四個可選的請求參數:
@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。 在接下來的三個部分,我們將使用不同的 HTML 表單元素,供用户將數據傳遞給控制器。
2.1. 輸入元素
首先,讓我們創建一個包含文本輸入字段和提交表單按鈕的簡單表單:
<form th:action="@{/}">
<input type="text" th:name="participant"/>
<input type="submit"/>
</form>屬性 將輸入字段的值綁定到控制器參數 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>所選選項的值綁定到 country 參數,並帶有 @RequestParam(value = “country”) 註解。
2.3. 按鈕元素
另一個可以使用 th:name 的元素是按鈕元素:
<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>根據提交表單時點擊的第一個或第二個按鈕,請求參數 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 頁面。