美好的一天,
我试图通过 Hashmap 显示选择字段选项并获取发布的值。
我使用两个类,一个用于 Controller ,另一个用于模型。
public class MyForm {
private int id;
private Map<String, String> list;
//getter setters
}
@Controller
public class MyController {
@GetMapping("/create")
public String showForm(MyForm myForm) {
Map<String, String> list = new HashMap();
list.put("US", "United States")
list.put("UK", "United Kingdom")
return "myview"
}
@PostMapping("/create")
@ResponseBody
public String showForm(MyForm myForm) {
return "id: " + myform.getId() + " list: " + myform.getList();
}
}
这是模板。
<form th:action="@{/create}" th:object="${myForm}" method="POST">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>
Countries :
<select id="list" name="list">
<option th:each="c : *{list}" th:value="${c.key}" th:text="${c.value}"></option>
</select>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
当我打开 localho:8080/test 时,它会显示一个文本字段并选择包含“美国”和“英国”选项的归档。
在 ID 字段中输入 1 并选择英国,然后按提交按钮后,它会显示
1, null
请帮助我。
谢谢。
最佳答案
没关系。
我是通过添加额外的字段来完成的。
List<String> country;
在 MyForm 模型类中,并将名称国家/地区分配给 thymeleaf 中的选择字段。
<select id="country" name="country">
<option th:each="c : *{list}" th:value="${c.key}" th:text="${c.value}"></option>
</select>
关于java - 如何使用 spring 和 thymeleaf 获取 Hashmap 中的发布值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49969634/