java關於ServletConfig FilterConfig什麼用

來源:互聯網
上載者:User

具體的使用方法你可以在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;
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.