标签:http package 初始化 strong 介绍 void 场景 ror context
一、JavaWeb三大组件
都需要在web.xml中进行配置
二、过滤器
创建示例:
1 package web.filter; 2 3 import javax.servlet.*; 4 import javax.servlet.annotation.WebFilter; 5 import java.io.IOException; 6 7 @WebFilter(filterName = "AFilter",urlPatterns = "/AServlet") 8 //urlPatterns为拦截资源路径名,等同于在下文配置web.xml文件 9 public class AFilter implements Filter { 10 /* 11 * 创建之后马上执行,用来做初始化,Filter会在服务器启动时就创建 12 * */ 13 public void init(FilterConfig config) throws ServletException { 14 System.out.println("过滤器出生了"); 15 } 16 /* 17 *每次过滤时都会执行 18 * */ 19 public void doFilter(ServletRequest req, ServletResponse resp, 20 FilterChain chain) throws ServletException, IOException { 21 System.out.println("拦截你"); 22 } 23 24 /* 25 * 销毁之前执行,在服务器关闭时销毁 26 * */ 27 public void destroy() { 28 System.out.println("过滤器要销毁了"); 29 } 30 }
web.xml文件
1 <filter> 2 <filter-name>AFilter</filter-name> 3 <filter-class>web.filter.AFilter</filter-class> 4 </filter> 5 <filter-mapping> 6 <filter-name>AFilter</filter-name> 7 <url-pattern>/AServlet </url-pattern> 8 </filter-mapping>
2、过滤器的生命周期
(<url-pattern>index.jsp</url-pattern>)”时执行,如果需要“放行”,那么需要调用FilterChain的doFilter(ServletRequest,ServletResponse)方法,如果不调用FilterChain的doFilter()方法,那么目标资源将无法执行;
功能与ServletConfig相似,与web.xml文件中的配置信息对应。下面是FilterConfig的功能介绍:
自动配置web.xml:
@WebFilter(filterName = "BFilter",urlPatterns = "/AServlet",dispatcherTypes = FORWARD)
//需导包
6、过滤器的应用场景
7、设置目标资源
<filter-mapping>
<filter-name>myfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>servlet.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>
<filter>
<filter-name>myfilter</filter-name>
<filter-class>filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myfilter</filter-name>
<servlet-name>myservlet</servlet-name>
</filter-mapping>
@WebFilter(filterName = "AFilter",servletNames = "AServlet",
urlPatterns = "/AServlet",dispatcherTypes = DispatcherType.FORWARD)
/*filterName 过滤器名
servletNames 指定过滤的servlet名字
urlPatterns为拦截资源路径
dispatcherTypes为拦截类型*/
标签:http package 初始化 strong 介绍 void 场景 ror context
原文地址:http://www.cnblogs.com/gdwkong/p/7634491.html