【问题标题】:How to bind the hashmap to thymeleaf radio button using th:field attribute in thymeleaf如何使用 th:field 属性将 hashmap 绑定到 thymeleaf 单选按钮
【发布时间】:2021-09-06 20:22:00
【问题描述】:

我想在thymleaf页面显示单选按钮输入值并保存单选按钮输入值。

但是,如下图所示,我的模型类使用hashmap来获取输入值(persons)并设置输入值(persons)。

private HashMap persons= new HashMap();

public void setPerson(String key, Object value) {
    this.persons.put(key, value);
}

public Object getPerson(String key) {
    return this.persons.get(key);
}

在 thymleaf 页面单选按钮中,我需要从特定键(人)的哈希映射中获取输入值,并为特定键(人)设置哈希映射的输入值(加载和保存数据)

基本上,我需要将 person hashmap 上的特定键与 thymleaf 页面中的单选按钮绑定。 我尝试使用 th: field 属性来绑定键,但它不起作用

<input type="radio" th:field="*{persons.get('person1')}" value="0"/>
<th:block condition>
  // input labels for value 0= No
</th:block>

<input type="radio" th:field="*{inputs.get('person1')}" value="1"/> 
<th:block condition>
  // input labels for value 0= yes
</th:block>

我也试过如下。现在它显示输入值(在 hashmap 中工作 get 方法)但我无法保存输入值(未将单选按钮输入设置为 hashmap)

<input type="radio" value="0" name="persons(person1)" 
       th:checked="*{persons.get('person1')=='0'}"/>

你们能帮我解决这个问题吗? 谢谢

【问题讨论】:

    标签: java spring hashmap thymeleaf


    【解决方案1】:

    您在 Thymeleaf 中查找的内容是 th:each。您可以使用它来遍历集合。 (https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#iteration)

    您正在为HashMap寻找解决方案:

    任何实现 java.util.Map 的对象。迭代地图时,iter 变量将属于 java.util.Map.Entry 类。

    所以在你的例子中它会是这样的:

    <div th:each="entry : ${map}">
        <p th:text="${entry.key}">entry key</p>
        <p th:text="${entry.value}">entry value</p>
    </div>

    【讨论】:

    • 如果 value 将是一个对象,那么您将需要另一个点和字段名称。
    猜你喜欢
    • 2016-09-27
    • 2019-10-17
    • 2014-10-14
    • 2019-01-09
    • 2016-01-08
    • 2014-02-03
    • 2010-11-27
    • 2017-06-22
    • 2012-12-27
    相关资源
    最近更新 更多