FilterConfig的用法是什么
发布日期:2021-11-04 11:54:16 浏览次数:0 分类:技术文章

FilterConfig的用法是什么?

1. FilterConfig的用法:

FilterConfig可以从web.xml当中取得一些有关Filter参数,当Web应用启动时就可以获得了

FilterConfig对象提供对servlet环境及web.xml文件中指派的过滤器名的访问。
FilterConfig对象具有一个getInitParameter方法,它能够访问部署描述符文件(web.xml)中分配的过滤器初始化参数

实例:
将下面的代码加入到web.xml中,试用FilterConfig就可以获得以 filter 作为描述标签内的参数。

CacheFilter com.jspbook.CacheFilter /TimeMonger.jsp nocache /TestCache.jsp nocache cacheTimeout 600 locale-sensitive true CacheFilter *.jsp

用法:

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;
}
}`

上一篇:FilterChain的详解
下一篇:idea下载不了插件的设置以及背景图和背景图透明度的设置