注意:這種方式須要JDK1.8版本支持java
開始:web
1.aop配置:
<aop:aspectj-autoproxy expose-proxy="true" />
spring
- 注意該配置須要配置在spring mvc的配置文件中,由於須要攔截controller層方法
- 或者在必需要配置在spring配置文件中的狀況下,同時須要攔截controller層的方法,能夠在spring配置文件中加入controller層的包掃描
2.具體代碼:apache
import org.apache.commons.lang3.ArrayUtils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 請求參數攔截校驗 */ @Aspect public class AopParamVerify { private static Logger log = LoggerFactory.getLogger(AopParamVerify.class); @Around(value = "execution(* com.website.controller..*.*(..))") public Object invoke(ProceedingJoinPoint joinPoint) { /** * 時間戳校驗,超過一分鐘,攔截 */ //返回結果封裝類 HzlqswReqResult rst = new HzlqswReqResult(); //1.這裏獲取到全部的參數值的數組 Object[] args = joinPoint.getArgs(); Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; //2.最關鍵的一步:經過這獲取到方法的全部參數名稱的字符串數組 String[] parameterNames = methodSignature.getParameterNames(); try { //3.經過你須要獲取的參數名稱的下標獲取到對應的值 int timeStampIndex = ArrayUtils.indexOf(parameterNames, "timeStamp"); if (timeStampIndex != -1) { long timeStamp = (Long) args[timeStampIndex]; if (System.currentTimeMillis() - timeStamp > 60000) { rst.setResultCode(rst.resultCode_hashCode_overdue); rst.setReturnMsg("時間戳過時"); rst.setReturnObject("時間戳過時"); return rst; } } return joinPoint.proceed(); } catch (Throwable throwable) { log.error("時間戳校驗異常"); throwable.printStackTrace(); rst.setResultCode(rst.resultCode_error); rst.setReturnMsg("AOP校驗異常"); rst.setReturnObject("AOP校驗異常"); return rst; } } }