【问题标题】:Input to the arraylist with Thymeleaf使用 Thymeleaf 输入到数组列表
【发布时间】:2017-07-28 12:21:38
【问题描述】:

我有一个简单的类,其中包含 2 个Strings、1 个Integer 和 1 个ArrayList<String>。使用 Spring MVC 和 Thymeleaf 我正在尝试创建一个表单,我可以在其中插入数据来创建一个对象。可悲的是,我不知道如何处理Arraylist。这是我到目前为止所得到的:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Insert title here</title>
</head>
<body>
<h1>F O R M</h1>
<form th:action="@{/form/person}" th:object="${person}" method="post">
  <table>
    <tr>
      <td>Name:</td>
      <td><input type="text" th:field="*{name}"/></td>
      <td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name error</td>
    </tr>
    <tr>
      <td>Age:</td>
      <td><input type="number" th:field="*{age} "/></td>
      <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Age Error</td>
    </tr>
    <tr>
      <td>City:</td>
      <td><input type="text" th:field="*{city}"/></td>
      <td th:if="${#fields.hasErrors('city')}" th:errors="*{city}">City Error</td>
    </tr>
    <tr>
      <td><input type="submit" value="Submit"/></td>
      <td><input type="reset" value="Reset"/></td>
    </tr>
  </table>
</form>
</body>
</html>

【问题讨论】:

    标签: spring-mvc arraylist input thymeleaf


    【解决方案1】:

    例如,如果您的列表名称是city,那么:

     <input type="text" th:field="*{city[__${INDEX}__]}" />
    

    INDEX 是您列表中的索引。例如,当您将 String 放在第二个索引上时,然后在第一个索引上您将拥有 null

    【讨论】:

    • 假设我的 arraylist 用于昵称(类是 Person.class)。每个人都可以有很多昵称,有没有办法在简单的form.html中添加昵称,使用SpEL?
    • @ogarogar 我对 SpEL 了解不多,因此无法帮助您。您不想让用户添加任意​​数量的昵称吗?为什么不为昵称添加例如 3 个输入字段?
    猜你喜欢
    • 2018-07-08
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 2019-10-21
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多