[JAVA] Output table from Map <String, Object> format with Thymeleaf3

Purpose

It is used when you want to output a table with variable items to be output by Thymeleaf.

Execution environment

SpringBoot 2.0.3.RELEASE ( Thymeleaf 3.0.9.RELEASE )

Data to be output with Controller

From Controller, pass the one in Map <String, Object> format. However, I use LinkedHashMap because I want to always define the output order of Map.

package alphapz.thymeleaf.controller;


import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author A-pZ
 *
 */
@Controller
public class MatrixController {
	@GetMapping("")
	public ModelAndView display(ModelAndView mnv) {

		mnv.addObject("data", matrix);
		mnv.setViewName("index");

		return mnv;
	}

	private Map<String, Object> matrix = new LinkedHashMap<String, Object>() {{
		put("id","ID001");
		put("name","username");
		put("address","USER_ADDRESS");
	}};
}

View (Template)

Since the previous Map is stored with the name of data, specify it with th: each, which repeatedly displays the Collection system.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
	<table>
		<thead class="thead-dark">
			<tr>
				<th th:each="entry : ${data}" th:text="${entry.key}"></th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td th:each="entry : ${data}" th:text="${entry.value}"></td>
			</tr>
		</tbody>
	</table>
</body>
</html>

Since the element fetched by th: each is EntrySet, the key name can be obtained from key and the value can be obtained from value.

Recommended Posts

Output table from Map <String, Object> format with Thymeleaf3
Output multiplication table with Stream
Is String # format (String, Object ...) really slow?
Output ER diagram from PostgreSQL with SchemaSpy 6.1.0