spring boot如何使用spring AOP實(shí)現(xiàn)攔截器
在spring boot中,簡(jiǎn)單幾步,使用spring AOP實(shí)現(xiàn)一個(gè)攔截器:
1、引入依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2、創(chuàng)建攔截器類(在該類中,定義了攔截規(guī)則:攔截com.xjj.web.controller包下面的所有類中,有@RequestMapping注解的方法。):
/** * 攔截器:記錄用戶操作日志,檢查用戶是否登錄…… * @author XuJijun */ @Aspect @Component public class ControllerInterceptor { private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class); @Value("${spring.profiles}") private String env; /** * 定義攔截規(guī)則:攔截com.xjj.web.controller包下面的所有類中,有@RequestMapping注解的方法。 */ @Pointcut("execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)") public void controllerMethodPointcut(){} /** * 攔截器具體實(shí)現(xiàn) * @param pjp * @return JsonResult(被攔截方法的執(zhí)行結(jié)果,或需要登錄的錯(cuò)誤提示。) */ @Around("controllerMethodPointcut()") //指定攔截器規(guī)則;也可以直接把“execution(* com.xjj.........)”寫進(jìn)這里 public Object Interceptor(ProceedingJoinPoint pjp){ long beginTime = System.currentTimeMillis(); MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); //獲取被攔截的方法 String methodName = method.getName(); //獲取被攔截的方法名 Set<Object> allParams = new LinkedHashSet<>(); //保存所有請(qǐng)求參數(shù),用于輸出到日志中 logger.info("請(qǐng)求開始,方法:{}", methodName); Object result = null; Object[] args = pjp.getArgs(); for(Object arg : args){ //logger.debug("arg: {}", arg); if (arg instanceof Map<?, ?>) { //提取方法中的MAP參數(shù),用于記錄進(jìn)日志中 @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) arg; allParams.add(map); }else if(arg instanceof HttpServletRequest){ HttpServletRequest request = (HttpServletRequest) arg; if(isLoginRequired(method)){ if(!isLogin(request)){ result = new JsonResult(ResultCode.NOT_LOGIN, "該操作需要登錄!去登錄嗎?\n\n(不知道登錄賬號(hào)?請(qǐng)聯(lián)系老許。)", null); } } //獲取query string 或 posted form data參數(shù) Map<String, String[]> paramMap = request.getParameterMap(); if(paramMap!=null && paramMap.size()>0){ allParams.add(paramMap); } }else if(arg instanceof HttpServletResponse){ //do nothing... }else{ //allParams.add(arg); } } try { if(result == null){ // 一切正常的情況下,繼續(xù)執(zhí)行被攔截的方法 result = pjp.proceed(); } } catch (Throwable e) { logger.info("exception: ", e); result = new JsonResult(ResultCode.EXCEPTION, "發(fā)生異常:"+e.getMessage()); } if(result instanceof JsonResult){ long costMs = System.currentTimeMillis() - beginTime; logger.info("{}請(qǐng)求結(jié)束,耗時(shí):{}ms", methodName, costMs); } return result; } /** * 判斷一個(gè)方法是否需要登錄 * @param method * @return */ private boolean isLoginRequired(Method method){ if(!env.equals("prod")){ //只有生產(chǎn)環(huán)境才需要登錄 return false; } boolean result = true; if(method.isAnnotationPresent(Permission.class)){ result = method.getAnnotation(Permission.class).loginReqired(); } return result; } //判斷是否已經(jīng)登錄 private boolean isLogin(HttpServletRequest request) { return true; /*String token = XWebUtils.getCookieByName(request, WebConstants.CookieName.AdminToken); if("1".equals(redisOperator.get(RedisConstants.Prefix.ADMIN_TOKEN+token))){ return true; }else { return false; }*/ } }
3、測(cè)試
瀏覽器中輸入:http://localhost:8082/api/admin/login
測(cè)試結(jié)果:
2016-07-26 11:58:12,057:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:58) - 請(qǐng)求開始,方法:login 2016-07-26 11:58:12,061:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:103) - login請(qǐng)求結(jié)束,耗時(shí):8ms
證明攔截器已經(jīng)生效。
源代碼參考:https://github.com/xujijun/my-spring-boot
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java 反射調(diào)用靜態(tài)方法的簡(jiǎn)單實(shí)例
下面小編就為大家?guī)?lái)一篇Java 反射調(diào)用靜態(tài)方法的簡(jiǎn)單實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-06-06Java中forEach使用lambda表達(dá)式,數(shù)組和集合的區(qū)別說(shuō)明
這篇文章主要介紹了Java中forEach使用lambda表達(dá)式,數(shù)組和集合的區(qū)別說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07Java中的synchronized和ReentrantLock的區(qū)別詳細(xì)解讀
這篇文章主要介紹了Java中的synchronized和ReentrantLock的區(qū)別詳細(xì)解讀,synchronized是Java內(nèi)建的同步機(jī)制,所以也有人稱其為 IntrinsicLocking,它提供了互斥的語(yǔ)義和可見性,當(dāng)一個(gè)線程已經(jīng)獲取當(dāng)前鎖時(shí),其他試圖獲取的線程只能等待或者阻塞在那里,需要的朋友可以參考下2024-01-01詳解Java編程中統(tǒng)一資源定位符URL的相關(guān)使用
這篇文章主要介紹了Java編程中統(tǒng)一資源定位符URL的相關(guān)使用,是Java網(wǎng)絡(luò)編程中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-10-10Spring?Lifecycle?和?SmartLifecycle區(qū)別面試精講
這篇文章主要為大家介紹了Spring?Lifecycle和SmartLifecycle的區(qū)別面試精講,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10