`
sungang_1120
  • 浏览: 310104 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类

spring AOP记录日志

阅读更多
package com.supinfo.jieneng.aop;

import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.supinfo.core.base.ServiceManager;
import com.supinfo.jieneng.domains.Admin;
import com.supinfo.jieneng.domains.Log;
import com.supinfo.util.DataUtil;

/**
 * 管理员操作日志记录
 * @author 
 *	
 */
@Aspect
public class LogAspect {
	
	@Autowired
	private ServiceManager serviceManager;
	
	//操作
	private static final String OP_UPDATE = "修改";
	private static final String OP_INSERT = "添加";
	private static final String OP_DELETE = "删除";
    /**
     * 筛选方法:
     * 
     */
	/*后台管理添加操作*/
    @Pointcut("execution(* com.supinfo.jieneng.services.*.insert*(..))")
    public void insertCall() { }
    
    @Pointcut("execution(* com.supinfo.jieneng.services.*.add*(..))")
    public void addCall() { }
    
    @Pointcut("execution(* com.supinfo.jieneng.services.*.save*(..))")
    public void saveCall() { }
    
    
    @Pointcut("( insertCall() || addCall() || saveCall() )")
    public void allInsertCall(){}
    
    /*后台管理修改操作*/
    @Pointcut("execution(* com.supinfo.jieneng.services.*.update*(..))")
    public void updateCall() { }
    @Pointcut("execution(* com.supinfo.jieneng.services.*.modify*(..))")
    public void modifyCall() { } 
    
    @Pointcut("( updateCall() || modifyCall() )")
    public void allUpdateCall() { }
    
    /*后台管理员删除*/
    @Pointcut("execution(* com.supinfo.jieneng.services.*.delete*(..))")
    public void deleteCall() { }
    @Pointcut("execution(* com.supinfo.jieneng.services.*.remove*(..))")
    public void removeCall() { }
    
    @Pointcut("(deleteCall() || removeCall())")
    public void allDeleteCall() { }
   
    
    
	/**
	 * 获取登录管理员ID
	 * 
	 * @return
	 */
	private Long loginUserId() {

		if(SecurityContextHolder.getContext() == null){
			return null;
		}
		
		if(SecurityContextHolder.getContext().getAuthentication() == null){
			return null;
		}
		
		UserDetails userDetails = (UserDetails) SecurityContextHolder
				.getContext().getAuthentication().getPrincipal();
		
		if(userDetails == null){
			return null;
		}
		
		String userName = userDetails.getUsername();
		
		if(DataUtil.isNullOrEmpty(userName)){
			return null;
		}
		
		// 根据用户名获取用户ID
		Admin admin = serviceManager.getAdminService().findAdminByNickname(userName);
		
		if(admin == null){
			return null;
		}
		
		return admin.getId();
	}
	
    /**
     * 管理员修改操作日志
     * @param joinPoint
     * @param rtv
     * @throws Throwable
     */
	@AfterReturning(value="allUpdateCall()", argNames="rtv", returning="rtv")
    public void allUpdateCallAfterCalls(JoinPoint joinPoint, Object rtv) throws Throwable{
		
		Long adminUserId = loginUserId();
		if(adminUserId == null){//没有管理员登录
			return;
		}
		
		//判断参数
		if(joinPoint.getArgs() == null){//没有参数
			return;
		}
		
		//获取操作方法名
		String optionMethodName = joinPoint.getSignature().getName();
		
		Log log = new Log();
		//用户编号
		log.setUserid(loginUserId());
		log.setCreatedate(new Date());
		//设置日志内容
		log.setContent(DataUtil.adminOptionContent(joinPoint.getArgs(),optionMethodName));
		log.setOperation(OP_UPDATE);
		serviceManager.getLogService().log(log);
	}
	
    /**
     * 管理员添加操作日志
     * @param joinPoint
     * @param rtv
     * @throws Throwable
     */
	@AfterReturning(value="allInsertCall()", argNames="rtv", returning="rtv")
    public void allInsertCallAfterCalls(JoinPoint joinPoint, Object rtv) throws Throwable{
		
		Long adminUserId = loginUserId();
		if(adminUserId == null){//没有管理员登录
			return;
		}
		
		//判断参数
		if(joinPoint.getArgs() == null){//没有参数
			return;
		}
		
		//获取操作方法名
		String optionMethodName = joinPoint.getSignature().getName();
		
		Log log = new Log();
		//用户编号
		log.setUserid(loginUserId());
		log.setCreatedate(new Date());
		//设置日志内容
		log.setContent(DataUtil.adminOptionContent(joinPoint.getArgs(),optionMethodName));
		log.setOperation(OP_INSERT);
		serviceManager.getLogService().log(log);
	}
	/**
	* @Description:  管理员删除日志记录
	* @方法名: allDeleteCallAfterCalls
	* @param : @param joinPoint
	* @param : @param rtv
	* @return void    返回类型
	* @throws 
	 */
	@AfterReturning(value="allDeleteCall()", argNames="rtv", returning="rtv")
	public void allDeleteCallAfterCalls(JoinPoint joinPoint,Object rtv) throws Throwable{
		Long adminUserId = loginUserId();
		if(adminUserId == null){//没有管理员登录
			return;
		}
		
		//判断参数
		if(joinPoint.getArgs() == null){//没有参数
			return;
		}
		//获取操作方法名
		String optionMethodName = joinPoint.getSignature().getName();
		
		Log log = new Log();
		//用户编号
		log.setUserid(loginUserId());
		log.setCreatedate(new Date());
		//设置日志内容
		log.setContent(DataUtil.adminOptionContent(joinPoint.getArgs(),optionMethodName));
		log.setOperation(OP_DELETE);
		serviceManager.getLogService().log(log);
	}
}

 

 

下面是通过反射 获取当前操作对象的参数值:

 

/**
	* @Description: 使用Java反射来获取被拦截方法(insert、update,delete)的参数值
	* @方法名: adminOptionContent
	* @param : @param args 参数
	* @param : @param optionMethodName 操作方法名
	* @return String    返回类型
	 */
	public static String adminOptionContent(Object[] args,String optionMethodName) throws Exception {

		if (args == null) {
			return null;
		}

		StringBuffer rs = new StringBuffer();
		
		//判断用户是 删除  修改 添加操作类型
		if (optionMethodName.startsWith("delete") || optionMethodName.startsWith("remove")) {
			//方法名
			rs.append("删除操作方法名:" + optionMethodName);
		}else if (optionMethodName.startsWith("insert") || optionMethodName.startsWith("add") || optionMethodName.startsWith("save")) {
			rs.append("添加操作方法名:" + optionMethodName);
		}else if (optionMethodName.startsWith("update") || optionMethodName.startsWith("modify")) {
			rs.append("修改操作方法名:" + optionMethodName);
		}
	
		String className = null;
		int index = 1;
		// 遍历参数对象
		for (Object info : args) {

			// 获取对象类型
			className = info.getClass().getName();
			className = className.substring(className.lastIndexOf(".") + 1);
			rs.append("[" + index + ",类型:" + className + ",值:");
			// 获取对象的所有方法
			Method[] methods = info.getClass().getDeclaredMethods();

			// 遍历方法,判断get方法
			for (Method method : methods) {
				String methodName = method.getName();
				// 判断是不是get方法 不是get方法
				if (methodName.indexOf("get") == -1) {
					continue;
				}

				Object rsValue = null;
				try {
					// 调用get方法,获取返回值
					rsValue = method.invoke(info);
					// 没有返回值
					if (rsValue == null) {
						continue;
					}
				} catch (Exception e) {
					continue;
				}

				// 将值加入内容中
				rs.append("(" + methodName + " : " + rsValue + ")");
			}

			rs.append("]");

			index++;
		}

		return rs.toString();
	}

 

 

Spring XML配置:

 <!-- 加入Aspectj 注解配置启动 -->  
<aop:aspectj-autoproxy />  
<!-- 日志 记录 AOP注入 -->
<bean id="logAspect" class="com.supinfo.jieneng.aop.LogAspect"/>	

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics