问题
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}"> </td>
<td th:text="${customer.name}"> </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