filterconfig
在Filter的init方法中有一个参数filterconfig.
FilterConfig作用也是获取Filter的相关配置信息:
1.初始化参数的获取
String getInitparameter(String name);
Enumeration EnumerngetInitParameterNames();
2.Filter的名称获取
getFilterName();
3.Servletcontext对象的获取
getServletContext();
测试:创建一个DemoFilter2的类文件.
package cn.itcast.web.filter;
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;
import com.sun.net.httpserver.Filter.Chain;
//Filter入门
//1.创建一个类,实现Filter接口
//2.重写方法
//3.在web.xml文件中配置
public class DemoFilter2 implements Filter{
public void destroy() {
}
//用来过滤的方法
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("DemoFilter2进行过滤操作...");
//放行
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
//1.获取Filter名称
String filterName = filterConfig.getFilterName();
System.out.println(filterName);
//2.获取初始化参数
String encoding = filterConfig.getInitParameter("encoding"); //根据指定名称获取
System.out.println(encoding);
Enumeration<String> names = filterConfig.getInitParameterNames();//获取所有名称
while(names.hasMoreElements()){
System.out.println(names.nextElement());
}
//3.获取ServletContext对象
filterConfig.getServletContext();
}
}
然后修改web.xml的配置文件.
<?xml version="1.0" encoding="UTF-8"?>
<web-APP version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- Filter入门 -->
<filter>
<filter-name>demoFilter</filter-name>
<filter-class>cn.itcast.web.filter.DemoFilter</filter-class>
</filter>
<filter>
<filter-name>demoFilter2</filter-name>
<filter-class>cn.itcast.web.filter.DemoFilter2</filter-class>
<!-- 初始化参数 -->
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>tom</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>demoFilter2</filter-name>
<url-pattern>/index.jsp</url-pattern> <!-- 访问index.jsp页面会被DemoFilter过滤掉 -->
</filter-mapping>
<filter-mapping>
<filter-name>demoFilter</filter-name>
<url-pattern>/index.jsp</url-pattern> <!-- 访问index.jsp页面会被DemoFilter过滤掉 -->
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
运行到服务器上,控制台会输出.