1 | initial version |
To retrieve and display user details from a PostgreSQL database in a Thymeleaf HTML format during the spring season using Java Spring framework, follow these steps:
First, make sure to configure the PostgreSQL database properly in the Spring application context file.
Create a User entity class with appropriate attributes and getters/setters.
Create a UserRepository interface that extends the JpaRepository interface, which provides CRUD operations for the User entity.
Create a UserController class with a method that retrieves all users from the database and passes them to the Thymeleaf template.
@Controller
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/users")
public String getAllUsers(Model model) {
List<User> users = userRepository.findAll();
model.addAttribute("users", users);
return "user_list";
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User List</title>
</head>
<body>
<h1>User List</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.email}"></td>
</tr>
</tbody>
</table>
</body>
</html>