java中的監聽和過濾器

監聽request對象的兩個接口

ServletRequestListener

ServletRequestAttributeListener

接口的作用及方法

ServletRequestListener

監聽request的創建和銷毀

1 requestInitialized(ServletRequestEvent sre)

2.requestDestroyed(ServletRequestEvent sre)

ServletRequestAttributeListener

AttributeAdded(HttpSessionBindingEven event) 添加

AttributeRemoved(HttpSessionBindingEven event) 刪除

AttributeReplaced(HttpSessionBindingEven event) 修改

在web.xml中配置監聽

<listener>

? ? <listener-class>包名 點 類名</listener-class>

</listener>

監聽session對象的接口

HttpSessionListener

HttpSessionAttributeListener

接口的方法及作用

監聽session的創建和銷毀:HttpSessionListener

SessionCreated(HttpSessionEvent se);創建session對象

SessionDestroyed(HttpSessionEvent se) 銷毀session對象

監聽session作用域數據的變更:HttpSessionAttributeListener

AttributeAdded(HttpSessionBindingEvent event) 添加

AttributeRemoved(HttpSessionBindingEvent event) 移除

AttributeReplaced(HttpSessionBindingEvent event) 修改

監聽application對象的接口

ServletContextListener

ServletContextAttributeListener

方法及作用

ServletContextListener:監聽application對象的創建和銷毀

contextInitialized(ServletContextEvent sce) application對象的創建

contextDestroyed(ServletContextEvent sce) 銷毀

ServletContextAttributeListtener 監聽application對象的變更

AttributeAdded(ServletContextAttributeEvent event)

AttributeRemoved(ServletContextAttributeEvent event)

AttributeReplaced(ServletContextAttributeEvent event)

過濾器

引入過濾器可以提高安全性和減少資源浪費?

創建過濾器需要實現的三個方法

Init()? ? ? ? doFilter()? ? Destroy()

在web.xml中配置過濾器

?<filter>

<filter-name>配置的過濾器名稱</filter-name>

<filter-class>要配置的過濾器的全限定路徑:包名.類名</filter-class>

</filter>

<filter-mapping>

<filter-name>配置的過濾器名稱</filter-name>

<url-pattern>過濾器攔截請求地址的范圍</url-pattern>

</filter-mapping>

過濾器之doFilter方法

?作用:服務器在接收到瀏覽器發過來的請求后,先解析請求信息,創建對象request和

response對象,然后根據請求url地址判斷如果符合過濾器的過濾范圍,則會調用過濾器

中的doFilter來進行請求攔截,并將request和response對象作為實參傳遞給doFilter

方法。我們可以在doFilter方法中聲明過濾器攔截代碼。

參數:

ServletRequest:接收此次攔截的請求的request實參

?ServletResponse :接收此次攔截請求的response實參

FilterChain :可以進行請求放行

????????chain.doFilter(request,response);

過濾器init和destory方法

init()方法 服務器加載的時候調用

destroy()? ? 服務器關閉時調用

過濾器之攔截范圍配置

攔截所有:/*

攔截部分Servlet的請求:*.do 攔截以 點 do 結尾的

攔截指定的Servlet的請求:和要攔截的指定的servlet的url-pattern配置完全一致即可

注意:過濾器之間會出現多重攔截,如果是按照攔截范圍的大小為web.xml中自大而小進行的配置

?則會先執行大范圍的攔截器,在執行小范圍的攔截器

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容