在 HTML 表中使用控制器数组与 Spring Boot



我的控制器函数成功返回数组。

我的控制器代码是:

private JdbcTemplate jdbcTemplate;
@Autowired
ConfigurationController configcon = new ConfigurationController(jdbcTemplate);
@RequestMapping(value = "/")
public String index(Model model) {
    model.addAttribute("users", configcon.getQuery("customers"));
    return "forward:/index.html" ;
}

但是如何在 webapp/index.html 中使用此数组(例如,用户)?

我想在 html 表中显示数据库值。

请指教。

谢谢。

为此,您需要一个模板引擎。弹簧支架:

  • 自由标记(列表,否则,项目,分隔,中断)
  • 时髦(7.标记模板引擎)
  • 百里香叶(6.迭代)
  • 速度(Foreach 循环)
  • 胡子(非空列表)

来源:文档

这些语言允许您基于模型动态生成 HTML 页面。使用 Thymeleaf,您可以使用 th:each 属性遍历模型,例如:

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr th:each="customer : ${customers}">
      <td th:text="${customer.id}">&nbsp;</td>
      <td th:text="${customer.name}">&nbsp;</td>
    </tr>
  </tbody>
</table>

在此示例中,我将循环访问模型${customers}(因为您在控制器中以这种方式命名它),并且为每个客户生成一行,其中包含两列,一列用于 ID,另一列用于名称。这些表示客户类中的属性(具有适当的 getter/setter)。

每个模板引擎都提供了一种不同的方法来循环您的模型,显示它们对于这个答案来说可能太多了。

最新更新