具體的使用方法你可以在google上搜尋 “filter 過濾器”,FilterConfig可以擷取部署描述符檔案(web.xml)中分配的過濾器初始化參數。 針對你的問題回答,結果就是說FilterConfig可以獲得web.xml中,以 filter 作為描述標籤內的參數。 定義: FilterConfig對象提供對servlet環境及web.xml檔案中指派的過濾器名的訪問。 FilterConfig對象具有一個getInitParameter方法,它能夠訪問部署描述符檔案(web.xml)中分配的過濾器初始化參數。 執行個體: 將下面的代碼加入到web.xml中,試用FilterConfig就可以獲得以 filter 作為描述標籤內的參數。 <!-- The Cache Filter --> <filter> <!-- 設計過濾處理類,產生靜態頁面 --> <filter-name>CacheFilter</filter-name> <filter-class>com.jspbook.CacheFilter</filter-class> <!-- 不需要緩衝的URL --> <init-param> <param-name>/TimeMonger.jsp</param-name> <param-value>nocache</param-value> </init-param> <init-param> <param-name>/TestCache.jsp</param-name> <param-value>nocache</param-value> </init-param> <!-- 緩衝逾時時間, 單位為秒 --> <init-param> <param-name>cacheTimeout</param-name> <param-value>600</param-value> </init-param> <!-- 是否根據瀏覽器不同的地區設定進行緩衝(產生的快取檔案為 test.jspid=1_zh_CN 的格式) --> <init-param> <param-name>locale-sensitive</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CacheFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> 用法: filterConfig.getInitParameter("locale-sensitive"); 得到的就是 ture filterConfig.getInitParameter("cacheTimeout"); 得到的就是 600 filterConfig.getInitParameter(request.getRequestURI()); 得到的就是param-name 對應的 param-value 值 過濾處理類: public class CacheFilter implements Filter { ServletContext sc; FilterConfig fc; long cacheTimeout = Long.MAX_VALUE; public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; // check if was a resource that shouldn't be cached. String r = sc.getRealPath(""); String path = fc.getInitParameter(request.getRequestURI()); if (path != null && path.equals("nocache")) { chain.doFilter(request, response); return; } path = r + path; } public void init(FilterConfig filterConfig) { this.fc = filterConfig; String ct = fc.getInitParameter("cacheTimeout"); if (ct != null) { cacheTimeout = 60 * 1000 * Long.parseLong(ct); } this.sc = filterConfig.getServletContext(); } public void destroy() { this.sc = null; this.fc = null; } } |