編輯:關於 Android 程式設計
監聽器是 Servlet 的一種擴展機制,可以監聽客戶端請求與服務端操作,並在事件發生時自動觸發一段邏輯。典型場景是在線人數統計:每當創建一個 HttpSession,就觸發 sessionCreated(HttpSessionEvent se),在方法內把計數加一即可。
在 javax.servlet 中,監聽器按作用範圍分為三類:ServletContext 相關、ServletRequest 相關、HttpSession 相關。
ServletContextAttributeListener:監聽上下文屬性的增刪改。
attributeAdded(scab):新增屬性時觸發;
attributeRemoved(scab):移除已有屬性時觸發;
attributeReplaced(scab):替換已有屬性時觸發。
ServletContextListener:監聽 ServletContext 本身的載入與銷毀。
contextInitialized(sce):創建上下文時觸發,所有 ServletContextListener 都會先於 filter 與 servlet 的初始化被通知;
contextDestroyed(sce):銷毀上下文時觸發,所有 filter 與 servlet 都會先於它被 destroy。
由此不難總結出初始化順序:listener → filter → servlet。
ServletRequestListener:當希望接收請求進入或離開某個 web 部件的消息時實現此接口。請求進入應用的第一個 servlet 或 filter 時觸發進入事件,離開最後一個 servlet 或 filter 時觸發離開事件(需注意 filter 鏈的執行順序)。
requestInitialized(sre):請求即將進入應用;
requestDestroyed(sre):請求即將離開應用。
ServletRequestAttributeListener:監聽 request 屬性的變更,通知只在 request 處於應用處理期間發出。
attributeAdded(srae):新增屬性;
attributeRemoved(srae):移除屬性;
attributeReplaced(srae):替換屬性。
HttpSessionListener:監聽會話本身的變化。
sessionCreated(se):創建 Session 時觸發;
sessionDestroyed(se):銷毀 Session 時觸發。
HttpSessionAttributeListener:監聽會話屬性的變化。
attributeAdded(se):Session 新增屬性;
attributeRemoved(se):Session 刪除屬性;
attributeReplaced(se):Session 屬性被重新設置。
監聽器需要在 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>
過濾器是小型 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 應用的橫向能力。
用 Windows cmd 視窗抓取 Android 手機 log 的技巧
前言 一般 Android 開發者習慣用 Eclipse 或 Android Studio 觀察 log 輸出,其實背後都是靠 adb 來印出 log。本文要介紹的是如何
Android Studio 與 Eclipse 的十個關鍵差異
Eclipse 是老牌的開發工具,早期寫 Android 的每個人都用過它,裝上 ADT 外掛就能开工。因為是開源的,開發起來頗為爽快……直到遇見 Google 親自操刀
Android 百度語音整合實務:語音喚醒、識別與合成的完整交互
百度語音提供語音喚醒、語音識別與語音合成能力,適合用來打造免手動的語音交互流程。使用者說出喚醒詞後,應用可進入識別狀態,並透過合成語音回饋結果。 整合重點 使用百度語音
Retrofit 實戰:Token 過期自動刷新並重放請求
社群裡有人提出這樣一個場景:App 請求某個接口時,因為 token 已失效而報錯;但產品經理希望 App 能立刻刷新 token,然後自動重試剛才那個接口,而整個過程對