java - 如何在 Thymeleaf 中使用对象中包含的 HashMap 填充下拉列表?

标签 java spring thymeleaf

我有一个包含 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...  
}

我想将该对象作为模型发送到表单,将该表单中的数据与该对象绑定(bind),然后将其显示在确认页面上。不幸的是,我在使用 HashMap 中的条目填充下拉列表时遇到问题。

我的 Controller 类:

@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";
    }
}

学生表格.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>

我的结果看起来像这样 my result

我做错了什么?

最佳答案

值和文本属性需要引用country,否则thymeleaf将打印countryOptions.toString()

<option th:each="country : ${student.countryOptions.entrySet()}"
        th:value="${country.key}"
        th:text="${country.value}">
</option>

关于java - 如何在 Thymeleaf 中使用对象中包含的 HashMap 填充下拉列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54689362/

相关文章:

java - Appium Maven 项目无法运行到真实设备

java - 按下一个键后从迭代器中删除对象

Spring OAUTH : Override CheckTokenEndpoint 'check_token?token=' response map

java - 更新现有 Gradle Libs 依赖项,以在 Spring 项目中使用 Jackson 2.8.5 和 DynamoDB 编码 ZonedDateTime

javascript - Spring MVC 如何将带有数据的 View 结果发送到ajax代码?

html - 当用户无法使用 Spring Boot 登录时,如何在登录页面中显示错误消息?

java - 从用户处获取密码值,我想在 url 路径中使用此密码,我使用 thymeleaf 作为模板引擎

java - LocaleChangeInterceptor.preHandle 中的对象处理程序有什么用

java - Spring - 需要使用注解进行依赖注入(inject)

java - 未定义类型的唯一 bean [blah] : expected single matching bean but found 2 [moreBlah]