【问题标题】:How to get the posted value in Hashmap using spring and thymeleaf?如何使用 spring 和 thymeleaf 在 Hashmap 中获取发布的值?
【发布时间】:2018-04-22 18:58:34
【问题描述】:

早安,

我正在尝试通过 Hashmap 显示选择字段选项并返回发布的值。

我正在使用两个类,一个用于控制器,另一个用于模型。

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

请帮帮我。

谢谢。

【问题讨论】:

    标签: java spring thymeleaf


    【解决方案1】:

    没关系。

    我通过添加额外的字段来做到这一点。

    List<String> country;
    

    在 MyForm 模型类中,并将名称 country 分配给 thymeleaf 中的选择字段。

    <select id="country" name="country">
    <option th:each="c : *{list}" th:value="${c.key}" th:text="${c.value}"></option>
    </select>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      • 2021-04-15
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      相关资源
      最近更新 更多