新建一個Filter
創建一個Filter02類實現 Filte接口
public class Filter02 implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { System.out.println("Filter02 doFilter"); chain.doFilter(req, resp); } public void init(FilterConfig config) throws ServletException { System.out.println("Filter02 init"); } }
在web.xml中配置Filter
<filter> <filter-name>Filter02</filter-name> <filter-class>com.zjl.main.filter.Filter02</filter-class> </filter> <filter-mapping> <filter-name>Filter02</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
- 部署至Tomcat,啓動運行,會在控制檯中打印
Filter02 init
Filter02 doFilter
注: 如果在web.xml中有多個Filter,他們的執行順序會根據
<filter-mapping></filter-mapping>
的配置順序調用不同的Filter.
Filter的生命週期
- 服務器啓動時,由服務器創建Filter對象,執行init()方法。
- 當訪問的資源被攔截時,執行doFilter() 方法。
- 放行:filterChain.doFilter(servletRequest, servletResponse);
- 服務器關閉時,執行destory() 方法。
FilterConfig
// 獲取Filter的filter-name
String filterName = config.getFilterName();
System.out.println(filterName);
// 獲取在web.xml中<filter></filter>裏配置的初始化參數
/*
<filter>
<filter-name>Filter02</filter-name>
<filter-class>com.zjl.main.filter.Filter02</filter-class>
<init-param>
<param-name>username</param-name>
<param-value>admin</param-value>
</init-param>
</filter>
*/
String username = config.getInitParameter("username");
System.out.println("username is " + username);
// 獲取ServletContext對象
ServletContext servletContext = config.getServletContext();
String contextPath = servletContext.getContextPath();
System.out.println(contextPath);
Filter的配置
- url-pattern配置
- 完全路徑匹配 :/*
- 目錄匹配 : /a/*
- 擴展名匹配 : 不能以 / 開始,*.jsp
- 指定過濾某一確定的Servlet
<servlet-name>Test01</servlet-name>
- 指定過濾以哪一種方式過來的請求
<dispatcher>REQUEST</dispatcher>
(可以配置多個)
- REQUEST : 默認值
- FORWAD: 攔截轉發
- ERROR: 攔截跳轉到錯誤頁面
- INCLUDE: 攔截在某一頁面包含另一頁面