springboot+jpa+thymeleaf项目实现分页功能

1 所使用的技术

后端:springboot+jpa

前端:thymeleaf模板

2 实现代码

2.1 前端核心代码

注意:page是后端传递过来的对象,其属性值包括:

{
 "content":[ //包含的内容对象
 {"id":123,"title":"blog122","content":"this is blog content"},
 {"id":122,"title":"blog121","content":"this is blog content"},
 {"id":121,"title":"blog120","content":"this is blog content"},
 {"id":120,"title":"blog119","content":"this is blog content"},
 {"id":119,"title":"blog118","content":"this is blog content"},
 {"id":118,"title":"blog117","content":"this is blog content"},
 {"id":117,"title":"blog116","content":"this is blog content"},
 {"id":116,"title":"blog115","content":"this is blog content"},
 {"id":115,"title":"blog114","content":"this is blog content"},
 {"id":114,"title":"blog113","content":"this is blog content"},
 {"id":113,"title":"blog112","content":"this is blog content"},
 {"id":112,"title":"blog111","content":"this is blog content"},
 {"id":111,"title":"blog110","content":"this is blog content"},
 {"id":110,"title":"blog109","content":"this is blog content"},
 {"id":109,"title":"blog108","content":"this is blog content"}],
 "last":false, //是否最后一页
 "totalPages":9, //总页数
 "totalElements":123, //数据总数
 "size":15, //每页包括的数据条数
 "number":0,  //当前是第几页
 "first":true, //是否第一页
 "sort":[{ //数据排序方式
 "direction":"DESC", //倒序
 "property":"id", //按id排序
 "ignoreCase":false,
 "nullHandling":"NATIVE",
 "ascending":false
 }],
 "numberOfElements":15
}

2.2 Controller层

创建IndexController类,其核心代码如下:

@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    //首页
    @GetMapping("/")
    public String index(@PageableDefault(size = 5, sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                        Model model){
        model.addAttribute("page",blogService.listBlog(pageable)); //查询到分页数据返回到前端页面展示
        return "index";
    }

}

注意:前端点击超链接之后,前端会传递过来page值(page值表示要查询的是第几页数据),并结合@PageableDefault注解给出的size值和sort值去创建Pageable对象,相当于执行了如下语句:Pageable pageable = new PageRequest(page,size,sort)。这里PageRequest类实现了Pageable接口,后端拿到Pageable对象值后,调用Service方法进行处理。

2.3 Service层

创建BlogService接口

public interface BlogService {
    Page listBlog(Pageable pageable);
}

创建实现BlogService接口的类

@Service
public class BlogServiceImpl implements BlogService {
    @Autowired
    private BlogRepository blogRepository;

    @Override
    public Page listBlog(Pageable pageable) {
        return blogRepository.findAll(pageable);
    }
}

2.4 Dao层

public interface BlogRepository extends JpaRepository, JpaSpecificationExecutor {
}

注意:JPA默认提供了一些基础功能,超出基础功能之外的操作数据库的方法需要自己定义,这里findAll就是基础功能。

3 运行结果

springboot+jpa+thymeleaf项目实现分页功能_第1张图片

springboot+jpa+thymeleaf项目实现分页功能_第2张图片

 

4 运行逻辑

前端点击上一页或下一页,传递一个Pageable对象给Controller层,Controller层接收该对象,调用Service层方法把Pageable对象传入,处理业务逻辑,Service层调用Dao层对数据库查询指定页的数据返回给前端展示。

 

你可能感兴趣的:(springboot,java,java,jpa,thymeleaf)