SpringBoot入門學習(十五)~~註冊Servlet元件
目錄
SpringBoot中註冊Servlet元件
在專案中,我們經常會使用到過濾器Filter、監聽器Listener,Filter和Listener都屬於Servlet元件之一。在SpringBoot中,我們依舊是要寫Servlet元件。這裡介紹SpringBoot的Servlet元件如何編寫。
這裡介紹兩種方式,一種是Spring3.0以上版本,使用註解非常方便。如果是Spring3.0以下沒有註解配置的話,那麼使用SpringBoot提供的方式。
-
第一種方式:Servlet註解的方式~~Spring3.x+
Servlet
1、編寫簡單的Servlet,使用@WebServlet
|
2、編寫核心配置類,在型別配置類中開啟Servlet掃描
@ServletComponentScan
|
3、啟動專案,嘗試訪問即可:
表示ok。
Filter
相同的原理,使用@WebFilter(urlPatterns = "/*")
@WebFilter(urlPatterns = "/*") |
Listener
使用@WebListener
|
-
第二種方式:SpringBoot方式
Servlet
在SpringBoot的Application中,注入一個ServletRegistrationBean,由該Bean幫我們管理
|
Filter
在SpringBoot的Application中,注入一個FilterRegistrationBean
,由該Bean幫我們管理
|
Listener
在SpringBoot的Application中,注入一個ServletListenerRegistrationBean,由該Bean幫我們管理
|
- 個人建議:
如果說是,Spring3.X以上的版本,建議採用註解的方式註冊Servlet,這樣比較簡單。如果是Spring2.x版本的話,那就用SpringBoot的方式去註冊Servlet。當然你會在老的專案中看到第二種寫法。