自定义注解结合pageHelper实现分页

话不多说,直接上代码

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxuwz.common.AjaxResult;
import com.gxuwz.utils.ServletUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.List;
import static com.gxuwz.common.Constants.PAGE_NUM;
import static com.gxuwz.common.Constants.PAGE_SIZE;

/**
 * // 获得当前访问的class
 * Class<?> className = joinPoint.getTarget().getClass();
 * // 获得访问的方法名
 * String methodName = joinPoint.getSignature().getName();
 * // 得到方法的参数的类型
 * Class<?>[] argClass = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
 * // 得到访问的方法对象
 * Method method = className.getMethod(methodName, argClass);
 * // 取消对权限的检查 实现对私有的访问和赋值,提高反射速度
 * method.setAccessible(true);
 * 
 *
 */
@Component
@Aspect
public class PageAspect {

    @Pointcut("@annotation(com.gxuwz.annotation.EnablePaging)")
    public void annotationPointcut() {
    }
	// 实现分页只需该方法即可
    @Around("annotationPointcut()")
    public AjaxResult doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Integer pageNum = ServletUtils.getParameterToInt(PAGE_NUM);
        Integer pageSize = ServletUtils.getParameterToInt(PAGE_SIZE);
        if (Validator.isNotNull(pageNum) && Validator.isNotNull(pageSize)) {
            // 设置分页,setReasonable -> 使分页参数合理化
            Page<?> objectPage = PageHelper.startPage(pageNum, pageSize).setReasonable(true);
            AjaxResult ajax = (AjaxResult) joinPoint.proceed();
            ajax.put("total",objectPage.getTotal());
            return ajax;
        }
        return (AjaxResult) joinPoint.proceed();
    }


    /**
     * 后置返回通知 可更改返回值
     * 这里需要注意的是:
     * 如果参数中的第一个参数为JoinPoint,则第二个参数为返回值的信息
     * 如果参数中的第一个参数不为JoinPoint,则第一个参数为returning中对应的参数
     * returning 限定了只有目标方法返回值与通知方法相应参数类型时才能执行后置返回通知,否则不执行,对于returning对应的通知方法参数为Object类型将匹配任何目标返回值
     */
    @AfterReturning(value = "annotationPointcut()", returning = "keys")
    public void doAfterReturningAdvice1(JoinPoint joinPoint, AjaxResult keys) {
        keys.put("hhh","哈哈哈");
    }
}

ps:这里自定义注解在controller层,要注意spring-mvc.xml要加上<aop:aspectj-autoproxy/>配置aspectj自动代理,不然会进不去切面

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值