a)Filter是SUN公司提供的一个资源过滤器接口,不同的Web容器有着不同的实现
b)Filter位于Web服务器和Web资源(Servlet/Jsp/Html)之间
c)过滤请求和响应二者
d)Filter可以进行简单判段,是否将请求放行给Web资源
e)Filter的开发过程:
>类 implements javax.servlet.Filter接口
>在web.xml文件配置Filter过滤器,告之Web服务器有过滤器的存在
web.xml中的配置信息如下:
<filter>
<filter-name>FilterDemo1</filter-name>(过滤器,可以随意,但要和filter-mapping中的name一致)
<filter-class>cn.web.filter.FilterDemo1</filter-class>(过滤器全路径)
</filter>
<filter-mapping>
<filter-name>FilterDemo1</filter-name>(过滤器名,同上)
<url-pattern>/*</url-pattern>(过滤器能够过滤的资源路径,不是用户在URL中访问的路径)
</filter-mapping>
ShowServlet
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 ShowServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("test/html; charset=UTF-8"); response.getWriter().write("欢迎学习servlet下篇"); }}
FilterDemo1
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;//自定义Filter过渡器public class FilterDemo1 implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException { System.out.println("过滤器+++doFilter()"); //放行请求[类似于函数调用] chain.doFilter(request,response); System.out.println("放行请求[类似于函数调用]"); } public void init(FilterConfig filterConfig) throws ServletException { }}
web.xml配置
<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" 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_3_0.xsd"> <filter> <filter-name>FilterDemo1</filter-name> <filter-class>cn.web.servlet.filter.FilterDemo1</filter-class> </filter> <filter-mapping> <filter-name>FilterDemo1</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>