difference between servlet lifecycle and filter lifecycle

落花浮王杯 提交于 2019-12-30 01:59:05

问题


is there any difference between servlet and filter lifecycle?.


回答1:


No, both a servlet and a filter:

  • are instantiated (once) when the context starts
  • the init(..) method is called
  • they handle each request - first it passes through all filters and then reaches the servlet
  • when the context is destroyed (i.e. when your container stops, or your application is undeployed from the manager console), the destroy(..) method is called



回答2:


So far I was also wondering the differences. I created a web project to observe life-cycle of them. It can be check-outed at

http://dntuan-java-workspace.googlecode.com/svn/trunk/simple-web

Once it is deployed on tomcat, you can observe logs from the console to see that filters are initialized before context is started. Whereas servlet is only initialized when a request is made (e.g. http://localhost:8080/simple-web/servlet/life.jsp)


More information from JSR-000315 JavaTM Servlet 3.0:

2.3.1 Loading and Instantiation

The servlet container is responsible for loading and instantiating servlets. The loading and instantiation can occur when the container is started, or delayed until the container determines the servlet is needed to service a request.

6.2.1 Filter Lifecycle

After deployment of the Web application, and before a request causes the container to access a Web resource, the container must locate the list of filters that must be applied to the Web resource as described below. The container must ensure that it has instantiated a filter of the appropriate class for each filter in the list, and called its init(FilterConfig config)method.



来源:https://stackoverflow.com/questions/3786111/difference-between-servlet-lifecycle-and-filter-lifecycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!