PageHelper插件
Posted brent
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PageHelper插件相关的知识,希望对你有一定的参考价值。
添加依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
直接写在控制器层:
1.PageHelper.startPage(1,3)
.doSelectPageInfo(new ISelect() {
@Override
public void doSelect() {
sysNoticeService.findNotices(notice);
}
2. return new JsonResult(PageHelper.startPage(1, 3)
.doSelectPageInfo(()->//lambda
sysNoticeService.findNotices(notice)));*/
定义工具类:
获取请求对象
ServletRequestAttributes sra=
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request=sra.getRequest();
获取请求中的分页参数对象
String pageCurrentStr=request.getParameter("pageCurrent");
String pageSizeStr=request.getParameter("pageSize");
int pageCurrent=pageCurrentStr?1:Integer.parseInt(pageCurrentStr);
int pageSize==pageSizeStr?3:Integer.parseInt(pageSizeStr);
启动分页查询
return PageHelper.startPage(pageCurrent, pageSize);
代码不重复编写,创建多个类:
创建PageUtile类:
package com.cy.pj.common.util;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import javax.servlet.http.HttpServletRequest;
/**
* 定义分页操作工具类,在此类方法内部启动分页查询
*/
public class PageUtil{
public static <T>Page<T> startPage(){
//获取请求对象
HttpServletRequest request=ServletUtil.getRequest();
//获取请求中的分页参数对象
String pageCurrentStr=request.getParameter("pageCurrent");
String pageSizeStr=request.getParameter("pageSize");
int pageCurrent=StringUtil.isEmpty(pageCurrentStr)?1:Integer.parseInt(pageCurrentStr);
int pageSize=StringUtil.isEmpty(pageSizeStr)?3:Integer.parseInt(pageSizeStr);
//启动分页查询
return PageHelper.startPage(pageCurrent, pageSize);
}
}
创建ServletUtil类:
package com.cy.pj.common.util;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletUtil {
/**
* 获取HttpServletRequest请求对象
* @return
*/
public static HttpServletRequest getRequest(){
return getServletRequestAttributes().getRequest();
}
public static HttpServletResponse getResponse(){
return getServletRequestAttributes().getResponse();
}
/**
* 通过spring提供的RequestContextHolder对象获取请求属性对象
* @return
*/
public static ServletRequestAttributes getServletRequestAttributes(){
// String className=
// RequestContextHolder.getRequestAttributes().getClass().getName();
//System.out.println("className="+className);
return (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
}
}
创建StringUtil类:
package com.cy.pj.common.util;
public class StringUtil {
/**
* 判定字符串是否为空(null,"")
* @param content
* @return
*/
public static boolean isEmpty(String content){
return content==null||"".equals(content);
}
//....
}
以上是关于PageHelper插件的主要内容,如果未能解决你的问题,请参考以下文章
MyBatis分页插件:比PageHelper都要简单,使用很灵活,目前支持Oracle和MySQL
SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页