问题描述
我有一个包含HashMap和其他变量的对象。 那是定义它的类:
public class Student {
private String firstName;
private String lastName;
private String country;
public HashMap<String,String> countryOptions;
public Student()
{
// populate country options: used ISO country code
countryOptions = new HashMap<String, String>() {};
countryOptions.put("BR", "Brazil");
countryOptions.put("FR", "France");
countryOptions.put("DE", "Germany");
countryOptions.put("IN", "India");
}
// getters and setters...
}
我想将该对象作为模型发送到表单,将表单中的数据与该对象绑定,然后将其显示在确认页面上。 不幸的是,我在使用HashMap中的条目填充下拉列表时遇到问题。
我的控制器类:
@Controller
@RequestMapping("/student")
public class StudentController {
@RequestMapping("/showForm")
public String showForm(Model theModel)
{
Student theStudent = new Student();
theModel.addAttribute("student", theStudent);
theModel.addAttribute("country", theStudent.countryOptions);
return "student-form";
}
@RequestMapping("/save")
public String save(@ModelAttribute("student") Student theStudent)
{
return "student-confirmation";
}
}
学生form.html:
<body>
<form th:action="@{save}" th:object="${student}" method="post">
<input type="text" name="firstName" th:field="${student.firstName}"/>
<input type="text" name="lastName" th:field="${student.lastName}"/>
<select name="country" th:field="${student.country}">
<option th:each="country : ${student.countryOptions}" th:value="${student.countryOptions}" th:text="${student.countryOptions}"></option>
</select>
<input type="submit"/>
</form>
</body>
我的结果看起来像这样
我究竟做错了什么?
1楼
值和文本属性需要引用country
,否则百里香将打印countryOptions.toString()
<option th:each="country : ${student.countryOptions.entrySet()}"
th:value="${country.key}"
th:text="${country.value}">
</option>