大家好,欢迎来到IT知识分享网。
在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>
运行到服务器上,控制台会输出.
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/9749.html