Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Servlet 監聽器與過濾器:Listener 與 Filter 完全梳理

編輯:關於 Android 程式設計

一、Listener 監聽器

監聽器是 Servlet 的一種擴展機制,可以監聽客戶端請求與服務端操作,並在事件發生時自動觸發一段邏輯。典型場景是在線人數統計:每當創建一個 HttpSession,就觸發 sessionCreated(HttpSessionEvent se),在方法內把計數加一即可。

在 javax.servlet 中,監聽器按作用範圍分為三類:ServletContext 相關、ServletRequest 相關、HttpSession 相關。

1. ServletContext 相關

ServletContextAttributeListener:監聽上下文屬性的增刪改。
attributeAdded(scab):新增屬性時觸發;
attributeRemoved(scab):移除已有屬性時觸發;
attributeReplaced(scab):替換已有屬性時觸發。

ServletContextListener:監聽 ServletContext 本身的載入與銷毀。
contextInitialized(sce):創建上下文時觸發,所有 ServletContextListener 都會先於 filter 與 servlet 的初始化被通知;
contextDestroyed(sce):銷毀上下文時觸發,所有 filter 與 servlet 都會先於它被 destroy。

由此不難總結出初始化順序:listener → filter → servlet。

2. ServletRequest 相關

ServletRequestListener:當希望接收請求進入或離開某個 web 部件的消息時實現此接口。請求進入應用的第一個 servlet 或 filter 時觸發進入事件,離開最後一個 servlet 或 filter 時觸發離開事件(需注意 filter 鏈的執行順序)。
requestInitialized(sre):請求即將進入應用;
requestDestroyed(sre):請求即將離開應用。

ServletRequestAttributeListener:監聽 request 屬性的變更,通知只在 request 處於應用處理期間發出。
attributeAdded(srae):新增屬性;
attributeRemoved(srae):移除屬性;
attributeReplaced(srae):替換屬性。

3. HttpSession 相關

HttpSessionListener:監聽會話本身的變化。
sessionCreated(se):創建 Session 時觸發;
sessionDestroyed(se):銷毀 Session 時觸發。

HttpSessionAttributeListener:監聽會話屬性的變化。
attributeAdded(se):Session 新增屬性;
attributeRemoved(se):Session 刪除屬性;
attributeReplaced(se):Session 屬性被重新設置。

4. 如何註冊監聽器

監聽器需要在 web.xml 的 web-app 元素內放置 listener 元素進行聲明,並在其中用 listener-class 給出完整限定類名:

<listener>
    <listener-class>package.ListenerClass</listener-class>
</listener>

結構雖簡單,但有兩點務必注意:一是 web-app 內子元素的順序有嚴格要求,listener 元素位於所有 servlet 元素之前、所有 filter-mapping 元素之後;二是應用生命週期監聽屬於 Servlet 2.3 規範的新特性,必須使用 2.3 版本的 DTD。

下面是一個簡單的上下文監聽器示例,它在應用裝載與關閉時向標准輸出打印消息:

package moreservlets;

import javax.servlet.*;
import java.util.*;

public class ContextReporter implements ServletContextListener {
    public void contextInitialized(ServletContextEvent event) {
        ServletContext servletContext = event.getServletContext();
        System.out.println("Context created on " + new Date() + ".");
    }

    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("Context destroyed on " + new Date() + ".");
    }
}

對應的 web.xml 片段:

<filter-mapping> ... </filter-mapping>
<listener>
    <listener-class>package.ListenerClass</listener-class>
</listener>
<servlet> ... </servlet>

二、Filter 過濾器

過濾器是小型 web 組件,能夠攔截請求與響應,從而查看、提取或以某種方式加工客戶端與服務端之間交換的數據。最典型的用途就是統一處理中文編碼問題。

過濾器先於關聯的 servlet 或 jsp 運行,可附加到一個或多個資源上,並在請求到達這些資源之前檢查請求信息。拿到請求後,它可以做四種選擇:按原樣調用資源;修改請求信息後調用;調用資源但在返回前修改響應;或乾脆攔下請求,轉由其他資源處理。

過濾器通過 web.xml 聲明,因此增刪過濾器無需改動任何業務代碼。匹配時先依 url-pattern 判斷由哪個過濾器處理;若一個 URL 同時符合多個過濾器的模式,則按 filter-mapping 在 web.xml 中的配置順序依次執行。

實現方式

開發過濾器需實現 javax.servlet.Filter 接口,其中定義了三個方法,對應過濾器的完整生命週期:

init(FilterConfig filterConfig):容器在實例化過濾器之後調用,用於完成初始化,只在第一次初始化時執行一次。通過 FilterConfig 可以讀取 web.xml 中配置的初始化參數(getInitParameter)。

doFilter(request, response, chain):過濾邏輯的所在,容器會在每個請求/響應鏈路中調用它。第三個參數 FilterChain 是關鍵——調用 chain.doFilter() 可把請求交給鏈路中的下一個過濾器,若後面沒有其他過濾器,則目標 servlet 或 jsp 被激活。

destroy():與 init 相對應,在銷毀實例前由容器調用,主要用於釋放申請過的資源。

配置與部署

配置需要兩個元素。<filter> 向系統註冊過濾對象,包含 filter-name(名稱)、filter-class(實現類)、init-param(可選的初始化參數,一組名值對)。<filter-mapping> 指定過濾器作用的範圍,包含 filter-name(引用已定義的過濾器)以及 url-pattern 或 servlet-name 之一。

url-pattern 以斜槓開頭:/* 匹配所有請求,/*.jsp 匹配所有 jsp 頁面,/manage/* 匹配 /manage 下的所有請求。servlet-name 則需與 servlet 元素中給定的名稱一致。兩者都支持通過重複整個 filter-mapping 元素來配置多組映射。

字符編碼過濾器的配置示例:

<filter>
    <filter-name>SimpleFilter</filter-name>
    <filter-class>com.darkmi.filter.SimpleFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>SimpleFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

實現代碼:

public class SetCharacterEncodingFilter implements Filter {

    protected String encoding = null;
    protected FilterConfig filterConfig = null;
    protected boolean ignore = true;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
        String value = filterConfig.getInitParameter("ignore");
        if (value == null) {
            this.ignore = true;
        } else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")) {
            this.ignore = true;
        } else {
            this.ignore = false;
        }
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 按需重新設置請求編碼
        if (ignore || request.getCharacterEncoding() == null) {
            String encoding = selectEncoding(request);
            if (encoding != null) {
                request.setCharacterEncoding(encoding);
            }
        }
        chain.doFilter(request, response);
    }

    public void destroy() {
        this.encoding = null;
        this.filterConfig = null;
    }

    protected String selectEncoding(ServletRequest request) {
        return this.encoding;
    }
}

另一個實用例子是禁止瀏覽器緩存頁面,只需在響應頭上動手腳:

public class ForceNoCacheFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Pragma", "no-cache");
        resp.setDateHeader("Expires", -1);
        chain.doFilter(request, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException { }

    public void destroy() { }
}

總的來說,Listener 解決的是「事件發生時通知我」,Filter 解決的是「請求經過時攔住它」,兩者都是在不侵入業務代碼的前提下擴展 web 應用的橫向能力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved