javascript
Spring boot注册三大组件
注冊(cè)三大組件
Spring boot
以jar包的方式
使用嵌入式的Tomcat啟動(dòng)Web應(yīng)用
沒有Web應(yīng)用目錄結(jié)構(gòu),沒有web.xml文件
Web應(yīng)用
是一個(gè)Web應(yīng)用的目錄結(jié)構(gòu)
存在目錄文件src/main/webapp/WEB-INF/web.xml
可以把三大組件,注冊(cè)在web.xml中
Spring boot
提供了三大組件,注冊(cè)方式
注冊(cè)Servlet,使用ServletRegistrationBean
注冊(cè)Filter,使用FilterRegistrationBean
注冊(cè)ServletListener,使用ServletListenerRegistrationBean
Servlet
自定義Servlet,繼承HttpServlet
重寫方法,處理請(qǐng)求
Filter
自定義Filter,實(shí)現(xiàn)Filter接口
實(shí)現(xiàn)Filter的三個(gè)方法
Init,初始化
doFilter,過濾
destroy,銷毀
chain.doFilter,放行請(qǐng)求
Listener
自定義Listener,實(shí)現(xiàn)ServletContextListener
Listener有很多,這里監(jiān)聽啟動(dòng)和銷毀的Listener
contextInitialized,初始化方法,Web項(xiàng)目啟動(dòng)
contextDestroyed,銷毀方法,Web項(xiàng)目銷毀
注冊(cè)Servlet
返回一個(gè)ServletRegistrationBean
是一個(gè)class,直接new一個(gè)
使用有參構(gòu)造器,傳遞自定義的Servlet,映射路徑
注冊(cè)Filter
返回一個(gè)FilterRegistrationBean
是一個(gè)class,直接new一個(gè)
設(shè)置自定義的Filter,設(shè)置攔截請(qǐng)求的url
是一個(gè)集合,使用Arrays轉(zhuǎn)換
注冊(cè)Listener
返回一個(gè)ServletListenerRegistrationBean
是一個(gè)類,直接new一個(gè)
傳遞自定義的Listener
可以注冊(cè)的Listener類型
注冊(cè)方式
@Configuration public class MyServerConfig {//注冊(cè)三大組件@Beanpublic ServletRegistrationBean myServlet(){ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");registrationBean.setLoadOnStartup(1);return registrationBean;}@Beanpublic FilterRegistrationBean myFilter(){FilterRegistrationBean registrationBean = new FilterRegistrationBean();registrationBean.setFilter(new MyFilter());registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));return registrationBean;}@Beanpublic ServletListenerRegistrationBean myListener(){ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());return registrationBean;}}屬性設(shè)置
可以直接在registrationBean中設(shè)置
自定義組件的屬性
總結(jié)
以上是生活随笔為你收集整理的Spring boot注册三大组件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring boot自动注册Dispa
- 下一篇: gradle idea java ssm