前言:这部分是我学习Filter通过web.xml配置时,总结和验证一些心得和总结,可能对您没有任何用处。主要是web.xml中<filter>标签和<filter-map>标签的配置顺序对于初始化Filter影响的顺序和调用Filter的顺序。
首先请看下面代码
public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub doctor=filterConfig.getInitParameter("DoctorWho"); System.out.println("*******"); System.out.println("*******"); count++; System.out.println(doctor); System.out.println(count); System.out.println("*******"); System.out.println("*******"); }
这个是Filter接口中的init方法主要是初始化Filter的一些参数,我当时感觉的困惑的是这句代码:
doctor=filterConfig.getInitParameter("DoctorWho");
通过过滤器配置文件,找到参数名“ DoctorWho”就可以找到参数名的值。先看下面的xml配置部分。
<filter> <filter-name>Doctor</filter-name> <filter-class>helloJava.guess.FilterGuess</filter-class> <init-param> <param-name>DoctorWho</param-name> <param-value>DoctorLiu</param-value> </init-param> </filter>
我认为是tomcat是通过通过web.xml中读取到<filter>时就会调用相关的Filter的init方法。
我写了一个验证类去验证先关问题。
package helloJava.guess; import java.io.IOException; 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 javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletRequest; public class FilterGuess implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } private int count=0; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub chain.doFilter(request, response); System.out.println("*******"); System.out.println("*******"); count++; System.out.println(doctor); System.out.println(count); System.out.println("*******"); System.out.println("*******"); } private String doctor; @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub doctor=filterConfig.getInitParameter("DoctorWho"); System.out.println("*******"); System.out.println("*******"); count++; System.out.println(doctor); System.out.println(count); System.out.println("*******"); System.out.println("*******"); } }
我想到的问题为
如果web.xml中<filter>标签中,有两个标签的<filter-name>不同,但是<filter-class>相同,会实例化几个对象?
web.xml配置内容为:
<filter> <filter-name>Doctor</filter-name> <filter-class>helloJava.guess.FilterGuess</filter-class> <init-param> <param-name>DoctorWho</param-name> <param-value>DoctorLiu</param-value> </init-param> </filter> <filter> <filter-name>Phd</filter-name> <filter-class>helloJava.guess.FilterGuess</filter-class> <init-param> <param-name>DoctorWho</param-name> <param-value>PhdLiu</param-value> </init-param> </filter>
根据控制台输出的结果,发现有两个标签的<filter-name>不同,但是<filter-class>相同时,会实例化不同的对象。
菜包子
2013年6月5日23:44:15 于宿舍