spring - 如何使用 Thymeleaf 将数据从单选按钮发送到 Controller

标签 spring spring-mvc thymeleaf

我有一个简单的 HTML 页面,其中显示了一些单选按钮:

<form action="#" th:action="@{/processForm}" th:object="${priorities}"
  method="post">
  <fieldset>
    <table style="width: 500px">
      <tr th:each="item : ${chosen}">
        <td>
          <div>
            <div>
              <label th:text="${item}">example</label>
              <input type="radio" th:name="${'priorities[' + item + ']'}" value="a" />A
              <input type="radio" th:name="${'priorities[' + item + ']'}" value="b" />B
              <input type="radio" th:name="${'priorities[' + item + ']'}" value="c" />C
            </div>
          </div>
        </td>
      </tr>
      <tr>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td>
          <button type="submit"
            class="btn btn-xs btn-primary margin10-right paddingNew"
            name="save">Calculate!</button>
        </td>
        <td></td>
      </tr>
    </table>
  </fieldset>
</form>

这是我所看到的:

radios

我想将此数据发送到我的 Controller ,因此我创建了一个:

@RequestMapping(value = "/processForm", method = RequestMethod.POST)
public String save(@ModelAttribute(value = "foo") ClusterParams foo,
@ModelAttribute(value = "priorities") HashMap<String, String> priorities,
final ModelMap m) throws ClassNotFoundException, IOException,
InterruptedException {

    for (String s : priorities.keySet()) {
        System.out.println(s);
    }
}

在这里您可以看到我的类(class)权重(已删除):

public class Weights {

    Map<String, String> priorities = new HashMap<String, String>();

    public Map<String, String> getPriorities() {
        return priorities;
    }

    public void setPriorities(Map<String, String> priorities) {
        this.priorities = priorities;
    }

}

但我不知道如何使用 thymeleaf 设置值。

我想要一个映射:

camera -> B
video -> C

你能帮我做到吗?当然创建HashMap是我的想法,如果有其他解决方案我会改变它。

提前谢谢

最佳答案

根据6.4.1 Setting and getting basic and nested properties ,你应该有<input>名称如priorities[camera]在生成的 HTML 中使其工作。

尝试以下操作:

<input type="radio" th:name="${'priorities[' + item + ']'}" value="a" />

关于spring - 如何使用 Thymeleaf 将数据从单选按钮发送到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24365716/

相关文章:

java - 在 Spring-Cloud-Netflix 中为 AWS 配置 EurekaInstanceConfigBean (Brixton.RELEASE)

java - Spring 安全 HttpSecurity

spring - @Autowired(required=false) 在构造函数上给出 NoSuchBeanDefinitionException

java - 如何将 Spring Data JPA 正确配置到 Spring Boot 2.X 应用程序的 application.properties 配置文件中?

java - Apache Tomcat 和 Apache TomEE 服务器未在 Eclipse 中运行 Web 项目

SpringMVC : DispatcherServlet makes extra requests to view

java - Spring CrudRepository,Webservice,返回带有特定字符串的json对象

java - Spring中Thymeleaf异常解析文档

java - html + Java |从输入类型 ="time"接收 0

javascript - 语义 UI 搜索栏 - 你能切断描述,让它只显示前几个词,但仍然搜索所有词吗?