日期:2014-05-18  浏览次数:20710 次

一个关于过滤器的问题----在线等
譬如我想对除了index.jsp之外的页面进行过滤,在web.xml中我该怎样配置?

------解决方案--------------------
web.xml中配置:

<filter>
   <filter-name> filter1 path </filter-name>
   <filter-class> com.filter.PathFilter </filter-class>
</filter>
<filter-mapping>
   <filter-name> filter path </filter-name>
   <url-pattern> /* </url-pattern>
</filter-mapping>

还需要新建一个过滤器类:

package com.filter;

import ...

public class PathFilter implements Filter {
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest)request;
    // HttpServletResponse httpResponse = (HttpServletResponse) response;

    // 这里你还需添加其他资源路径(如图像、CSS、JS),否则也会进行过滤
    if(!httpRequest.getRequestURI().endsWith( "/index.jsp ")){
      // 需要进行的处理
    }  
    chain.doFilter(request, response);
  }
}
------解决方案--------------------
首先你的web.xml中写错了。两个filter-name的元素必须一致的,另外,如果要实现除了xx.jsp或者servlet的这样的过滤功能,可以在web.xml中直接写/*,然后在过滤器中判断是否是index.jsp页面,如果是的话,就跳过过滤程序。或者你可以将index.jsp页面,与其他页面分成两个文件夹,这样只要在web.xml中写/需要过滤的文件夹/*。这样也可以。不过建议使用第一种方法。