Java Filter過濾器

百聯達發表於2016-12-05
一:過濾器簡介

Filter也稱之為過濾器,它是Servlet技術中最實用的技術,Web開發人員通過Filter技術,對web伺服器管理的所有web資源:例如Jsp, Servlet, 靜態圖片檔案或靜態 html 檔案等進行攔截,從而實現一些特殊的功能。例如實現URL級別的許可權訪問控制、過濾敏感詞彙、壓縮響應資訊等一些高階功能。
它主要用於對使用者請求進行預處理,也可以對HttpServletResponse進行後處理。使用Filter的完整流程:Filter對使用者請求進行預處理,接著將請求交給Servlet進行處理並生成響應,最後Filter再對伺服器響應進行後處理。


二:過濾器功能

在HttpServletRequest到達 Servlet 之前,攔截客戶的HttpServletRequest 。根據需要檢查HttpServletRequest,也可以修改HttpServletRequest 頭和資料。
在HttpServletResponse到達客戶端之前,攔截HttpServletResponse 。根據需要檢查HttpServletResponse,也可以修改HttpServletResponse頭和資料。



三:過濾器開發


點選(此處)摺疊或開啟

  1. public interface Filter {

  2.     /**
  3.     * Called by the web container to indicate to a filter that it is being placed into
  4.     * service. The servlet container calls the init method exactly once after instantiating the
  5.     * filter. The init method must complete successfully before the filter is asked to do any
  6.     * filtering work. <br><br>

  7.          * The web container cannot place the filter into service if the init method either<br>
  8.         * 1.Throws a ServletException <br>
  9.         * 2.Does not return within a time period defined by the web container
  10.     */
  11.     public void init(FilterConfig filterConfig) throws ServletException;
  12.     
  13.     
  14.     /**
  15.     * The <code>doFilter</code> method of the Filter is called by the container
  16.     * each time a request/response pair is passed through the chain due
  17.     * to a client request for a resource at the end of the chain. The FilterChain passed in to this
  18.     * method allows the Filter to pass on the request and response to the next entity in the
  19.     * chain.


  20.     * A typical implementation of this method would follow the following pattern:- <br>
  21.     * 1. Examine the request<br>
  22.     * 2. Optionally wrap the request object with a custom implementation to
  23.     * filter content or headers for input filtering <br>
  24.     * 3. Optionally wrap the response object with a custom implementation to
  25.     * filter content or headers for output filtering <br>
  26.     * 4. a) Either invoke the next entity in the chain using the FilterChain object (<code>chain.doFilter()</code>), <br>
  27.     ** 4. b) or not pass on the request/response pair to the next entity in the filter chain to block the request processing<br>
  28.     ** 5. Directly set headers on the response after invocation of the next entity in the filter chain.
  29.     **/
  30.     public void doFilter ( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException;

  31.     /**
  32.     * Called by the web container to indicate to a filter that it is being taken out of service. This
  33.     * method is only called once all threads within the filter's doFilter method have exited or after
  34.     * a timeout period has passed. After the web container calls this method, it will not call the
  35.     * doFilter method again on this instance of the filter. <br><br>
  36.     *
  37.          * This method gives the filter an opportunity to clean up any resources that are being held (for
  38.     * example, memory, file handles, threads) and make sure that any persistent state is synchronized
  39.     * with the filter's current state in memory.
  40.     */

  41.     public void destroy();


  42. }
Filter介面中有一個doFilter方法,當開發人員編寫好Filter,並配置對哪個web資源進行攔截後,Web伺服器每次在呼叫web資源的service方法之前,都會先呼叫一下filter的doFilter方法,因此,在該方法內編寫程式碼可達到如下目的:

呼叫目標資源之前,讓一段程式碼執行。 是否呼叫目標資源(即是否讓使用者訪問web資源)。 web伺服器在呼叫doFilter方法時,會傳遞一個filterChain物件進來,filterChain物件是filter介面中最重要的一個物件,它也提供了一個doFilter方法,開發人員可以根據需求決定是否呼叫此方法,呼叫該方法,則web伺服器就會呼叫web資源的service方法,即web資源就會被訪問,否則web資源不會被訪問。

在一個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時,可以使用為filter配置一些初始化引數,當web容器例項化Filter物件,呼叫其init方法時,會把封裝了filter初始化引數的filterConfig物件傳遞進來。因此開發人員在編寫filter時,通過filterConfig物件的方法,就可獲得以下內容:


STRING getFilterName();//得到filter的名稱。 
STRING getInitParameter(STRING NAME);//返回在部署描述中指定名稱的初始化引數的值。如果不存在返回null. 
Enumeration getInitParameterNames();//返回過濾器的所有初始化引數的名字的列舉集合。 
public ServletContext getServletContext();//返回Servlet上下文物件的引用。


四:過濾器例項

本例項的作用是使頁面支援gzip壓縮資源請求(Content-Encoding:gzip)

web.xml配置

點選(此處)摺疊或開啟

  1. <filter>
  2.         <filter-name>GzipJsFilter</filter-name>
  3.         <filter-class>com.gemdale.gmap.manager.web.filter.GzipJsFilter</filter-class>
  4.         <init-param>
  5.             <param-name>headers</param-name>
  6.             <param-value>Content-Encoding=gzip</param-value>
  7.         </init-param>
  8.     </filter>
  9.     <filter-mapping>
  10.         <filter-name>GzipJsFilter</filter-name>
  11.         <url-pattern>*.gzjs</url-pattern>
  12.     </filter-mapping>
程式碼:

點選(此處)摺疊或開啟

  1. public class GzipJsFilter implements Filter {
  2.     Map headers = new HashMap();

  3.     public void destroy() {
  4.     }

  5.     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
  6.             throws IOException, ServletException {
  7.         if (req instanceof HttpServletRequest) {
  8.             doFilter((HttpServletRequest) req, (HttpServletResponse) res, chain);
  9.         }
  10.         else {
  11.             chain.doFilter(req, res);
  12.         }
  13.     }

  14.     public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
  15.             throws IOException, ServletException {
  16.         request.setCharacterEncoding("UTF-8");
  17.         for (Iterator it = headers.entrySet().iterator(); it.hasNext();) {
  18.             Map.Entry entry = (Map.Entry) it.next();
  19.             response.addHeader((String) entry.getKey(), (String) entry.getValue());
  20.         }
  21.         chain.doFilter(request, response);
  22.     }

  23.     public void init(FilterConfig config) throws ServletException {
  24.         String headersStr = config.getInitParameter("headers");
  25.         String[] headers = headersStr.split(",");
  26.         for (int i = 0; i < headers.length; i++) {
  27.             String[] temp = headers[i].split("=");
  28.             this.headers.put(temp[0].trim(), temp[1].trim());
  29.         }
  30.     }
  31. }







來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28624388/viewspace-2129713/,如需轉載,請註明出處,否則將追究法律責任。

相關文章