2020.5.27随记

2020.5.27随记

一. 使用AOP实现日志记录
二. Mybatis分页

一. 使用AOP实现日志记录

1. 创建一个自定义注解,格式如下:
package com.AOP.log;
 
import java.lang.annotation.*;
 
/**
 * ClassName Crmlog
 * AOP日志记录 自定义注解类
 * Date 2018年12月17日  14:27
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemCrmlog {
    /**
     * 日志描述
     */
    String description()  default "";
    
}

其中String description() default "";,用来存储注释的内容,你也可定义多几个。

2. 创建切面类
package com.AOP.log;
 
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
 
 
/**
 * @ClassName SystemLogAspect
 * @Author Administrator
 * @Describe  定义切入面类
 * @Date 2018/12/17 0017 14:49
 */
@Aspect
@Component
public class SystemLogAspect {
 
    /**
     * 注解Pointcut切入点
	*  即设置拦截方法的范围
     */
    @Pointcut("execution (* com.controller..*.*(..))")
    public void crmAspect() {
    }
 
 
    /**
     *抛出异常后通知(@AfterThrowing):方法抛出异常退出时执行的通知
     * 注意在这里不能使用ProceedingJoinPoint
     * 不然会报错ProceedingJoinPoint is only supported for around advice
     * throwing注解为错误信息
     * @param joinPoint
     * @param ex
     */
    @AfterThrowing(value="crmAspect()", throwing="ex")
    public void afterThrowingMethod(JoinPoint joinPoint, Exception ex) throws Exception {
        //获取Request,可以根据request获取session
        HttpServletRequest httpServletRequest = getHttpServletRequest();
        //获取参数信息
		Object[] arguments = joinPoint.getArgs();
        //获取注释信息
        String context=getServiceMthodDescription(joinPoint);
        //异常信息
        String exString ex.getMessage()
        //根据获取到的信息进行处理,保存到数据库或者存储到本地文件
	    ........
    }
 
 
    /**
     * @After, 而已根据自己的需要选择通知类型
     * crmAspect()指向需要控制的方法
     * @param joinPoint
     * @param returnValue  返回值
     * @throws Exception
     */
    @After(value = "crmAspect()")
    public  void doCrmLog(JoinPoint joinPoint) throws Exception {
        //获取Request,可以根据request获取session
        HttpServletRequest httpServletRequest = getHttpServletRequest();
        //获取参数信息
		Object[] arguments = joinPoint.getArgs();
        //获取注释信息
        String context=getServiceMthodDescription(joinPoint);
        //根据获取到的信息进行处理,保存到数据库或者存储到本地文件
	    ........
    }
 
 
    /**
     *获取自定义注解里的日志描述
     * @param joinPoint
     * @return 返回注解里面的日志描述
     * @throws Exception
     */
    private String getServiceMthodDescription(JoinPoint joinPoint)
            throws Exception {
        //类名
        String targetName = joinPoint.getTarget().getClass().getName();
        //方法名
        String methodName = joinPoint.getSignature().getName();
        //参数
        Object[] arguments = joinPoint.getArgs();
        //通过反射获取示例对象
        Class targetClass = Class.forName(targetName);
        //通过实例对象方法数组
        Method[] methods = targetClass.getMethods();
        String description = "";
        for(Method method : methods) {
            //判断方法名是不是一样
            if(method.getName().equals(methodName)) {
                //对比参数数组的长度
                Class[] clazzs = method.getParameterTypes();
                if(clazzs.length == arguments.length) {
                    //获取注解里的日志信息
                   if(method.getAnnotation(SystemCrmlog.class)!=null) {
                		description = method.getAnnotation(SystemCrmlog.class).description();
                		break;
                	}
                }
            }
        }
        return description;
    }
 

    /**
     * 获取当前的request
     * RequestContextHolder是SpringMvc用来管理Request的容器
     */
    public HttpServletRequest getHttpServletRequest(){
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes)ra;
        HttpServletRequest request = sra.getRequest();
        return request;
    }
}
3. 添加配置信息
<-- 开启Spring对@Aspect注解的支持 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<-- 让spring管理你的切面,你也可以使用扫描包的方式 -->
<bean id="systemLogAspect" class="com.miaoyi.util.log.SystemLogAspect"></bean>
4. 使用注解
@SystemCrmlog(description = "进行了登录操作")
public void login(){
    
}

当执行login方法后,就会被拦截并且去执行切面类的***doCrmLog***方法。

参考文章:https://blog.csdn.net/yjt520557/article/details/85099115

二. Mybatis实现分页

1. 直接使用sql语句分页
//使用limit i,n : i标识其实位置,n标识记录数量
select * from user limit ${pageSize*(pageNum-1)},#{pageSize}
2. 使用PageInfo分页
2.1 添加依赖
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>最新版本</version>
</dependency>
2.2 配置拦截器插件
//方式一,在Spring的配置文件中配置
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
    <property name="mapperLocations" value="classpath:com/miaoyi/mapper/**/*.xml" />
    <property name="typeAliasesPackage" value="com.isea533.ssm.model"/>
    <property name="plugins">
        <array>
            <bean class="com.github.pagehelper.PageHelper">
                <property name="properties">
                    <value>
                        dialect=mysql
                    </value>
                </property>
            </bean>
        </array>
    </property>
</bean>
//方式二,在Mybatis的配置文件中配置
<plugins>
    <!-- com.github.pagehelper为PageHelper类所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
        <property name="param1" value="value1"/>
	</plugin>
</plugins>
2.3 在代码中使用
//获取第1页,10条内容,默认查询总数count
PageHelper.startPage(1, 10);
List<User> list = userMapper.selectAll();
//用PageInfo对结果进行包装
PageInfo page = new PageInfo(list);

只需要在mapper方法执行前设置startPage方法就可以对查询结果进行分页。

参考文档:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值