<filter-mapping>
<filter-name>MappingFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
`
e)对于过滤Servlet资源时,即可使用url-pattern,又可以使用servlet-name
f)一个Filter可以过滤1个或N个资源
</filter>
<filter-mapping>
<filter-name>MappingFilter</filter-name>
<url-pattern>/FromServlet</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>MappingFilter</filter-name>
<url-pattern>/ToServlet</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter>`
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;
public class MappingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
System.out.println("MappingFilter::doFilter():A");
chain.doFilter(request,response);
System.out.println("MappingFilter::doFilter():B");
System.out.println("模拟正在写日志Log4J");
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
//
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ToServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
System.out.println("ToServlet::doGet()");
//int i = 10 / 0;
}
}
//
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FromServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
System.out.println("FromServlet::doGet()");
request.getRequestDispatcher("/ToServlet").forward(request,response);
//request.getRequestDispatcher("/ToServlet").include(request,response);
}
}
原文地址:http://blog.51cto.com/357712148/2105470