## 過濾器
過濾器(Filter),并非必須,但很實用。
過濾器是一種設計模式,主要用來封裝Servlet中一些通用的代碼。在web.xml中配置哪些URL對應哪些過濾器。
一個過濾器的寫法如下:
~~~
public void doFilter(ServletRequest request , ServletResponse response , FilterChain chain) {
//處理 request
chain.doFilter(request, response);
//處理 response
}
~~~
假設針對一URL定義了3個過濾器,分別是MyFilter1、MyFilter2、MyFilter3,在web.xml中也是按照這個順序設置的, 那么過濾器和Servlet的執行順序如下:
* MyFilter1中處理request的代碼;
* MyFilter2中處理request的代碼;
* MyFilter3中處理request的代碼;
* 相應的Servlet;
* MyFilter3中處理response的代碼;
* MyFilter2中處理response的代碼;
* MyFilter1中處理response的代碼;
之所以能達到這樣的效果,`chain.doFilter(request, response);`起到了很大的作用。 值得注意的是,如果每個Filter沒有到達`chain.doFilter`就返回了,那么后續的Filter或者Servlet也就不會執行。
**相關資料:**
[Tomcat 的過濾訣竅](http://www.ibm.com/developerworks/cn/java/j-tomcat/)
[三個有用的過濾器](http://www.iteye.com/topic/185094)
[Java Web筆記 – Servlet中的Filter過濾器的介紹和使用 編寫過濾器](http://www.itzhai.com/java-web-notes-servlet-filters-in-the-filter-writing-the-introduction-and-use-of-filters.html#read-more)
[Intercepting HTTP Response using Servlet Filter](https://punekaramit.wordpress.com/2010/03/16/intercepting-http-response-using-servlet-filter/)
[How to write response filter?](http://stackoverflow.com/questions/5634477/how-to-write-response-filter)
[責任鏈模式](http://www.runoob.com/design-pattern/chain-of-responsibility-pattern.html)
## [](https://github.com/someus/another-tutorial-about-java-web/blob/master/00-05.md#監聽器)監聽器
當某個事件發生時候,監聽器里的方法會被調用。例如Tomcat容器啟動時、銷毀時,session創建時、銷毀時。
- JSP & Servlet
- 00-00、序
- 00-01、相關軟件的安裝
- 00-02、理解HTTP
- 00-03、從JSP開始
- 00-04、理解Servlet
- 00-05、過濾器與監聽器
- 00-06、使用velocity模板引擎
- 00-07、使用數據庫連接池
- 00-08、Tomcat的運行機制
- Spring MVC
- 01-00、Spring與依賴注入
- 01-01、Spring與面向切面編程
- 01-02、使用Spring MVC構建Hello World
- 01-03、JdbcTemplate
- 01-04、基于注解的URL映射
- 01-05、JSON
- 01-06、校驗器
- 01-07、國際化
- 01-08、攔截器
- 01-09、文件上傳
- 01-10、轉換器與格式化
- Book
- Online Tutorial
- Q & A
- Learn More
- Supplement