SpringBoot2.x 中配置攔截器

攔截器介紹

攔截器的作用:通過攔截執行中通用的代碼邏輯,來減少控制器中的代碼冗餘

攔截器的特點:

  • 只能攔截控制器的相關請求,不能攔截靜態資源和頁面的相關請求(css、img)
  • 請求發送經過攔截器響應回來同樣經過攔截器
  • 攔截器中斷用戶的請求
  • 攔截器可以針對性攔截某些控制器請求

攔截器開發

開發一個自己的攔截器類,要求實現 HandlerInterceptor

  • preHandlercontroller 執行之前,進行攔截,通過返回值判斷是否放行。
    返回值 true 表示放行,然後去執行 controller 中的代碼。
    返回值 false 表示攔截,不再繼續執行後續代碼。
  • postHandler 請求過程中處理 controller 執行之後的操作。
  • afterCompletion 最終處理。

開發攔截器 MyInterceptor

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("---------1----------");
        return true; // true代表放行, false表示攔截住
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("---------3----------");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("---------4----------");
    }
}

開發控制器 HelloController

@RestController
@RequestMapping("/hello")
public class HelloController {
    @RequestMapping("/hello")
    public String hello() {
        System.out.println("---------2----------");
        return "hello";
    }
    @RequestMapping("world")
    public String world() {
        System.out.println("-------world--------");
        return "world";
    }
}

配置攔截器 InterceptorConfig

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()) // 添加攔截器
                .addPathPatterns("/hello/**") // 添加l攔截的請求路徑
        .excludePathPatterns("/hello/world"); // 添加排除哪些請求路徑不經過攔截器
    }
}

運行

首先在 preHandle 中進行攔截,上述代碼爲 true 表示放行,則開始執行 HelloController 中的代碼,執行完控制器之後再去執行 postHandle 中的代碼,整個過程結束以後再執行 afterCompletion 中的代碼。

---------1----------
---------2----------
---------3----------
---------4----------
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章