SpringBoot 2 快速整合 Filter過(guò)程解析
概述
SpringBoot 中沒(méi)有 web.xml, 我們無(wú)法按照原來(lái)的方式在 web.xml 中配置 Filter 。但是我們可以通過(guò) JavaConfig(@Configuration +@Bean)方式進(jìn)行配置。通過(guò)FilterRegistrationBean 將自定義 Filter 添加到 SpringBoot 的過(guò)濾鏈中。
實(shí)戰(zhàn)操作
實(shí)戰(zhàn)操作通過(guò)定義一個(gè)攔截所有訪問(wèn)項(xiàng)目的URL的 Filter來(lái)進(jìn)行演示的。
首先定義一個(gè)統(tǒng)一訪問(wèn) URL 攔截的 Filter。代碼如下:
public class UrlFilter implements Filter {
private Logger log = LoggerFactory.getLogger(UrlFilter.class);
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String requestURI = httpServletRequest.getRequestURI();
StringBuffer requestURL = httpServletRequest.getRequestURL();
log.info("requestURI:" +requestURI+" "+"requestURL:"+requestURL);
chain.doFilter(httpServletRequest, response);
}
}
通過(guò) javaConfig方式配置 SpringBoot 過(guò)濾鏈類(lèi) FilterRegistrationBean,具體代碼如下:
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean filterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new UrlFilter());
List<String> urlList = new ArrayList<String>();
urlList.add("/*");
registration.setUrlPatterns(urlList);
registration.setName("UrlFilter");
registration.setOrder(1);
return registration;
}
}
FilterRegistrationBean 中方法介紹:
- registration.setFilter(Filter filter):設(shè)置我們自定義Filter對(duì)象。
- registration.setUrlPatterns(Collection urlPatterns):設(shè)置自定義Filter需要攔截的URL的集合。
- registration.setName(String name): 設(shè)置自定義Filter名稱(chēng)。
- registration.setOrder(int order):設(shè)置自定義Filter攔截順序。
測(cè)試
啟動(dòng) SpirngBoot 項(xiàng)目并通過(guò)游覽器訪問(wèn)我們的項(xiàng)目下的 index.html。


以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java并發(fā)系列之JUC中的Lock鎖與synchronized同步代碼塊問(wèn)題
這篇文章主要介紹了Java并發(fā)系列之JUC中的Lock鎖與synchronized同步代碼塊,簡(jiǎn)單介紹了lock鎖及鎖的底層知識(shí),結(jié)合案例給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04
詳解WebSocket+spring示例demo(已使用sockJs庫(kù))
本篇文章主要介紹了WebSocket spring示例demo(已使用sockJs庫(kù)),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01
springboot 用監(jiān)聽(tīng)器統(tǒng)計(jì)在線人數(shù)案例分析
這篇文章主要介紹了springboot 用監(jiān)聽(tīng)器統(tǒng)計(jì)在線人數(shù)案例分析,質(zhì)是統(tǒng)計(jì)session 的數(shù)量,思路很簡(jiǎn)單,具體實(shí)例代碼大家參考下本文2018-02-02
JAXB命名空間及前綴_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要給大家介紹了關(guān)于JAXB命名空間及前綴的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-08-08

