在spring boot中,簡單幾步,使用spring AOP實現一個攔截器:
1、引入依賴:
1
2
3
4
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-aop</ artifactId > </ dependency > |
1
2
3
4
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-aop</ artifactId > </ dependency > |
2、創建攔截器類(在該類中,定義了攔截規則:攔截com.xjj.web.controller包下面的所有類中,有@RequestMapping注解的方法。):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
/** * 攔截器:記錄用戶操作日志,檢查用戶是否登錄…… * @author XuJijun */ @Aspect @Component public class ControllerInterceptor { private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor. class ); @Value (“${spring.profiles}”) private String env; /** * 定義攔截規則:攔截com.xjj.web.controller包下面的所有類中,有@RequestMapping注解的方法。 */ @Pointcut (“execution(* com.xjj.web.controller..*(..)) and @annotation (org.springframework.web.bind.annotation.RequestMapping)”) public void controllerMethodPointcut(){} /** * 攔截器具體實現 * @param pjp * @return JsonResult(被攔截方法的執行結果,或需要登錄的錯誤提示。) */ @Around (“controllerMethodPointcut()”) //指定攔截器規則;也可以直接把“execution(* com.xjj………)”寫進這里 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<>(); //保存所有請求參數,用于輸出到日志中 logger.info(”請求開始,方法:{}”, methodName); Object result = null ; Object[] args = pjp.getArgs(); for (Object arg : args){ //logger.debug(“arg: {}”, arg); if (arg instanceof Map<?, ?>) { //提取方法中的MAP參數,用于記錄進日志中 @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(不知道登錄賬號?請聯系老許。)”, null ); } } //獲取query string 或 posted form data參數 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 ){ // 一切正常的情況下,繼續執行被攔截的方法 result = pjp.proceed(); } } catch (Throwable e) { logger.info(”exception: ”, e); result = new JsonResult(ResultCode.EXCEPTION, “發生異常:”+e.getMessage()); } if (result instanceof JsonResult){ long costMs = System.currentTimeMillis() - beginTime; logger.info(”{}請求結束,耗時:{}ms”, methodName, costMs); } return result; } /** * 判斷一個方法是否需要登錄 * @param method * @return */ private boolean isLoginRequired(Method method){ if (!env.equals(“prod”)){ //只有生產環境才需要登錄 return false ; } boolean result = true ; if (method.isAnnotationPresent(Permission. class )){ result = method.getAnnotation(Permission. class ).loginReqired(); } return result; } //判斷是否已經登錄 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; }*/ } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
/** * 攔截器:記錄用戶操作日志,檢查用戶是否登錄…… * @author XuJijun */ @Aspect @Component public class ControllerInterceptor { private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor. class ); @Value ( "${spring.profiles}" ) private String env; /** * 定義攔截規則:攔截com.xjj.web.controller包下面的所有類中,有@RequestMapping注解的方法。 */ @Pointcut ( "execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)" ) public void controllerMethodPointcut(){} /** * 攔截器具體實現 * @param pjp * @return JsonResult(被攔截方法的執行結果,或需要登錄的錯誤提示。) */ @Around ( "controllerMethodPointcut()" ) //指定攔截器規則;也可以直接把“execution(* com.xjj.........)”寫進這里 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<>(); //保存所有請求參數,用于輸出到日志中 logger.info( "請求開始,方法:{}" , methodName); Object result = null ; Object[] args = pjp.getArgs(); for (Object arg : args){ //logger.debug("arg: {}", arg); if (arg instanceof Map<?, ?>) { //提取方法中的MAP參數,用于記錄進日志中 @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(不知道登錄賬號?請聯系老許。)" , null ); } } //獲取query string 或 posted form data參數 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 ){ // 一切正常的情況下,繼續執行被攔截的方法 result = pjp.proceed(); } } catch (Throwable e) { logger.info( "exception: " , e); result = new JsonResult(ResultCode.EXCEPTION, "發生異常:" +e.getMessage()); } if (result instanceof JsonResult){ long costMs = System.currentTimeMillis() - beginTime; logger.info( "{}請求結束,耗時:{}ms" , methodName, costMs); } return result; } /** * 判斷一個方法是否需要登錄 * @param method * @return */ private boolean isLoginRequired(Method method){ if (!env.equals( "prod" )){ //只有生產環境才需要登錄 return false ; } boolean result = true ; if (method.isAnnotationPresent(Permission. class )){ result = method.getAnnotation(Permission. class ).loginReqired(); } return result; } //判斷是否已經登錄 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、測試
瀏覽器中輸入:http://localhost:8082/api/admin/login
測試結果:
1
2
|
2016-07-26 11:58:12,057:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:58) - 請求開始,方法:login 2016-07-26 11:58:12,061:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:103) - login請求結束,耗時:8ms |
1
2
|
2016-07-26 11:58:12,057:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:58) - 請求開始,方法:login 2016-07-26 11:58:12,061:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:103) - login請求結束,耗時:8ms |
證明攔截器已經生效。
源代碼參考:https://github.com/xujijun/my-spring-boot
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/zmken497300/article/details/53516764