1 : 로그 엔티티 클래스
공개 클래스 syslog { / *** / private Integer ID; / ** 로그 설명*/ 개인 문자열 설명; / ** 실행 방법*/ 개인 문자열 메서드; /** 로그 유형 0 : 작동 로그; 1 : 예외 로그*/ 개인 정수 로그 타입; / ** 클라이언트가 요청한 IP 주소*/ 개인 문자열 requestIP; / ** 예외 코드*/ private String ExceptionCode; / ** 예외 세부 사항*/ 개인 문자열 예외 시간; / ** 요청 매개 변수*/ 개인 문자열 매개 변수; / ** 연산자*/ 개인 문자열 CreateBy; / ** 작동 시간*/ 개인 문자열 생성물; 공개 정수 getId () {return id; } public void setId (정수 ID) {this.id = id; } public String getDescription () {return description; } public void setDescription (문자열 설명) {this.Description = 설명; } public String getMethod () {return 메소드; } public void setMethod (문자열 메서드) {this.Method = 메소드; } public Integer getLogType () {return logtype; } public void setLogType (정수 logtype) {this.logtype = logtype; } public String getRequestip () {return requestip; } public void setRequestip (String requestIP) {this.requestip = requestip; } public String getExceptionCode () {return ExceptionCode; } public void setExceptionCode (String ExceptionCode) {this.exceptionCode = ExceptionCode; } public String getExceptionDetail () {return ExceptionDetail; } public void setExceptionDetail (String ExceptionDetail) {this.ExceptionDetail = ExceptionDetail; } public String getParams () {return params; } public void setparams (String params) {this.params = params; } public String getCreateBy () {return createby; } public void setcreateby (String CreateBy) {this.createby = createby; } public string getCreatedate () {return readate; } public void setCreatedate (String radeate) {this.createdate = createate; }}2 : Maven이 요구하는 항아리
<pectionency> <groupId> org.aspectj </groupid> <artifactid> agagjrt </artifactid> <bersion> 1.7.4 </version> </fectionency> <pectionency> <groupId> org.aspectj </groupId> <artifactid> aggeweaver </artifactid> 1.7.4 </dependency> </dependency> </version> </version> <groupid> cglib </groupid> <artifactid> cglib </artifactid> <bersion> 2.1_3 </version> </dependency> <pectionency> <groupid> org.springframework </groupid> <artifactid> Spring-Aop </artifactid> <version> 4.2. Release> </dependency>
이 프로젝트는 JDK1.7을 사용해야합니다
3 : springservlet-mvc.xml
<!-프록시-타겟 클래스 = "True"CGLIB 프록시 사용을 강제로합니다. False 인 경우 Spring은 자동으로 선택합니다 .-> <AOP : SALSE-AUTOPPROXY Proxy-Target Class = "True"/>
프록시-표적 클래스 = "true"를 추가하는 것은 컨트롤러의 메소드를 가로 채는 것입니다.
4 : 섹션을 정의하면 주로 사전 통과 및 예외 알림을 여기에 작성합니다.
아래는 사용자 정의 주석입니다
import java.lang.annotation.*; @target ({elementtype.parameter, elementtype.method}) @retention (retentionpolicy.runtime) @documented public @interface log {/ ** 수행 할 작업 유형 : 작업 추가 **/ public string tempepe () 기본값 ""; / ** 수행 할 특정 작업 (예 : 다음과 같이 수행 할 특정 작업).얼굴 절단
import java.lang.reflect.method; import java.text.simpledateformat; import java.util.arrays; import java.util.date; import javax.annotation.resource; import javax.servlet.http.httpservletrequest; import javax.servlet.htttttttect org.aspectj.lang.joinpoint; import org.aspectj.lang.proeessingjoinpoint; import org.aspectj.lang.annotation.after; import org.aspectj.lang.annotation.afterreturning; import org.aspectj.lang.annotation.afterthrowing; import org.asj.lang org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation.before; import org.aspectj.lang.annotation.annotation.annotation.pointcut; import org.slf4j.logger; import org.slf4j.loggeractory; import org.spramepramework.component; import; org.springframework.web.context.request.requestcontextholder; import org.springframework.web.context.request.servletrequestattributes; import com.gtcity.user.model.syslog; import com.gtcity.user.model.sysuser; com.gtcity.user.service.syslogservice;/** * @author panliang * @version creation time : 2017-3-31 * @desc point-cut class * */ @componentpublic class @componentpublic class systemlogaspect {// sysource systemlogservice에 로그를 저장하기 위해 {// systemlogservice; 개인 정적 최종 로거 로거 = loggerfactory.getLogger (SystemLogaspect. Class); // 컨트롤러 레이어 탄젠트 포인트 // 첫 번째 *는 모든 반환 값 유형을 나타냅니다. // 두 번째 *는 모든 클래스를 나타냅니다. // 세 번째 *는 클래스의 모든 메소드를 나타냅니다. // 마지막 매개 변수를 나타냅니다. @PointCut ( "execution (* com.gtcity.web.web.controller ..*.* (..))") public void controlleraspect () {} /**** @author : panliang* @time : 2017-3-31 2:22:16 pm* @param point point-cut* @description : pre-notification은 상호 사용됩니다. @Before ( "ControlLerAspect ()") public void dobefore (joinpoint joinpoint) {/* system.out.println ( "======================================================================================================================== System.out.info ( " + joinpoint request}; session.getattribute (user = user = null); getSignature () getName []; method.getParameterTypes (); System.out.println ( "============= 컨트롤러 프리-노트 시작 =============); System.out.out.println ("요청 메소드 : " + (joinpoint.getTarget (). getClass (). getName () +". " + joinPoint.getSignature () +" + "()" System.out.println (메소드 설명 : " + user system.out.out.out.println; Log.SetDescription (OperationName); log.setexceptiondetail (null) systemlogservice.insert (log). @Author : Panliang * @Time : 2017-3-31 2:24:36 PM * @param joinpoint point-cut * @description : 예외 알림은 예외 로그를 가로 채고 기록하는 데 사용됩니다. (servletrequestattributes) getRequest 세션 (); user ");} // 요청 된 IP 문자열 ip = request.getRemoteaddr (); String params =" "; if (joinpoint.getargs ()! = null && joinpoint.getargs (). length> 0) {joinpoint.getargs ()); getTarget (). getName (); if (method.getname (methodname)) {clazzs = method.getParameterTypes (clazzs.length == arguments.length) {getAntantation (log.class). /*============== Console Output ========* / System.out.println ( "============== 예외 알림 시작 ====================================================================================================================================== ========================================================================================================= ========================================================================================================= ========================================================================================================= System.out.println (예외 정보 : " + e.getMessage ());"예외 메소드 : " + (joinpoint.getTarget (). getName () +". system.out.println ( "requester :" + user.getusername ()); log.setexceptioncode (e.getclass () .setLogType (1); "()"); System.out.println ( "=========== 예외 알림 end ==========);} catch (예외) {// 로컬 예외 알림 ("== 예외 알림 예외 == "); logger.error ("예외 정보 : {} ", ex.getMessage ());});}); log ================ gger.error ( "예외 메소드 : {} 예외 코드 : {} 예외 정보 : {}" ", joinpoint.getTarget (). getName () + joinPoint.getSignature (), e.getclass ().5 : 컨트롤러에서
/** * 사용자 이름과 비밀번호가 올바른지 여부를 결정하기 위해 사용자 이름을 기반으로 암호를 찾으십시오 * @Author panliang * @param request * @param response * @throws ioexception */ @requestMapping */ @requestMapping */ @regimpe.do (OperationType = ", OperationName ="user login ") // note가 추가되지 않을 것입니다. Skippage (httpservletRequest 요청, httpservletResponse 응답)는 ioException {modelAndView result = null; String username = request.getParameter ( "email"); String password = request.getParameter ( "password"); int flag = sysuserVice.login (request, username, password); new (new); ModelAndView ( "Redirect : /login/dispacher_main.do");} else if (flag == 2) {// 사용자 이름이 존재하지 않습니다. ModelAndView ( "retirect : /login/login.do? errorcode = 2");} return result;}다른 세 가지 알림에 대해 알고 싶은 사람들은이 블로그 게시물을 참조하십시오. 링크를 열려면 클릭하십시오.
이러한 방식으로 사용자가 배경에 액세스 할 때 일반 액세스 또는 버그 데이터베이스인지 기록이 있습니다.
글로벌 로그 관리를 구현하기위한 위의 AOP 주석 방법은 내가 공유 한 모든 컨텐츠입니다. 나는 당신이 당신에게 참조를 줄 수 있기를 바랍니다. 그리고 당신이 wulin.com을 더 지원할 수 있기를 바랍니다.