<filter>
<filter-name>FilterDemo3</filter-name>
<filter-class>cn.web.servlet.filter.FilterDemo3</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>FilterDemo3</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class FilterDemo3 implements Filter {
private FilterConfig filterConfig;
public FilterDemo3()
{
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
//WEB容器
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//从web.xml中全部获取参数
Enumeration<String> enums = filterConfig.getInitParameterNames();
while(enums.hasMoreElements())
{
String key = enums.nextElement();
String value = filterConfig.getInitParameter(key);
System.out.println(key+":"+value);
}
String encoding = filterConfig.getInitParameter("encoding");
response.setContentType("text/html;charset="+encoding);
chain.doFilter(request,response);
}
@Override
public void destroy() {
System.out.println("摧毁 方法: destroy()");
}
}
结果:
摧毁 方法: destroy()
四月 18, 2018 9:38:57 下午 org.apache.catalina.core.StandardContext reload
信息: Reloading Context with name [/day04] has started
四月 18, 2018 9:38:57 下午 org.apache.catalina.core.StandardContext reload
信息: Reloading Context with name [/day04] is completed
encoding:UTF-8
使用FilterConfig读取配置文件的信息 ---学习笔记
原文地址:http://blog.51cto.com/357712148/2105106