Use Controller array in HTML Table with Spring Boot

旧城冷巷雨未停 提交于 2019-12-11 10:11:28

问题


My Controller function return array successfully.

My Controller Code is :

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" ;
}

But How to use this array (For ex., users) in webapp/index.html?

I want to display the database values in html table.

Please Advice.

Thank you.


回答1:


You need a templating engine for that. Spring supports:

  • Freemarker (list, else, items, sep, break)
  • Groovy (7. The MarkupTemplateEngine)
  • Thymeleaf (6. Iteration)
  • Velocity (Foreach loop)
  • Mustache (Non-Empty lists)

Source: docs

These languages allow you to dynamically generate a HTML page based on your model. With Thymeleaf you could use the th:each attribute to loop over your model, for example:

<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>

In this example I'm looping over the model ${customers} (because you named it like that in your controller), and for each customer a row is generated with two columns, one for the ID and another one for the name. These represent properties (with proper getter/setter) in your customer class.

Each of the templating engines provide a different way for looping over your model, showing them all would probably be too much for this answer.



来源:https://stackoverflow.com/questions/35124027/use-controller-array-in-html-table-with-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!