html th:each分页循环
时间: 2023-10-08 10:12:51 浏览: 139
Thymeleaf 的 th:each 指令可以在 HTML 中循环遍历集合,但是它本身并不支持分页。如果你想要在 Thymeleaf 中实现分页循环,你可以使用 Spring Boot 自带的分页插件 Pageable 和 Page。
首先在 Spring Boot 中配置 Pageable 和 Page,例如:
```java
@Configuration
@EnableJpaRepositories(basePackages = {"com.example.repository"})
@EnableTransactionManagement
public class PersistenceConfig {
@Bean
public DataSource dataSource() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/testdb");
config.setUsername("username");
config.setPassword("password");
return new HikariDataSource(config);
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.MYSQL);
adapter.setShowSql(true);
adapter.setGenerateDdl(false);
adapter.setDatabasePlatform("org.hibernate.dialect.MySQL8Dialect");
return adapter;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
emf.setJpaVendorAdapter(jpaVendorAdapter());
emf.setPackagesToScan("com.example.entity");
return emf;
}
@Bean
public JpaTransactionManager transactionManager() {
return new JpaTransactionManager(entityManagerFactory().getObject());
}
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
@Bean
public PageableHandlerMethodArgumentResolver pageableHandlerMethodArgumentResolver() {
PageableHandlerMethodArgumentResolver pageableResolver = new PageableHandlerMethodArgumentResolver();
pageableResolver.setOneIndexedParameters(true);
pageableResolver.setFallbackPageable(PageRequest.of(0, 10));
pageableResolver.setMaxPageSize(100);
return pageableResolver;
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(pageableHandlerMethodArgumentResolver());
}
}
```
然后在你的控制器中使用 Pageable 对象获取分页数据,例如:
```java
@GetMapping("/users")
public String getUsers(Pageable pageable, Model model) {
Page<User> page = userRepository.findAll(pageable);
model.addAttribute("page", page);
return "users";
}
```
最后在 Thymeleaf 的 HTML 页面中使用 Page 对象进行循环遍历和分页导航,例如:
```html
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${page.content}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.email}"></td>
</tr>
</tbody>
</table>
<div>
<ul>
<li th:if="${page.hasPrevious()}">
<a th:href="@{${#httpServletRequest.requestURI}}?page=${page.previousPageable().pageNumber}"><<</a>
</li>
<li th:each="i : ${#numbers.sequence(0, page.totalPages - 1)}">
<a th:href="@{${#httpServletRequest.requestURI}}?page=${i}" th:text="${i + 1}"></a>
</li>
<li th:if="${page.hasNext()}">
<a th:href="@{${#httpServletRequest.requestURI}}?page=${page.nextPageable().pageNumber}">>></a>
</li>
</ul>
</div>
```
这样就可以在 Thymeleaf 中实现分页循环了。
阅读全文