java關於ServletConfig FilterConfig什么用


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM