1、在Web請求處理的程序中,攔截器是服務器端進行資料處理的最后一道屏障,可以將所有用戶請求的資訊在攔截器中進行驗證,在SpringBoot中可以繼續使用SpringMVC所提供的攔截器進行處理,
1 package com.demo.config;
2
3 import java.lang.reflect.Method;
4
5 import javax.servlet.http.HttpServletRequest;
6 import javax.servlet.http.HttpServletResponse;
7
8 import org.springframework.web.method.HandlerMethod;
9 import org.springframework.web.servlet.HandlerInterceptor;
10 import org.springframework.web.servlet.ModelAndView;
11
12 /**
13 *
14 * @author 實作攔截器介面
15 *
16 */
17 public class MyInterceptor implements HandlerInterceptor {
18
19 long start = System.currentTimeMillis();
20
21 @Override
22 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
23 throws Exception {
24 // 攔截器處理代碼
25
26 }
27
28 @Override
29 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
30 ModelAndView modelAndView) throws Exception {
31 HandlerMethod handlerMethod = (HandlerMethod) handler;
32 // 攔截器處理代碼
33 System.out.println("Interceptor cost=" + (System.currentTimeMillis() - start));
34 }
35
36 /**
37 * 在攔截器中最需要用戶處理的方法是preHandle(),此方法會在控制層的方法執行之前進行呼叫,
38 */
39 @Override
40 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
41 throws Exception {
42 start = System.currentTimeMillis();
43 HandlerMethod handlerMethod = (HandlerMethod) handler;
44 // 攔截器處理的代碼
45 Object bean = handlerMethod.getBean();
46 System.out.println(bean.toString());
47
48 Method method = handlerMethod.getMethod();
49 System.out.println(method.toString());
50
51 // 如果回傳false,表示不繼續請求,如果回傳true,表示繼續請求
52 return true;
53 }
54
55 }
2、如果要攔截器生效,則還需要定義一個攔截器的配置類,此時代碼,將攔截器配置到了Web專案中,配置的訪問路徑為全部請求路徑,這樣不管用戶如何訪問都會先執行攔截器中的處理方法,
1 package com.demo.config;
2
3 import org.springframework.context.annotation.Configuration;
4 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
5 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
6
7 /**
8 * Spring 5.0后,WebMvcConfigurerAdapter被廢棄,取代的方法有兩種:
9 * 第一種是,implements WebMvcConfigurer(官方推薦),
10 *
11 * 第二種是,extends WebMvcConfigurationSupport,
12 *
13 * 注意:使用第一種方法是實作了一個介面,可以任意實作里面的方法,不會影響到Spring Boot自身的@EnableAutoConfiguration,
14 * 而使用第二種方法相當于覆寫了@EnableAutoConfiguration里的所有方法,每個方法都需要重寫,
15 * 比如,若不實作方法addResourceHandlers(),則會導致靜態資源無法訪問,
16 *
17 * @author
18 *
19 */
20 @Configuration
21 public class MyWebApplicationConfig implements WebMvcConfigurer {
22
23 /**
24 * alt + /可以提出要實作的方法,
25 * 進行攔截器的注冊處理操作,
26 */
27 @Override
28 public void addInterceptors(InterceptorRegistry registry) {
29 // 匹配路徑
30 registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
31 WebMvcConfigurer.super.addInterceptors(registry);
32 }
33
34 }
演示效果,如下所示:
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/223563.html
標籤:其他
上一篇:最全前端面試總結
下一篇:學習CSS3這一篇就夠了
