1. 程式人生 > >Spring-boot 配置Aop獲取controller裡的request中的引數以及其返回值

Spring-boot 配置Aop獲取controller裡的request中的引數以及其返回值

轉自:http://ysj5125094.iteye.com/blog/2151855

前提條件:

除了spring相關jar包外,還需要引入aspectj包。

Xml程式碼 

  1. <dependency>  
  2.         <groupId>org.aspectj</groupId>  
  3.         <artifactId>aspectjweaver</artifactId>  
  4.         <version>1.7.2</version>  
  5.     </dependency>  

 

要實現此功能,必須完成以下幾步:

1.在springmvc-servlet.xml中實現對AOP的支援

Xml程式碼 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"   
  3.     xmlns:aop="http://www.springframework.org/schema/aop"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  7.     xsi:schemaLocation="     
  8.            http://www.springframework.org/schema/beans     
  9.            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd     
  10.            http://www.springframework.org/schema/context     
  11.            http://www.springframework.org/schema/context/spring-context-4.0.xsd    
  12.            http://www.springframework.org/schema/mvc     
  13.            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
  14.            http://www.springframework.org/schema/aop   
  15.            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">       
  16.     <aop:aspectj-autoproxy proxy-target-class="true"/>  
  17.     <bean class="com.yusj.interceptor.LogAspect" />  
  18. </beans>  

 

2.註解的方法實現Aspect

Java程式碼 

  1. package com.yusj.core.interceptor;  
  2. import java.text.SimpleDateFormat;  
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5. import javax.servlet.http.HttpServletRequest;  
  6. import org.aspectj.lang.JoinPoint;  
  7. import org.aspectj.lang.ProceedingJoinPoint;  
  8. import org.aspectj.lang.annotation.After;  
  9. import org.aspectj.lang.annotation.Around;  
  10. import org.aspectj.lang.annotation.Aspect;  
  11. import org.aspectj.lang.annotation.Before;  
  12. import org.slf4j.Logger;  
  13. import org.slf4j.LoggerFactory;  
  14. import org.springframework.web.context.request.RequestAttributes;  
  15. import org.springframework.web.context.request.RequestContextHolder;  
  16. import org.springframework.web.context.request.ServletRequestAttributes;  
  17. import com.google.gson.Gson;  
  18. /** 
  19.  *  
  20. * @ClassName: LogAspect  
  21. * @Description: 日誌記錄AOP實現  
  22. * @author shaojian.yu 
  23. * @date 2014年11月3日 下午1:51:59  
  24.  */  
  25. @Aspect  
  26. public class LogAspect {  
  27.     private final Logger logger = LoggerFactory.getLogger(this.getClass());  
  28.   
  29.     private String requestPath = null ; // 請求地址  
  30.     private String userName = null ; // 使用者名稱  
  31.     private Map<?,?> inputParamMap = null ; // 傳入引數  
  32.     private Map<String, Object> outputParamMap = null; // 存放輸出結果  
  33.     private long startTimeMillis = 0; // 開始時間  
  34.     private long endTimeMillis = 0; // 結束時間  
  35.   
  36.     /** 
  37.      *  
  38.      * @Title:doBeforeInServiceLayer 
  39.      * @Description: 方法呼叫前觸發  
  40.      *  記錄開始時間  
  41.      * @author shaojian.yu  
  42.      * @date 2014年11月2日 下午4:45:53 
  43.      * @param joinPoint 
  44.      */  
  45.     @Before("execution(* com.yusj.controller..*.*(..))")  
  46.     public void doBeforeInServiceLayer(JoinPoint joinPoint) {  
  47.         startTimeMillis = System.currentTimeMillis(); // 記錄方法開始執行的時間  
  48.     }  
  49.   
  50.     /** 
  51.      *  
  52.      * @Title:doAfterInServiceLayer 
  53.      * @Description: 方法呼叫後觸發  
  54.      *  記錄結束時間 
  55.      * @author shaojian.yu  
  56.      * @date 2014年11月2日 下午4:46:21 
  57.      * @param joinPoint 
  58.      */  
  59.     @After("execution(* com.yusj.controller..*.*(..))")  
  60.     public void doAfterInServiceLayer(JoinPoint joinPoint) {  
  61.         endTimeMillis = System.currentTimeMillis(); // 記錄方法執行完成的時間  
  62.         this.printOptLog();  
  63.     }  
  64.   
  65.     /** 
  66.      *  
  67.      * @Title:doAround 
  68.      * @Description: 環繞觸發  
  69.      * @author shaojian.yu  
  70.      * @date 2014年11月3日 下午1:58:45 
  71.      * @param pjp 
  72.      * @return 
  73.      * @throws Throwable 
  74.      */  
  75.     @Around("execution(* com.yusj.controller..*.*(..))")  
  76.     public Object doAround(ProceedingJoinPoint pjp) throws Throwable {  
  77.         /** 
  78.          * 1.獲取request資訊 
  79.          * 2.根據request獲取session 
  80.          * 3.從session中取出登入使用者資訊 
  81.          */  
  82.         RequestAttributes ra = RequestContextHolder.getRequestAttributes();  
  83.         ServletRequestAttributes sra = (ServletRequestAttributes)ra;  
  84.         HttpServletRequest request = sra.getRequest();  
  85.         // 從session中獲取使用者資訊  
  86.         String loginInfo = (String) session.getAttribute("username");  
  87.         if(loginInfo != null && !"".equals(loginInfo)){  
  88.             userName = operLoginModel.getLogin_Name();  
  89.         }else{  
  90.             userName = "使用者未登入" ;  
  91.         }  
  92.         // 獲取輸入引數  
  93.         inputParamMap = request.getParameterMap();  
  94.         // 獲取請求地址  
  95.         requestPath = request.getRequestURI();  
  96.           
  97.         // 執行完方法的返回值:呼叫proceed()方法,就會觸發切入點方法執行  
  98.         outputParamMap = new HashMap<String, Object>();  
  99.         Object result = pjp.proceed();// result的值就是被攔截方法的返回值  
  100.         outputParamMap.put("result", result);  
  101.           
  102.         return result;  
  103.     }  
  104.   
  105.     /** 
  106.      *  
  107.      * @Title:printOptLog 
  108.      * @Description: 輸出日誌  
  109.      * @author shaojian.yu  
  110.      * @date 2014年11月2日 下午4:47:09 
  111.      */  
  112.     private void printOptLog() {  
  113.         Gson gson = new Gson(); // 需要用到google的gson解析包  
  114.         String optTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTimeMillis);  
  115.         logger.info("\n user:"+userName  
  116.                 +"  url:"+requestPath+"; op_time:" + optTime + " pro_time:" + (endTimeMillis - startTimeMillis) + "ms ;"  
  117.                 +" param:"+gson.toJson(inputParamMap)+";"+"\n result:"+gson.toJson(outputParamMap));  
  118.     }  
  119. }