随着机器的配置越来越好,使用注解分页无疑是更优雅更前卫的选择;当然任何时候都得考虑这种技术适用于什么场景。自定义注解分页适用于数据量较少的数据;
package com.annotation.page;
import java.lang.annotation.*;
/**
* @program: xxxx
* @description: PageSize注解类
* @author: an yu
* @create: 2020-03-23
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface PageQuery {
String pageIndexName() default "pageIndex";//页号的参数名
String pageSizeName() default "pageSize";//每页行数的参数名
}
package com.annotation.page;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
/**
* @program: xxxx
* @description: 自定义PageInfo
* @author: anyu
* @create: 2020-03-23
*/
@Data
@Accessors(chain = true)
@SuppressWarnings("all")
public class PageInfo implements Serializable {
private int pageNum; //
private int pageSize;
private long total;
private List<Object> list;
public PageInfo(int pageNum, int pageSize, long total, List<Object> list) {
this.pageNum = pageNum;
this.pageSize = pageSize;
this.total = total;
this.list = list;
}
public PageInfo(int pageNum, int pageSize, List<Object> list) {
this.pageNum = pageNum;
this.pageSize = pageSize;
this.list = list;
}
public PageInfo(List<Object> list) {
this.list = list;
}
public PageInfo() {
}
}
package com.annotation.page;
import com.alibaba.dubbo.common.utils.IOUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cdmtc.response.RespEntity;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
* @program: xxxx
* @description: 分页切面
* @author: anyu
* @create: 2020-03-23
*/
@Aspect
@Component
public class PageAspect {
private final static Logger LOGGER = LoggerFactory.getLogger(PageAspect.class);
@Around("@annotation(pageQuery)")
public Object pagingQuery(ProceedingJoinPoint joinPoint, PageQuery pageQuery) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Class<?> returnType = signature.getMethod().getReturnType();
if (("com.cdmtc.response.RespEntity").equals(returnType.getName())) {
/* 1. 获取分页名称*/
String pageIndexName = pageQuery.pageIndexName();
String pageSizeName = pageQuery.pageSizeName();
/* 2. 获取分页值 */
ServletRequestAttributes currentRequestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = currentRequestAttributes.getRequest();
String body = IOUtils.read(request.getReader());
JSONObject jsonObject = JSONObject.parseObject(body);
String pageNum = jsonObject.getString(pageIndexName);
String pageSize = jsonObject.getString(pageSizeName);
/* 3. 赋默认值 */
try {
/* 进行分页 */
Object respEntityObj = joinPoint.proceed();
RespEntity respEntity = JSON.parseObject(JSON.toJSONString(respEntityObj), RespEntity.class); // 这里根据自己的接口通用返回实体类进行对应修改
Object result = respEntity.getResult(); // 这里根据自己的接口通用返回实体类进行对应修改
List list = JSON.parseObject(JSON.toJSONString(result), List.class);
Integer pageNumInt = Integer.valueOf(pageNum);
Integer pageSizeInt = Integer.valueOf(pageSize);
List list1 = pageBySubList(list, pageNumInt, pageSizeInt);
PageInfo pageInfo = new PageInfo(pageNumInt, pageSizeInt, list.size(), list1); // 将结果存入
return RespEntity.success(pageInfo);
} catch (Exception e) {
LOGGER.error("查询失败", e);
return RespEntity.success(new PageInfo());
}
}
return joinPoint.proceed();
}
/**
* 利用subList方法进行分页
*
* @param list 分页数据
* @param pageSize 页面大小
* @param currentPage 当前页面
*/
public static List pageBySubList(List list, int currentPage, int pageSize) {
if (pageSize < 1 || currentPage < 1 || list.size() / pageSize < currentPage - 1) {
return new ArrayList();
}
return list.subList((currentPage - 1) * pageSize, pageSize * currentPage < list.size() ? pageSize * currentPage : list.size());
}
}
package com.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.io.Serializable;
/**
* @Create anyu
* @CraeteTime 2019/5/31
* @Description
*/
@Data
@ToString
public class PageQuery<T> implements Serializable {
private static final long serialVersionUID = 1918876594784006915L;
@ApiModelProperty(value="页码",name="pageIndex",example="1")
@NotBlank(message = "当前页不能为空")
@Pattern(regexp = "[1-9]\\d*",message = "参数错误")
private int pageIndex;
@ApiModelProperty(value="每页条数",name="pageSize",example="10")
@NotBlank(message = "每页记录数不能为空")
@Pattern(regexp = "[1-9]\\d*",message = "参数错误")
private int pageSize;
@ApiModelProperty(value="请求条件",name="param",example="")
private T param;
}
package com.controller;
import com.cdmtc.annotation.page.PageQuery;
import com.cdmtc.response.RespEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @program: xxxx
* @description: ceshilei
* @author: zhang lei
* @create: 2020-03-13
*/
@RestController
@RequestMapping("api")
@Api(value="CustomMonitor",tags={"测试类"})
public class DemoController {
@ApiOperation("测试分页集合")
@PostMapping("getList")
@PageQuery
public RespEntity getList(@RequestBody com.cdmtc.param.PageQuery<String> pageQuerys){
List<String> list=new ArrayList<>();
Collections.addAll(list,"0","1","2","3","4","5","6","7","8","9","10","11","12","13");
return RespEntity.success(list);
}
}
package com.response;
import com.model.response.RespResult;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.util.MultiValueMap;
import java.io.Serializable;
/**
* @create_by: anyu
* @craete_time 2019/7/17
*/
@Data
@Accessors(chain = true)
public class RespEntity implements Serializable {
public int errCode=0;
public String errMsg="success";
public Object result="";
private static final RespEntity fail = new RespEntity().setErrCode(1).setErrMsg("fail").setResult("");
private static final RespEntity success = new RespEntity().setResult("");
private RespEntity() {
}
public static RespEntity fail() {
return fail;
}
public static RespEntity success(){
return success;
}
public static RespEntity fail(String errMsg,Object object){
RespEntity fail= RespEntity.fail();
fail.setErrMsg(errMsg);
fail.setResult(object);
return fail;
}
public static RespEntity fail(String errMsg){
RespEntity fail= RespEntity.fail();
fail.setErrMsg(errMsg);
return fail;
}
public static RespEntity success(Object object){
RespEntity success = RespEntity.success;
success.setResult(object);
return success;
}
}