diff --git a/src/main/java/com/corewing/app/common/page/PageContext.java b/src/main/java/com/corewing/app/common/page/PageContext.java new file mode 100644 index 0000000..435a37e --- /dev/null +++ b/src/main/java/com/corewing/app/common/page/PageContext.java @@ -0,0 +1,23 @@ +package com.corewing.app.common.page; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; + +public class PageContext { + private static final ThreadLocal> PAGE_HOLDER = new ThreadLocal<>(); + + // 设置分页对象 + public static void setPage(Page page) { + PAGE_HOLDER.set(page); + } + + // 泛型方法:获取指定类型的分页对象(消除警告) + @SuppressWarnings("unchecked") + public static Page getPage(Class clazz) { + return (Page) PAGE_HOLDER.get(); + } + + // 清除线程变量 + public static void clear() { + PAGE_HOLDER.remove(); + } +} \ No newline at end of file diff --git a/src/main/java/com/corewing/app/common/page/PageInterceptor.java b/src/main/java/com/corewing/app/common/page/PageInterceptor.java new file mode 100644 index 0000000..74576e6 --- /dev/null +++ b/src/main/java/com/corewing/app/common/page/PageInterceptor.java @@ -0,0 +1,53 @@ +package com.corewing.app.common.page; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class PageInterceptor implements HandlerInterceptor { + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + // 默认分页参数 + int pageNum = 1; + int pageSize = 10; + + // 从请求参数中获取分页信息 + String current = request.getParameter("current"); + String size = request.getParameter("size"); + + // 解析页码 + if (current != null && !current.isEmpty()) { + try { + pageNum = Integer.parseInt(current); + if (pageNum < 1) pageNum = 1; // 页码不能小于1 + } catch (NumberFormatException e) { + // 非法参数使用默认值 + } + } + + // 解析每页条数 + if (size != null && !size.isEmpty()) { + try { + pageSize = Integer.parseInt(size); + if (pageSize < 1) pageSize = 10; // 每页条数不能小于1 + if (pageSize > 100) pageSize = 100; // 限制最大条数 + } catch (NumberFormatException e) { + // 非法参数使用默认值 + } + } + + // 创建 MyBatis-Plus 的 Page 对象并存储到 ThreadLocal + Page page = new Page<>(pageNum, pageSize); + PageContext.setPage(page); + return true; + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + // 清除ThreadLocal中的数据,防止内存泄漏 + PageContext.clear(); + } +}