過濾器(Filter)、攔截器(Interceptor)、監聽器(Listener)

 1、Filter 過濾器html

一、簡介java

  Filter也稱之爲過濾器,它是Servlet技術中最實用的技術,WEB開發人員經過Filter技術,對web服務器管理的全部web資源:例如Jsp, Servlet, 靜態圖片文件或靜態 html 文件等進行攔截,從而實現一些特殊的功能。例如實現URL級別的權限訪問控制、過濾敏感詞彙、壓縮響應信息等一些高級功能。web

  它主要用於對用戶請求進行預處理,也能夠對HttpServletResponse 進行後處理。使用Filter 的完整流程:Filter 對用戶請求進行預處理,接着將請求交給Servlet 進行處理並生成響應,最後Filter 再對服務器響應進行後處理。spring

  Filter功能:apache

  • 在HttpServletRequest 到達 Servlet 以前,攔截客戶的 HttpServletRequest 。 根據須要檢查 HttpServletRequest ,也能夠修改HttpServletRequest 頭和數據。
  • 在HttpServletResponse 到達客戶端以前,攔截HttpServletResponse 。 根據須要檢查 HttpServletResponse ,也能夠修改HttpServletResponse頭和數據。

二、如何實現攔截緩存

  Filter接口中有一個doFilter方法,當開發人員編寫好Filter,並配置對哪一個web資源進行攔截後,WEB服務器每次在調用web資源的service方法以前,都會先調用一下filter的doFilter方法,所以,在該方法內編寫代碼可達到以下目的:tomcat

  1. 調用目標資源以前,讓一段代碼執行。
  2. 是否調用目標資源(便是否讓用戶訪問web資源)。

  web服務器在調用doFilter方法時,會傳遞一個filterChain對象進來,filterChain對象是filter接口中最重要的一個對象,它也提供了一個doFilter方法,開發人員能夠根據需求決定是否調用此方法,調用該方法,則web服務器就會調用web資源的service方法,即web資源就會被訪問,不然web資源不會被訪問。 安全

三、Filter開發兩步走服務器

  1. 編寫java類實現Filter接口,並實現其doFilter方法。 
  2. 在 web.xml 文件中使用<filter>和<filter-mapping>元素對編寫的filter類進行註冊,並設置它所能攔截的資源。

  web.xml配置各節點介紹:session

<filter-name>用於爲過濾器指定一個名字,該元素的內容不能爲空。 

<filter-class>元素用於指定過濾器的完整的限定類名。 

<init-param>元素用於爲過濾器指定初始化參數,它的子元素<param-name>指定參數的名字,<param-value>指定參數的值。

在過濾器中,可使用FilterConfig接口對象來訪問初始化參數。

 

<filter-mapping>元素用於設置一個 Filter 所負責攔截的資源。一個Filter攔截的資源可經過兩種方式來指定:Servlet 名稱和資源訪問的請求路徑 

<filter-name>子元素用於設置filter的註冊名稱。該值必須是在<filter>元素中聲明過的過濾器的名字 

<url-pattern>設置 filter 所攔截的請求路徑(過濾器關聯的URL樣式) 

<servlet-name>指定過濾器所攔截的Servlet名稱。 

<dispatcher>指定過濾器所攔截的資源被 Servlet 容器調用的方式,能夠是REQUEST,INCLUDE,FORWARD和ERROR之一,默認REQUEST。用戶能夠設置多個<dispatcher> 子元素用來指定 Filter 對資源的多種調用方式進行攔截。 

 

<dispatcher> 子元素能夠設置的值及其意義: 

REQUEST:當用戶直接訪問頁面時,Web容器將會調用過濾器。若是目標資源是經過RequestDispatcher的include()或forward()方法訪問時,那麼該過濾器就不會被調用。 

INCLUDE:若是目標資源是經過RequestDispatcher的include()方法訪問時,那麼該過濾器將被調用。除此以外,該過濾器不會被調用。 

FORWARD:若是目標資源是經過RequestDispatcher的forward()方法訪問時,那麼該過濾器將被調用,除此以外,該過濾器不會被調用。 

ERROR:若是目標資源是經過聲明式異常處理機制調用時,那麼該過濾器將被調用。除此以外,過濾器不會被調用。

四、Filter鏈

  在一個web應用中,能夠開發編寫多個Filter,這些Filter組合起來稱之爲一個Filter鏈。

  web服務器根據Filter在web.xml文件中的註冊順序,決定先調用哪一個Filter,當第一個Filter的doFilter方法被調用時,web服務器會建立一個表明Filter鏈的FilterChain對象傳遞給該方法。在doFilter方法中,開發人員若是調用了FilterChain對象的doFilter方法,則web服務器會檢查FilterChain對象中是否還有filter,若是有,則調用第2個filter,若是沒有,則調用目標資源。

五、Filter的生命週期

public void init(FilterConfig filterConfig) throws ServletException;//初始化

  和咱們編寫的Servlet程序同樣,Filter的建立和銷燬由WEB服務器負責。 web 應用程序啓動時,web 服務器將建立Filter 的實例對象,並調用其init方法,讀取web.xml配置,完成對象的初始化功能,從而爲後續的用戶請求做好攔截的準備工做(filter對象只會建立一次,init方法也只會執行一次)。開發人員經過init方法的參數,可得到表明當前filter配置信息的FilterConfig對象。

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;//攔截請求

  這個方法完成實際的過濾操做。當客戶請求訪問與過濾器關聯的URL的時候,Servlet過濾器將先執行doFilter方法。FilterChain參數用於訪問後續過濾器。

public void destroy();//銷燬

  Filter對象建立後會駐留在內存,當web應用移除或服務器中止時才銷燬。在Web容器卸載 Filter 對象以前被調用。該方法在Filter的生命週期中僅執行一次。在這個方法中,能夠釋放過濾器使用的資源。

六、FilterConfig接口

  用戶在配置filter時,可使用<init-param>爲filter配置一些初始化參數,當web容器實例化Filter對象,調用其init方法時,會把封裝了filter初始化參數的filterConfig對象傳遞進來。所以開發人員在編寫filter時,經過filterConfig對象的方法,就可得到如下內容:

String getFilterName();//獲得filter的名稱。 

String getInitParameter(String name);//返回在部署描述中指定名稱的初始化參數的值。若是不存在返回null. 

Enumeration getInitParameterNames();//返回過濾器的全部初始化參數的名字的枚舉集合。 

public ServletContext getServletContext();//返回Servlet上下文對象的引用。

七、Filter使用案例

  一、使用Filter驗證用戶登陸安全控制

  前段時間參與維護一個項目,用戶退出系統後,再去地址欄訪問歷史,根據url,仍然可以進入系統響應頁面。我去檢查一下發現對請求未進行過濾驗證用戶登陸。添加一個filter搞定問題!

  先在web.xml配置

<filter>

    <filter-name>SessionFilter</filter-name>

    <filter-class>com.action.login.SessionFilter</filter-class>

    <init-param>

        <param-name>logonStrings</param-name><!-- 對登陸頁面不進行過濾 -->

        <param-value>/project/index.jsp;login.do</param-value>

    </init-param>

    <init-param>

        <param-name>includeStrings</param-name><!-- 只對指定過濾參數後綴進行過濾 -->

        <param-value>.do;.jsp</param-value>

    </init-param>

    <init-param>

        <param-name>redirectPath</param-name><!-- 未經過跳轉到登陸界面 -->

        <param-value>/index.jsp</param-value>

    </init-param>

    <init-param>

        <param-name>disabletestfilter</param-name><!-- Y:過濾無效 -->

        <param-value>N</param-value>

    </init-param>

</filter>

<filter-mapping>

    <filter-name>SessionFilter</filter-name>

    <url-pattern>/*</url-pattern>

</filter-mapping>

  接着編寫FilterServlet:

package com.action.login;

 

import java.io.IOException;

 

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpServletResponseWrapper;

 

/**

 *    判斷用戶是否登陸,未登陸則退出系統

 */

public class SessionFilter implements Filter {

    

    public FilterConfig config;

    

    public void destroy() {

        this.config = null;

    }

    

    public static boolean isContains(String container, String[] regx) {

        boolean result = false;

 

        for (int i = 0; i < regx.length; i++) {

            if (container.indexOf(regx[i]) != -1) {

                return true;

            }

        }

        return result;

    }

 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest hrequest = (HttpServletRequest)request;

        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response);

        

        String logonStrings = config.getInitParameter("logonStrings");        // 登陸登錄頁面

        String includeStrings = config.getInitParameter("includeStrings");    // 過濾資源後綴參數

        String redirectPath = hrequest.getContextPath() + config.getInitParameter("redirectPath");// 沒有登錄轉向頁面

        String disabletestfilter = config.getInitParameter("disabletestfilter");// 過濾器是否有效

        

        if (disabletestfilter.toUpperCase().equals("Y")) {    // 過濾無效

            chain.doFilter(request, response);

            return;

        }

        String[] logonList = logonStrings.split(";");

        String[] includeList = includeStrings.split(";");

        

        if (!this.isContains(hrequest.getRequestURI(), includeList)) {// 只對指定過濾參數後綴進行過濾

            chain.doFilter(request, response);

            return;

        }

        

        if (this.isContains(hrequest.getRequestURI(), logonList)) {// 對登陸頁面不進行過濾

            chain.doFilter(request, response);

            return;

        }

        

        String user = ( String ) hrequest.getSession().getAttribute("useronly");//判斷用戶是否登陸

        if (user == null) {

            wrapper.sendRedirect(redirectPath);

            return;

        }else {

            chain.doFilter(request, response);

            return;

        }

    }

 

    public void init(FilterConfig filterConfig) throws ServletException {

        config = filterConfig;

    }

}

  這樣既可完成對用戶全部請求,均要通過這個Filter進行驗證用戶登陸。

  二、防止中文亂碼過濾器

  項目使用spring框架時。當前臺JSP頁面和JAVA代碼中使用了不一樣的字符集進行編碼的時候就會出現表單提交的數據或者上傳/下載中文名稱文件出現亂碼的問題,那就可使用這個過濾器。

<filter>

    <filter-name>encoding</filter-name>

    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

    <init-param>

        <param-name>encoding</param-name><!--用來指定一個具體的字符集-->

        <param-value>UTF-8</param-value>

    </init-param>

    <init-param>

        <param-name>forceEncoding</param-name><!--true:不管request是否指定了字符集,都是用encoding;false:若是request已指定一個字符集,則不使用encoding-->

        <param-value>false</param-value>

    </init-param>

</filter>

<filter-mapping>

    <filter-name>encoding</filter-name>

    <url-pattern>/*</url-pattern>

</filter-mapping>

  三、Spring+Hibernate的OpenSessionInViewFilter控制session的開關

  當hibernate+spring配合使用的時候,若是設置了lazy=true(延遲加載),那麼在讀取數據的時候,當讀取了父數據後,hibernate 會自動關閉session,這樣,當要使用與之關聯數據、子數據的時候,系統會拋出lazyinit的錯誤,這時就須要使用spring提供的OpenSessionInViewFilter過濾器。

  OpenSessionInViewFilter主要是保持Session狀態直到request將所有頁面發送到客戶端,直到請求結束後才關閉session,這樣就能夠解決延遲加載帶來的問題。

  注意:OpenSessionInViewFilter配置要寫在struts2的配置前面。由於tomcat容器在加載過濾器的時候是按照順序加載的,若是配置文件先寫的是struts2的過濾器配置,而後纔是OpenSessionInViewFilter過濾器配置,因此加載的順序致使,action在得到數據的時候session並無被spring管理。

<!-- lazy loading enabled in spring -->

<filter>

    <filter-name>OpenSessionInViewFilter</filter-name>

    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>

    <init-param>

        <param-name>sessionFactoryBeanName</param-name><!-- 可缺省。默認是從spring容器中找id爲sessionFactory的bean,若是id不爲sessionFactory,則須要配置以下,此處SessionFactory爲spring容器中的bean。 -->

        <param-value>sessionFactory</param-value>

    </init-param>

    <init-param>

        <param-name>singleSession</param-name><!-- singleSession默認爲true,若設爲false則等於沒用OpenSessionInView -->

        <param-value>true</param-value>

    </init-param>

</filter>

<filter-mapping>

    <filter-name>OpenSessionInViewFilter</filter-name>

    <url-pattern>*.do</url-pattern>

</filter-mapping>

  四、Struts2的web.xml配置

  項目中使用Struts2一樣須要在web.xml配置過濾器,用來截取請求,轉到Struts2的Action進行處理。

  注意:若是在2.1.3之前的Struts2版本,過濾器使用org.apache.struts2.dispatcher.FilterDispatcher。不然使用org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter。從Struts2.1.3開始,將廢棄ActionContextCleanUp過濾器,而在StrutsPrepareAndExecuteFilter過濾器中包含相應的功能。

  三個初始化參數配置:

  1. config參數:指定要加載的配置文件。逗號分割。
  2. actionPackages參數:指定Action類所在的包空間。逗號分割。
  3. configProviders參數:自定義配置文件提供者,須要實現ConfigurationProvider接口類。逗號分割。

<!-- struts 2.x filter -->

<filter>

    <filter-name>struts2</filter-name>

    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

</filter>

<filter-mapping>

    <filter-name>struts2</filter-name>

    <url-pattern>*.do</url-pattern>

</filter-mapping>

2、Interceptor 攔截器

待更新

 

3、Listener 監聽器

一、Listener的定義與做用

  監聽器Listener就是在application,session,request三個對象建立、銷燬或者往其中添加修改刪除屬性時自動執行代碼的功能組件。

  Listener是Servlet的監聽器,能夠監聽客戶端的請求,服務端的操做等。

二、Listener的分類與使用

  主要有如下三類:

  一、ServletContext監聽

  ServletContextListener:用於對Servlet整個上下文進行監聽(建立、銷燬)。

public void contextInitialized(ServletContextEvent sce);//上下文初始化

public void contextDestroyed(ServletContextEvent sce);//上下文銷燬

 

public ServletContext getServletContext();//ServletContextEvent事件:取得一個ServletContext(application)對象

  ServletContextAttributeListener:對Servlet上下文屬性的監聽(增刪改屬性)。

public void attributeAdded(ServletContextAttributeEvent scab);//增長屬性

public void attributeRemoved(ServletContextAttributeEvent scab);//屬性刪除

public void attributeRepalced(ServletContextAttributeEvent scab);//屬性替換(第二次設置同一屬性)

 

//ServletContextAttributeEvent事件:能取得設置屬性的名稱與內容

public String getName();//獲得屬性名稱

public Object getValue();//取得屬性的值

  二、Session監聽

  Session屬於http協議下的內容,接口位於javax.servlet.http.*包下。

  HttpSessionListener接口:對Session的總體狀態的監聽。

public void sessionCreated(HttpSessionEvent se);//session建立

public void sessionDestroyed(HttpSessionEvent se);//session銷燬

 

//HttpSessionEvent事件:

public HttpSession getSession();//取得當前操做的session

  HttpSessionAttributeListener接口:對session的屬性監聽。

public void attributeAdded(HttpSessionBindingEvent se);//增長屬性

public void attributeRemoved(HttpSessionBindingEvent se);//刪除屬性

public void attributeReplaced(HttpSessionBindingEvent se);//替換屬性

 

//HttpSessionBindingEvent事件:

public String getName();//取得屬性的名稱

public Object getValue();//取得屬性的值

public HttpSession getSession();//取得當前的session

  session的銷燬有兩種狀況:

  一、session超時,web.xml配置:

<session-config>

    <session-timeout>120</session-timeout><!--session120分鐘後超時銷燬-->

</session-config>

  二、手工使session失效

public void invalidate();//使session失效方法。session.invalidate();

  三、Request監聽

  ServletRequestListener:用於對Request請求進行監聽(建立、銷燬)。

public void requestInitialized(ServletRequestEvent sre);//request初始化

public void requestDestroyed(ServletRequestEvent sre);//request銷燬

 

//ServletRequestEvent事件:

public ServletRequest getServletRequest();//取得一個ServletRequest對象

public ServletContext getServletContext();//取得一個ServletContext(application)對象

  ServletRequestAttributeListener:對Request屬性的監聽(增刪改屬性)。

public void attributeAdded(ServletRequestAttributeEvent srae);//增長屬性

public void attributeRemoved(ServletRequestAttributeEvent srae);//屬性刪除

public void attributeReplaced(ServletRequestAttributeEvent srae);//屬性替換(第二次設置同一屬性)

 

//ServletRequestAttributeEvent事件:能取得設置屬性的名稱與內容

public String getName();//獲得屬性名稱

public Object getValue();//取得屬性的值

  四、在web.xml中配置

  Listener配置信息必須在Filter和Servlet配置以前,Listener的初始化(ServletContentListener初始化)比Servlet和Filter都優先,而銷燬比Servlet和Filter都慢。

<listener>

    <listener-class>com.listener.class</listener-class>

</listener>

三、Listener應用實例

  一、利用HttpSessionListener統計最多在線用戶人數

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.Date;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;

 

public class HttpSessionListenerImpl implements HttpSessionListener {

 

    public void sessionCreated(HttpSessionEvent event) {

        ServletContext app = event.getSession().getServletContext();

        int count = Integer.parseInt(app.getAttribute("onLineCount").toString());

        count++;

        app.setAttribute("onLineCount", count);

        int maxOnLineCount = Integer.parseInt(app.getAttribute("maxOnLineCount").toString());

        if (count > maxOnLineCount) {

            //記錄最多人數是多少

            app.setAttribute("maxOnLineCount", count);

            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            //記錄在那個時刻達到上限

            app.setAttribute("date", df.format(new Date()));

        }

    }

    //session註銷、超時時候調用,中止tomcat不會調用

    public void sessionDestroyed(HttpSessionEvent event) {

        ServletContext app = event.getSession().getServletContext();

        int count = Integer.parseInt(app.getAttribute("onLineCount").toString());

        count--;

        app.setAttribute("onLineCount", count);    

        

    }

}

  二、Spring使用ContextLoaderListener加載ApplicationContext配置信息

  ContextLoaderListener的做用就是啓動Web容器時,自動裝配ApplicationContext的配置信息。由於它實現了ServletContextListener這個接口,在web.xml配置這個監聽器,啓動容器時,就會默認執行它實現的方法。

  ContextLoaderListener如何查找ApplicationContext.xml的配置位置以及配置多個xml:若是在web.xml中不寫任何參數配置信息,默認的路徑是"/WEB-INF/applicationContext.xml",在WEB-INF目錄下建立的xml文件的名稱必須是applicationContext.xml(在MyEclipse中把xml文件放置在src目錄下)。若是是要自定義文件名能夠在web.xml里加入contextConfigLocation這個context參數。

<context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>classpath:spring/applicationContext-*.xml</param-value><!-- 採用的是通配符方式,查找WEB-INF/spring目錄下xml文件。若有多個xml文件,以「,」分隔。 -->

</context-param>

 

<listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

  三、Spring使用Log4jConfigListener配置Log4j日誌

  Spring使用Log4jConfigListener的好處:

  1. 動態的改變記錄級別和策略,不須要重啓Web應用。
  2. 把log文件定在 /WEB-INF/logs/ 而不須要寫絕對路徑。由於系統把web目錄的路徑壓入一個叫webapp.root的系統變量。這樣寫log文件路徑時不用寫絕對路徑了。
  3. 能夠把log4j.properties和其餘properties一塊兒放在/WEB-INF/ ,而不是Class-Path。
  4. 設置log4jRefreshInterval時間,開一條watchdog線程每隔段時間掃描一下配置文件的變化。

<context-param>

    <param-name>webAppRootKey</param-name>

    <param-value>project.root</param-value><!-- 用於定位log文件輸出位置在web應用根目錄下,log4j配置文件中寫輸出位置:log4j.appender.FILE.File=${project.root}/logs/project.log -->

</context-param>

<context-param>

    <param-name>log4jConfigLocation</param-name>

    <param-value>classpath:log4j.properties</param-value><!-- 載入log4j配置文件 -->

</context-param>

<context-param>

    <param-name>log4jRefreshInterval</param-name>

    <param-value>60000</param-value><!--Spring刷新Log4j配置文件的間隔60秒,單位爲millisecond-->

</context-param>

 

<listener>

    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>

</listener>

  四、Spring使用IntrospectorCleanupListener清理緩存

  這個監聽器的做用是在web應用關閉時刷新JDK的JavaBeans的Introspector緩存,以確保Web應用程序的類加載器以及其加載的類正確的釋放資源。

  若是JavaBeans的Introspector已被用來分析應用程序類,系統級的Introspector緩存將持有這些類的一個硬引用。所以,這些類和Web應用程序的類加載器在Web應用程序關閉時將不會被垃圾收集器回收!而IntrospectorCleanupListener則會對其進行適當的清理,已使其可以被垃圾收集器回收。

  惟一可以清理Introspector的方法是刷新整個Introspector緩存,沒有其餘辦法來確切指定應用程序所引用的類。這將刪除全部其餘應用程序在服務器的緩存的Introspector結果。

  在使用Spring內部的bean機制時,不須要使用此監聽器,由於Spring本身的introspection results cache將會當即刷新被分析過的JavaBeans Introspector cache,而僅僅會在應用程序本身的ClassLoader裏面持有一個cache。雖然Spring自己不產生泄漏,注意,即便在Spring框架的類自己駐留在一個「共同」類加載器(如系統的ClassLoader)的狀況下,也仍然應該使用使用IntrospectorCleanupListener。在這種狀況下,這個IntrospectorCleanupListener將會妥善清理Spring的introspection cache。

  應用程序類,幾乎不須要直接使用JavaBeans Introspector,因此,一般都不是Introspector resource形成內存泄露。相反,許多庫和框架,不清理Introspector,例如: Struts和Quartz。

  須要注意的是一個簡單Introspector泄漏將會致使整個Web應用程序的類加載器不會被回收!這樣作的結果,將會是在web應用程序關閉時,該應用程序全部的靜態類資源(好比:單實例對象)都沒有獲得釋放。而致使內存泄露的根本緣由其實並非這些未被回收的類!

  注意:IntrospectorCleanupListener應該註冊爲web.xml中的第一個Listener,在任何其餘Listener以前註冊,好比在Spring's ContextLoaderListener註冊以前,才能確保IntrospectorCleanupListener在Web應用的生命週期適當時機生效。

<!-- memory clean -->

<listener>

    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>

</listener>

相關文章
相關標籤/搜索