[英]Thymeleaf dynamic datatype for form
我有一個HashMap,提供某些文檔的數據:
Key | Value
----------------
Name | test1
Type | type1
...
未指定行數,並且鍵和值都首先是字符串。
現在我要編輯此動態數據。 我為此創建了此模板:
<form action="#" th:action="@{/documents/{id}(id=${doc_id})}" th:object="${properties}" method="post">
<h1 th:text="${document_h1_text}">Documents</h1>
<table class="table table-striped">
<tr>
<th>Property</th>
<th>Value</th>
</tr>
<tr th:each="property : ${document_properties}">
<td th:text="${property.key}">Property</td>
<td>
<input name="${property.key}" th:value="${property.value}" />
</td>
</tr>
</table>
<button type="submit" class="btn btn-default">Submit</button>
</form>
document_properties
與HashMap<String,String>
當我使用以下方法獲取此Web服務時,此方法工作正常
@RequestMapping(path = "documents/{doc_id}", method = RequestMethod.GET)
public String document(@PathVariable long doc_id, Model model) { ... }
現在,我想在前端編輯此輸出並提交更改:
@PostMapping("documents/{doc_id}")
public String editDocument(@PathVariable long doc_id, @ModelAttribute HashMap<String, String> properties,Model model) { ... }
不幸的是,當我通過單擊“提交”按鈕將其命名時,HashMap properties
為空。 你們中有人知道如何解決這個問題嗎? 僅供參考:我故意選擇不使用常規的類綁定。 原因是我想獲得一個動態解決方案,可以處理任意類。
這是一個簡單的示例,應該可以按照您想要的方式工作。
包裝紙
public class MapWrapper {
private Map<String, String> map = new HashMap<>();
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
}
控制者
@Controller
public class MapController {
@GetMapping("map.html")
public String get(Map<String, Object> model) throws Exception {
MapWrapper wrapper = new MapWrapper();
wrapper.getMap().put("1", "One");
wrapper.getMap().put("2", "Two");
wrapper.getMap().put("3", "Three");
model.put("wrapper", wrapper);
return "map";
}
@PostMapping("map.html")
public String post(Map<String, Object> model, @ModelAttribute("wrapper") MapWrapper wrapper) throws Exception {
return "map";
}
}
形成
<form action="map.html" th:object="${wrapper}" method="post">
<table class="table table-striped">
<tr>
<th>Property</th>
<th>Value</th>
</tr>
<tr th:each="key : ${wrapper.map.keySet()}">
<td th:text="${key}" />
<td>
<input th:field="*{map[__${key}__]}" />
</td>
</tr>
</table>
<button type="submit" class="btn btn-default">Submit</button>
</form>
它有過多的支持對象,似乎不是一個好方法,我認為我們需要一些通用的模式,例如:
public class GenericEntity {
protected Map<String, Object> properties = new LinkedHashMap<String, Object>();
//setter getter
}
entity extends GenericEntity
並在控制器中
<tr th:each=" key : ${wrapper.map.keySet()}">
<td th:text="${key}" />
<td>
<input th:field="*{properties[__${key}__]}" />
</td>
</tr>
但是您應該找到一種在超類中設置屬性映射的方法,並且它是如此硬編碼的,另一種方法可以寫下thymleafe v3的自定義方言。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.