Spring Boot 中,過濾器和攔截器的區別是什麼?

過濾器和攔截器有相似之處,都能對 Servlet 請求二次加工。但是過濾器並不是 SpringBoot 規範中的概念,事實上,過濾器是 Servlet 規範中的事物。

因此過濾器和攔截器的最大區別就是他們存在的空間是不一樣的。

Filter 攔截器是 Servlet 中的規範,它可不依賴於 Spring,它是由 Servlet 容器 Filter 每個請求和響應。它可以在請求到達 Servlet 之前就處,因此 Filter 也總是優先於 Interceptor 執行。

Interceptor 過濾器是工作在 Spring 容器中的,由 Spring 所控制,因此能和 Spring 緊密的結合,在 Spring 中使用攔截器,處理攔截行爲更方便,事實上 Filter 能做的事情,Interceptor 也都能實現。

選用 Filter 還是 Interceptor, 官方有話

As a basic guideline, fine-grained handler-related preprocessing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.

對於 handler 相關的,尤其是抽取出的公共 handler 模塊,可以使用 Interceptor,過濾器更適合內容控制,比如 Gzip 壓縮等。

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