JavaWeb監聽器、過濾器、
JavaWeb監聽器:域監聽器
Ø ServletContext
¨ 生命週期監聽:ServletContextListener
² 建立SErvletcontext觸發:voidcontextInitialized(ServletContextEvent sce)
² 銷燬Servletcontext觸發:voidcontextDestroyed(ServletContextEvent sce)
¨ 屬性監聽:ServletContextAttributeListener
Ø HttpSession
¨ 生命週期監聽:HttpSessionListener
² 建立session時:voidsessionCreated(HttpSessionEvent se)
² 銷燬session時:voidsessionDestroyed(HttpSessionEvent se)
¨ 屬性監聽:HttpSessioniAttributeListener
² 替換屬性時:voidattributeReplaced(HttpSessionBindingEvent event)
Ø ServletRequest
¨ 生命週期監聽:ServletRequestListener
² 建立request時:voidrequestInitialized(
² 銷燬request時:voidrequestDestroyed(ServletRequestEvent sre)
¨ 屬性監聽:ServletRequestAttributeListener。
過濾器
1. 作用:它會在一組資源的前面執行,具有攔截請求的能力。與Servlet類似是單例的。
2. 實現方法:
1) 寫一個類實現Filter介面:需實現介面中的3個生命週期方法
voidinit(FilterConfig):建立之後馬上執行,用來初始化Filter例項。只調用一次。
a) 引數:FilterConfig-->與ServletConfig相似
* 獲取初始化引數:getInitParameter()
* 獲取過濾器名稱:getFilterName()
* 獲取appliction:getServletContext()
2) void destory():銷燬之前執行,在伺服器關閉時銷燬。只調用一次。
3) void doFilter(ServletRequest,ServletResponse,FilterChain):每次過濾時都會執行
Ø FilterChain:重要方法doFilter(ServletRequest, ServletResponse),作用是放行,即執行目標資源,或是執行下一個過濾器。如果沒有下一個過濾器那麼執行的是目標資源,如果有,那麼就執行下一個過濾器
4) 過濾器的四種攔截方式
a) <dispatcher>REQUEST</dispatcher>:預設的,對請求進行攔截
b) <dispatcher>FORWARD</dispatcher>:對轉發進行攔截
c) <dispatcher>INCLUDE</dispatcher>:對包含進行攔截
d) <dispatcher>ERROR</dispatcher>:對錯誤進行攔截
3. 在web.xml中進行配置
<filter>
<filter-name>xxx</filter-name>
<filter-class>cn.itcast.web.filter.AFitler</fitler-class>
</filter>
<fitler-mapping>
<filter-name>xxx</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
1) 若有多個攔截器,配置順序就是攔截器的執行順序