为什么过滤器只执行一次?

03-07-11 新疆朋友
我编写了一个测试的过滤器,当我第一次装载一个servlet时,过滤器发挥作用,重复刷新该servlet时,过滤器没有被调用,是否是我的配置有问题,如果真是这样,就无法使用它来做认证了。请高手指点。谢谢
我的web.xml:
<web-app>
<filter>
<filter-name>Servlet Mapped Filter</filter-name>
<filter-class>filters.ExampleFilter</filter-class>
<init-param>
<param-name>attribute</param-name>
<param-value>filters.ExampleFilter.SERVLET_MAPPED</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>Servlet Mapped Filter</filter-name>
<servlet-name>invoker</servlet-name>
</filter-mapping>

<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
</web-app>


过滤器程序:
package filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public final class ExampleFilter implements Filter {


private String attribute = null;
private FilterConfig filterConfig = null;
public void destroy() {
System.out.println("enter filter.destory()");
this.attribute = null;
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
System.out.println("enter filter.doFilter()");
// Store ourselves as a request attribute (if requested)
if (attribute != null)
request.setAttribute(attribute, this);

// Time and log the subsequent processing
long startTime = System.currentTimeMillis();
chain.doFilter(request, response);
long stopTime = System.currentTimeMillis();
String url = ((HttpServletRequest)request).getRequestURI();
filterConfig.getServletContext().log
(this.toString() + "(" + url + "): " + (stopTime - startTime) +
" milliseconds");
}

public void init(FilterConfig filterConfig) throws ServletException {

System.out.println("enter filter.init()");
this.filterConfig = filterConfig;
this.attribute = filterConfig.getInitParameter("attribute");

}
public String toString() {

if (filterConfig == null)
return ("InvokerFilter()");
StringBuffer sb = new StringBuffer("InvokerFilter(");
sb.append(filterConfig);
sb.append(")");
return (sb.toString());
}
}

新疆朋友
2003-07-11 12:15
请各位高手帮忙,我的结论是否正确,给个明确的回复,如果是每次装载servlet时,都能执行过滤器的话,我一定在多次几次,给兄弟指条路。再次表示感谢。

porlo
2003-07-11 14:52
可能是因为你的浏览器没有重新从服务器请求文档,而是使用了缓存。
关闭浏览器窗口,再重新打开试下吧。

新疆朋友
2003-07-11 15:34
我明白了,主要是在web.xml中的设置有关,我将
《servlet-name》invoker《/servlet-name》改为
《url-pattern》/servlet/*《/url-pattern》,一切问题解决。
我个人猜,invoker和servlet的装载一样,装载一次下次从内存中运行,不需要再次装载。