ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 过滤器 过滤器(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创建时、销毁时。