mvc 用户操作记录注解方式

package com.digitcore.log;


import java.lang.annotation.*;  




/** 
 *自定义注解 拦截Controller 
 */  
@Target({ElementType.PARAMETER, ElementType.METHOD})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
public @interface  SystemControllerLog {
String description()  default "";  

}


package com.digitcore.log;


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.lang.reflect.Method;
import java.util.Date;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
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 com.alibaba.druid.support.json.JSONUtils;
import com.digitcore.Const;
import com.digitcore.com.pojo.SysUserRolePermisionWrapper;
import com.digitcore.util.DateHelper;


/** 
 * 切点类 
 * @author tiangai 
 * @since 2014-08-05 Pm 20:35 
 * @version 1.0 
 */  
@Aspect
@Component
public class SystemLogAspect {


//注入Service用于把日志保存数据库  

    //本地异常日志记录对象  
     private  static  final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);  
  
    //Service层切点  
    @Pointcut("@annotation(com.digitcore.log.SystemServiceLog)")  
     public  void serviceAspect() {  
    }  
  
    //Controller层切点  
    @Pointcut("@annotation(com.digitcore.log.SystemControllerLog)")  
     public  void controllerAspect() {  
    }  
    /** 
     * 前置通知 用于拦截Controller层记录用户的操作 
     * 
     * @param joinPoint 切点 
     */  
    @Before("controllerAspect()")
     public  void doBefore(JoinPoint joinPoint) {
   
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
   
        //当前目录路径  
        //String currentPath=getClass().getResource(".").getFile().toString();  
        String currentPath = "/usr/local/apache-tomcat-7.0.70/logs/";
        String tempPath = currentPath+"operation_log_"+DateHelper.formatDateToStr(new Date(), "yyyy-MM-dd")+".txt";
   
        HttpSession session = request.getSession();  
        //读取session中的用户  
        SysUserRolePermisionWrapper sysUserRolePermisionWrapper = (SysUserRolePermisionWrapper) session.getAttribute(Const.CURR_USER);
        //请求的IP  
        String ip = request.getRemoteAddr();  
         try {
            //*========控制台输出=========*//  
            String method = (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()");  
            String methodText =getControllerMethodDescription(joinPoint);  
            String userName = sysUserRolePermisionWrapper.getAccountNumber();  
            String userIp = ip;  
            //*========数据库日志=========*//  
            String contxt =DateHelper.formatDateToStr(new Date(), "yyyy-MM-dd HH:mm:ss")+" ["+method+"]"+"--"+"["+methodText+"]"+"--"+"["+userName+"]"+"--"+"["+userIp+"]";
            WriteStringToFile(tempPath,contxt);
            
            System.out.println("=====前置通知结束=====");  
        }  catch (Exception e) {
            //记录本地异常日志  
        logger.error("==异常通知异常==");  
             logger.error("异常信息:{}", e.getMessage());  
        }  
    }
    
    
    /** 
     * 异常通知 用于拦截service层记录异常日志 
     * 
     * @param joinPoint 
     * @param e 
     */  
    @AfterThrowing(pointcut = "serviceAspect()", throwing = "e")  
     public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {  
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();  
        HttpSession session = request.getSession();  
        
        //当前目录路径  
        String currentPath=getClass().getResource(".").getFile().toString();  
        
        String tempPath = currentPath+"operation_log_"+DateHelper.formatDateToStr(new Date(), "yyyy-MM-dd")+".txt";
        
        //读取session中的用户  
        SysUserRolePermisionWrapper sysUserRolePermisionWrapper = (SysUserRolePermisionWrapper) session.getAttribute(Const.CURR_USER);
        //获取请求ip  
        String ip = request.getRemoteAddr();  
        //获取用户请求方法的参数并序列化为JSON格式字符串  
        String params = "";  
         if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {  
             for ( int i = 0; i < joinPoint.getArgs().length; i++) {  
                params += JSONUtils.toJSONString(joinPoint.getArgs()[i]) + ";";  
            }  
        }  
         try {  
              /*========控制台输出=========*/  
            System.out.println("=====异常通知开始=====");  
            System.out.println("异常代码:" + e.getClass().getName());  
            System.out.println("异常信息:" + e.getMessage());  
            System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));  
            System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));  
            System.out.println("请求人:" + sysUserRolePermisionWrapper.getAccountNumber());  
            System.out.println("请求IP:" + ip);  
            System.out.println("请求参数:" + params);  
            
            String method = (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()");
            String contxt = DateHelper.formatDateToStr(new Date(), "yyyy-MM-dd HH:mm:ss")+" ["+e.getClass().getName()+"]"+"["+e.getMessage()+"]"+"["+method+"]"+"["+sysUserRolePermisionWrapper.getAccountNumber()+"]"+"["+ip+"]";
            WriteStringToFile(tempPath,contxt);
            /*==========数据库日志=========*/  
        }  catch (Exception ex) {  
            //记录本地异常日志  
            logger.error("==异常通知异常==");  
            logger.error("异常信息:{}", ex.getMessage());  
        }  
         /*==========记录本地异常日志==========*/  
        logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName());  
  
    }  
    
    /** 
     * 获取注解中对方法的描述信息 用于service层注解 
     * 
     * @param joinPoint 切点 
     * @return 方法描述 
     * @throws Exception 
     */  
     public  static 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) {  
                    description = method.getAnnotation(SystemServiceLog. class).description();  
                     break;  
                }  
            }  
        }  
         return description;  
    }  
     
     /** 
      * 获取注解中对方法的描述信息 用于Controller层注解 
      * 
      * @param joinPoint 切点 
      * @return 方法描述 
      * @throws Exception 
      */  
      public  static String getControllerMethodDescription(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) {  
                     description = method.getAnnotation(SystemControllerLog. class).description();  
                      break;  
                 }  
             }  
         }  
          return description;  
     }  
      
      public void WriteStringToFile(String filePath,String contxt) {
          try {
              FileWriter fw = new FileWriter(filePath, true);
              BufferedWriter bw = new BufferedWriter(fw);
              bw.append(contxt+"\r\n");
              bw.close();
              fw.close();
          } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
}


package com.digitcore.log;


import java.lang.annotation.*;  


/** 
 *自定义注解 拦截service 
 */  
 @Target({ElementType.PARAMETER, ElementType.METHOD})  
 @Retention(RetentionPolicy.RUNTIME)  
 @Documented  
 public  @interface SystemServiceLog {  
String description()  default "";  
}





      http://www.springframework.org/schema/aop 
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd


<!-- 激活自动代理功能 -->


<aop:aspectj-autoproxy proxy-target-class="true"/>


@SystemControllerLog(description = "去详情页")

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值