<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Spring Boot實(shí)戰(zhàn):攔截器與過濾器詳解與使用!?。?/h1>

          共 5081字,需瀏覽 11分鐘

           ·

          2021-02-19 11:20

          作者:liuxiaopeng

          鏈接:http://www.cnblogs.com/paddix


          一、攔截器與過濾器

          在講Spring boot之前,我們先了解一下過濾器和攔截器。這兩者在功能方面很類似,但是在具體技術(shù)實(shí)現(xiàn)方面,差距還是比較大的。在分析兩者的區(qū)別之前,我們先理解一下AOP的概念,AOP不是一種具體的技術(shù),而是一種編程思想。在面向?qū)ο缶幊痰倪^程中,我們很容易通過繼承、多態(tài)來解決縱向擴(kuò)展。

          但是對(duì)于橫向的功能,比如,在所有的service方法中開啟事務(wù),或者統(tǒng)一記錄日志等功能,面向?qū)ο蟮氖菬o法解決的。所以AOP——面向切面編程其實(shí)是面向?qū)ο缶幊趟枷氲囊粋€(gè)補(bǔ)充。而我們今天講的過濾器和攔截器都屬于面向切面編程的具體實(shí)現(xiàn)。

          而兩者的主要區(qū)別包括以下幾個(gè)方面:

          • Filter是依賴于Servlet容器,屬于Servlet規(guī)范的一部分,而攔截器則是獨(dú)立存在的,可以在任何情況下使用。

          • Filter的執(zhí)行由Servlet容器回調(diào)完成,而攔截器通常通過動(dòng)態(tài)代理的方式來執(zhí)行。

          • Filter的生命周期由Servlet容器管理,而攔截器則可以通過IoC容器來管理,因此可以通過注入等方式來獲取其他Bean的實(shí)例,因此使用會(huì)更方便。

          二、過濾器的配置

          現(xiàn)在我們通過過濾器來實(shí)現(xiàn)記錄請(qǐng)求執(zhí)行時(shí)間的功能,其實(shí)現(xiàn)如下:

          1. publicclassLogCostFilterimplementsFilter{

          2. ? ?@Override

          3. ? ?publicvoid init(FilterConfig filterConfig) throwsServletException{


          4. ? ?}


          5. ? ?@Override

          6. ? ?publicvoid doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throwsIOException, ServletException{

          7. ? ? ? ?long start = System.currentTimeMillis();

          8. ? ? ? ?filterChain.doFilter(servletRequest,servletResponse);

          9. ? ? ? ?System.out.println("Execute cost="+(System.currentTimeMillis()-start));

          10. ? ?}


          11. ? ?@Override

          12. ? ?publicvoid destroy() {


          13. ? ?}

          14. }

          這段代碼的邏輯比較簡單,就是在方法執(zhí)行前先記錄時(shí)間戳,然后通過過濾器鏈完成請(qǐng)求的執(zhí)行,在返回結(jié)果之間計(jì)算執(zhí)行的時(shí)間。這里需要主要,這個(gè)類必須繼承Filter類,這個(gè)是Servlet的規(guī)范,這個(gè)跟以前的Web項(xiàng)目沒區(qū)別。

          但是,有了過濾器類以后,以前的web項(xiàng)目可以在web.xml中進(jìn)行配置,但是spring boot項(xiàng)目并沒有web.xml這個(gè)文件,那怎么配置?在Spring boot中,我們需要FilterRegistrationBean來完成配置。其實(shí)現(xiàn)過程如下:

          1. @Configuration

          2. publicclassFilterConfig{


          3. ? ?@Bean

          4. ? ?publicFilterRegistrationBean registFilter() {

          5. ? ? ? ?FilterRegistrationBean registration = newFilterRegistrationBean();

          6. ? ? ? ?registration.setFilter(newLogCostFilter());

          7. ? ? ? ?registration.addUrlPatterns("/*");

          8. ? ? ? ?registration.setName("LogCostFilter");

          9. ? ? ? ?registration.setOrder(1);

          10. ? ? ? ?return registration;

          11. ? ?}


          12. }

          這樣配置就完成了,需要配置的選項(xiàng)主要包括實(shí)例化Filter類,然后指定url的匹配模式,設(shè)置過濾器名稱和執(zhí)行順序,這個(gè)過程和在web.xml中配置其實(shí)沒什么區(qū)別,只是形式不同而已?,F(xiàn)在我們可以啟動(dòng)服務(wù)器訪問任意URL:

          大家可以看到上面的配置已經(jīng)生效了。除了通過 FilterRegistrationBean 來配置以外,還有一種更直接的辦法,直接通過注解就可以完成了:

          1. @WebFilter(urlPatterns = "/*", filterName = "logFilter2")

          2. publicclassLogCostFilter2implementsFilter{

          3. ? ?@Override

          4. ? ?publicvoid init(FilterConfig filterConfig) throwsServletException{


          5. ? ?}


          6. ? ?@Override

          7. ? ?publicvoid doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throwsIOException, ServletException{

          8. ? ? ? ?long start = System.currentTimeMillis();

          9. ? ? ? ?filterChain.doFilter(servletRequest, servletResponse);

          10. ? ? ? ?System.out.println("LogFilter2 Execute cost="+ (System.currentTimeMillis() - start));

          11. ? ?}


          12. ? ?@Override

          13. ? ?publicvoid destroy() {


          14. ? ?}

          15. }

          這里直接用@WebFilter就可以進(jìn)行配置,同樣,可以設(shè)置url匹配模式,過濾器名稱等。這里需要注意一點(diǎn)的是@WebFilter這個(gè)注解是Servlet3.0的規(guī)范,并不是Spring boot提供的。除了這個(gè)注解以外,我們還需在配置類中加另外一個(gè)注解:@ServletComponetScan,指定掃描的包。

          1. @SpringBootApplication

          2. @MapperScan("com.pandy.blog.dao")

          3. @ServletComponentScan("com.pandy.blog.filters")

          4. publicclassApplication{

          5. ? ?publicstaticvoid main(String[] args) throwsException{

          6. ? ? ? ?SpringApplication.run(Application.class, args);

          7. ? ?}

          8. }

          現(xiàn)在,我們?cè)賮碓L問一下任意URL:

          可以看到,我們配置的兩個(gè)過濾器都生效了。細(xì)心的讀者會(huì)發(fā)現(xiàn),第二個(gè)Filter我們并沒有指定執(zhí)行的順序,但是卻在第一個(gè)Filter之前執(zhí)行。這里需要解釋一下,@WebFilter這個(gè)注解并沒有指定執(zhí)行順序的屬性,其執(zhí)行順序依賴于Filter的名稱,是根據(jù)Filter類名(注意不是配置的filter的名字)的字母順序倒序排列,并且@WebFilter指定的過濾器優(yōu)先級(jí)都高于FilterRegistrationBean配置的過濾器。有興趣的朋友可以自己實(shí)驗(yàn)一下。

          三、攔截器的配置

          上面我們已經(jīng)介紹了過濾器的配置方法,接下來我們?cè)賮砜纯慈绾闻渲靡粋€(gè)攔截器。我們使用攔截器來實(shí)現(xiàn)上面同樣的功能,記錄請(qǐng)求的執(zhí)行時(shí)間。首先我們實(shí)現(xiàn)攔截器類:

          1. publicclassLogCostInterceptorimplementsHandlerInterceptor{

          2. ? ?long start = System.currentTimeMillis();

          3. ? ?@Override

          4. ? ?publicboolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throwsException{

          5. ? ? ? ?start = System.currentTimeMillis();

          6. ? ? ? ?returntrue;

          7. ? ?}


          8. ? ?@Override

          9. ? ?publicvoid postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throwsException{

          10. ? ? ? ?System.out.println("Interceptor cost="+(System.currentTimeMillis()-start));

          11. ? ?}


          12. ? ?@Override

          13. ? ?publicvoid afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throwsException{

          14. ? ?}

          15. }

          這里我們需要實(shí)現(xiàn)HandlerInterceptor這個(gè)接口,這個(gè)接口包括三個(gè)方法,preHandle是請(qǐng)求執(zhí)行前執(zhí)行的,postHandler是請(qǐng)求結(jié)束執(zhí)行的,但只有preHandle方法返回true的時(shí)候才會(huì)執(zhí)行,afterCompletion是視圖渲染完成后才執(zhí)行,同樣需要preHandle返回true,該方法通常用于清理資源等工作。除了實(shí)現(xiàn)上面的接口外,我們還需對(duì)其進(jìn)行配置:

          1. @Configuration

          2. publicclassInterceptorConfigextendsWebMvcConfigurerAdapter{


          3. ? ?@Override

          4. ? ?publicvoid addInterceptors(InterceptorRegistry registry) {

          5. ? ? ? ?registry.addInterceptor(newLogCostInterceptor()).addPathPatterns("/**");

          6. ? ? ? ?super.addInterceptors(registry);

          7. ? ?}

          8. }

          這里我們繼承了WebMVCConfigurerAdapter,看過前面的文章的朋友應(yīng)該已經(jīng)見過這個(gè)類了,在進(jìn)行靜態(tài)資源目錄配置的時(shí)候我們用到過這個(gè)類。這里我們重寫了addInterceptors這個(gè)方法,進(jìn)行攔截器的配置,主要配置項(xiàng)就兩個(gè),一個(gè)是指定攔截器,第二個(gè)是指定攔截的URL?,F(xiàn)在我們?cè)賳?dòng)系統(tǒng)訪問任意一個(gè)URL:

          可以看到,我們通過攔截器實(shí)現(xiàn)了同樣的功能。不過這里還要說明一點(diǎn)的是,其實(shí)這個(gè)實(shí)現(xiàn)是有問題的,因?yàn)閜reHandle和postHandle是兩個(gè)方法,所以我們這里不得不設(shè)置一個(gè)共享變量start來存儲(chǔ)開始值,但是這樣就會(huì)存在線程安全問題。當(dāng)然,我們可以通過其他方法來解決,比如通過ThreadLocal就可以很好的解決這個(gè)問題,有興趣的同學(xué)可以自己實(shí)現(xiàn)。不過通過這一點(diǎn)我們其實(shí)可以看到,雖然攔截器在很多場景下優(yōu)于過濾器,但是在這種場景下,過濾器比攔截器實(shí)現(xiàn)起來更簡單。

          四、總結(jié)

          本文主要對(duì)基于Spring boot對(duì)過濾器和攔截器的配置進(jìn)行的講解。無論是過濾器還是攔截器都屬于AOP(面向切面編程)思想的具體實(shí)現(xiàn)。除了這兩種實(shí)現(xiàn)我們還見過另一種更靈活的AOP實(shí)現(xiàn)技術(shù),即Aspect,我們可以通過Aspect來完成更多更強(qiáng)大的功能。這個(gè)后續(xù)再給大家分享。

          點(diǎn)擊關(guān)注公眾號(hào)↑↑

          瀏覽 44
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)

          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  国产亲子伦A片免费看 | 日韩大香蕉 | 美女做受 | 偷拍久久久久 | 欧美在线免费观看 |