Filter
簡介
概念: Filter 表示過濾器,是 JavaWeb 三大組件(Servlet、Filter、Listener)之一。
過濾器可以把對資源的請求攔截下來,從而實現一些特殊的功能。
過濾器一般完成一些通用的操作,比如:權限控制、統一編碼處理、敏感字符處理等等.
快速入門
1.定義類,實現 Filter接口,并重寫其所有方法
public class FilterDemo implements Filter{
? ? ? ? ? public void init(FilterConfig filterConfig)
? ? ? ? ? public void doFilter(ServletRequest reguest
? ? ? ? ? public void destroy() {}
}
2.配置Filter攔截資源的路徑:在類上定義 @WebFilter 注解
@WebFilter("/*")
public class FilterDemo implements Filter {
3.在doFilter方法中輸出一句話,并放行
public void doFilter(ServletRequest request,ServletResponse,FilterChain chain)
? ? ? ? ? ?System.out.println("filter 被執行了..");
? ? ? ? ? ?chain.doFilter(request,response);
}
執行流程
注:
放行后訪問對應資源,資源訪問完成后,還會回到Fiter中嗎?? ? 會
如果回到Filter中,是重頭執行還是執行放行后的邏輯呢?? ? ?放行后邏輯
? ? ? ?執行放行前邏輯-->?放行--> 訪問資源--> 執行放行后邏輯
使用細節
1.Filter 攔截路徑配置
? ? ? ? ? Filter 可以根據需求,配置不同的攔截資源路徑
? ? ? ? ? ? ? ? ? @WebFilter("/*")
? ? ? ? ? ? ? ? ? public class FilterDemo
>攔截具體的資源:/index.jsp:只有訪問index.jsp時才會被攔截。
>目錄攔截:/user/*:訪問/user下的所有資源,都會被攔截
>后綴名攔截:*jsp:訪問后綴名為jsp的資源,都會被攔截
>攔截所有:/*:訪問所有資源,都會被攔截
2.過濾器鏈
一個Web應用,可以配置多個過濾器,這多個過濾器稱為過濾器鏈
注解配置的Filter,優先級按照過濾器類名(字符串)的自然排序
Listener
簡介
1.概念:Listener 表示監聽器,是JavaWeb 三大組件(Servlet、Filter、Listener)之一
監聽器可以監聽就是在application,session,request三個對象創建、銷毀或者往其中添加修改刪除屬
性時自動執行代碼的功能組件
2.Listener分類:JavaWeb中提供了8個監聽器
使用
ServletContextListener使用
1.定義類,實現ServletContextListener接口
public class ContextLoaderListener implements ServletContextListener {
? ? ? ? ? public void contextInitialized(ServletContextEvent sce){}
? ? ? ? ? public void contextDestroyed(ServletContextEvent sce){}
}
2.在類上添加@WebListener 注解