1、引入PageHelper的Maven依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
2、在项目的config目录里创建PageHelper对象
package com.zkjt.xxzx.config;
import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class PageHelperConfig {
@Bean
public PageHelper createPaeHelper(){
PageHelper page= new PageHelper();
return page;
}
}
3、
package com.springboot.pagehelper.controller;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.springboot.pagehelper.model.User;
import com.springboot.pagehelper.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/")
public String first(){
return "serverinfo";
}
@RequestMapping("/index")
@ResponseBody
public Map<String, Object> index(@RequestParam Map condition){
System.out.println(condition);
// 接受前端传过来的,起始页,每页记录数这两个参数,将其转换为整数
int startPage= Integer.parseInt((String)condition.get("page"));
int pageSize= Integer.parseInt((String)condition.get("limit"));
// 创建Page对象,将page,limit参数传入,必须位于从数据库查询数据的语句之前,否则不生效
Page page= PageHelper.startPage(startPage, pageSize);
// ASC是根据id 正向排序,DESC是反向排序
PageHelper.orderBy("id ASC");
// 从数据库查询,这里返回的的allUser就已经分页成功了
List<User> allUser = userService.getAllUser();
// 获取查询记录总数,必须位于从数据库查询数据的语句之后,否则不生效
long total = page.getTotal();
// 一下是layui的分页要求的信息
HashMap<String, Object> map = new HashMap<>();
map.put("code",0);
map.put("msg","请求成功");
map.put("data",allUser);
map.put("count",total);
return map;
}
网友评论