spring op 구현(사용자 조작 기록,기록)

http://tiangai.iteye.com/blog/2103708
첫 번 째 단 계 는 두 개의 주 해 를 정의 합 니 다.
Java 코드 패키지 com.annotation;
import java.lang.annotation.*;
/**사용자 정의 주해 차단 컨트롤 러*/
@Target({ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface SystemControllerLog {
String description() default "";  

}
package com.annotation;
import java.lang.annotation.*;
/**사용자 정의 주석 차단 서비스*/
@Target({ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface SystemServiceLog {
String description() default "";  

}두 번 째 단 계 는 절 점 클래스 를 만 듭 니 다:
Java 코드 패키지 com.annotation;
import com.model.Log; import com.model.User; import com.service.LogService; import com.util.DateUtil; import com.util.JSONUtil; import com.util.SpringContextHolder; import com.util.WebConstants; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; 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.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.lang.reflect.Method;
/**
  • 절 점 류
  • @author tiangai
  • @since 2014-08-05 Pm 20:35
  • @version 1.0*/@Aspect@Component public class SystemLogAspect{/주입 Service 는 로 그 를 데이터베이스@Resource private LogService logService 에 저장 합 니 다.//로 컬 이상 로그 기록 대상 개인 static final Logger logger=LoggerFactory.getLogger(System LogAspect.class);/서비스 계층 접점@Pointcut("@annotation(com.annotation.System ServiceLog)")public void serviceAspect(){}/Control 계층 접점@Pointcut("@annotation(com.annotation.System Controller Log)")public void controllerAspect(){}/**
  • 사전 알림 은 컨트롤 러 층 이 사용 자 를 기록 하 는 작업 을 차단 하 는 데 사 용 됩 니 다

  • @param joinPoint 접점*/@Before("controllerAspect()")public void doBefore(JoinPoint joinPoint){HttpServletRequest request=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes().getRequest();HttpSession session = request.getSession(); //session 의 사용자 User user=(User)session.getAttribute(WebConstants.CURRENT 읽 기USER); //요청 한 IP String ip=request.getRemoteAddr();try{//콘 솔 출력=/System.out.println("=사전 알림 시작=");System.out.println("요청 방법:"+(joinPoint.getTarget().getClass().getName()+"."+joinPoint.getSignature().getName()+"()"));System.out.println("방법 설명:"+getController MethodDescription(joinPoint));System.out.println("요청 자:"+user.getName());System.out.println("IP 요청:"+ip);/데이터베이스 로그=/로그 로그 로그=SpringContextHolder.getBean("logxx");log.setDescription(getControllerMethodDescription(joinPoint)); log.setMethod((joinPoint.getTarget().getClass().getName() + “.” + joinPoint.getSignature().getName() + “()”)); log.setType(“0”); log.setRequestIp(ip); log.setExceptionCode(null); log.setExceptionDetail(null); log.setParams(null); log.setCreateBy(user); log.setCreateDate(DateUtil.getCurrentDate()); //데이터베이스 logService.add 저장 하기;System.out.println("=사전 알림 끝=");}catch(Exception e){/로 컬 이상 로그 logger.error("사전 알림 이상")를 기록 합 니 다.logger.error("이상 정보:{}",e.getMessage());}

  • /**
  • 이상 알림 은 서비스 계층 의 이상 로 그 를 차단 하 는 데 사 용 됩 니 다

  • @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(); //session 의 사용자 User user=(User)session.getAttribute(WebConstants.CURRENT 읽 기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 += JSONUtil.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("요청 자:"+user.getName());System.out.println("IP 요청:"+ip);System.out.println("요청 인자:"+params);/==데이터베이스 로그=/로그 로그 로그=SpringContextHolder.getBean("logxx");log.setDescription(getServiceMthodDescription(joinPoint)); log.setExceptionCode(e.getClass().getName()); log.setType(“1”); log.setExceptionDetail(e.getMessage()); log.setMethod((joinPoint.getTarget().getClass().getName() + “.” + joinPoint.getSignature().getName() + “()”)); log.setParams(params); log.setCreateBy(user); log.setCreateDate(DateUtil.getCurrentDate()); log.setRequestIp(ip); //데이터베이스 logService.add 저장 하기;System.out.println("=이상 알림 종료=");}catch(Exception ex){/로 컬 이상 로그 logger.error("이상 알림 이상")를 기록 합 니 다.logger.error("이상 정보:{}",ex.getMessage());}/로 컬 이상 로그*/logger.error("이상 방법:{}이상 코드:{}이상 정보:{}인자:{}",joinPoint.getTarget().getClass().getName()+joinPoint.getSignature().getName(),e.getClass().getName(),e.getMessage(),params)를 기록 합 니 다.

  • } /**
  • 주석 에서 방법 에 대한 설명 정 보 를 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; } } 세 번 째 단 계 는 Controller 의 대리 권 을 cglib
  • 에 게 맡 깁 니 다.

    응용 프로그램 Context 를 실례 화 할 때 추가 해 야 합 니 다.
    Xml 코드
    op:aspectj-autoproxy/컨트롤 러 를 호출 할 때 AOP 가 역할 을 하기 때문에 SpringMVC 설정 파일 에 추가 합 니 다.
    Xml 코드

    좋은 웹페이지 즐겨찾기