java HttpServlet 的生命周期是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3894088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the lifecycle of a HttpServlet?
提问by GC_
Basically, how long is an instance of a servlet around for? I am kind of guessing it is session scope. However, I suppose it could have some sort of timeout or garbage collection to remove old instances.
基本上,一个 servlet 的实例存在多长时间?我有点猜测它是会话范围。但是,我想它可能会有某种超时或垃圾收集来删除旧实例。
回答by Bozho
- a servlet is created when the application starts (it is deployed on the servlet container) or when it is first accessed (depending on the
load-on-startup
setting) - when the servlet is instantiated, the
init()
method of the servlet is called - then the servlet (its one and only instance) handles all requests (its
service()
method being called by multiple threads). That's why it is not advisable to have any synchronization in it, and you should avoid instance variables of the servlet - when the application is undeployed (the servlet container stops), the
destroy()
method is called.
- servlet 在应用程序启动时(部署在 servlet 容器上)或首次访问时创建(取决于
load-on-startup
设置) - 当servlet被实例化时,
init()
调用servlet的方法 - 然后 servlet(它的唯一实例)处理所有请求(它的
service()
方法被多个线程调用)。这就是为什么不建议在其中进行任何同步,并且您应该避免使用 servlet 的实例变量 - 当应用程序被取消部署时(servlet 容器停止),该
destroy()
方法被调用。
回答by Will Hartung
The lifecycle is well defined, and exposed through lifecycle methods exposed in init, service, and destroy methods of the Servlet.
生命周期定义良好,并通过 Servlet 的 init、service 和 destroy 方法中公开的生命周期方法公开。
And, despite what else is being said here, this is all you can count on from the specification. Basically, you get those three methods and a guarantee that Servlets are not thread safe. That a single servlet MAY be simultaneously accessed by one or more requests.
而且,尽管这里还说了些什么,但这就是您可以从规范中指望的全部内容。基本上,您可以获得这三种方法并保证 Servlet 不是线程安全的。一个或多个请求可以同时访问单个 servlet。
There is nothing in the specification that limits a servlet to one instance the container, if a container decides to, it can get a request, create a servlet, call it's init, then service, then destroy methods, and set it free for garbage collection.
规范中没有任何内容将 servlet 限制为容器的一个实例,如果容器决定这样做,它可以获取请求,创建 servlet,调用它的 init,然后调用 service,然后销毁方法,并将其释放以进行垃圾收集.
Individual containers have potentially different implementations.
单个容器可能有不同的实现。
Most containers do create a single instance. But the specification does not guarantee that, so you shouldn't rely on it.
大多数容器确实会创建单个实例。但是规范并不能保证这一点,所以你不应该依赖它。
Also, consider something like Google App Engine. GAE is VERY aggressive is continually expiring and shutting down entire web apps that receive no traffic. If you have a lightly traveled site, you can very well expect the entire app to start up, init all of its services, init any load-on-startup servlets, execute the request, and then shut everything down. So, on GAE it's imperative that you have a very fast application startup in order to maintain any semblance of performance.
另外,考虑像 Google App Engine 这样的东西。GAE 非常激进,它不断过期并关闭没有流量的整个 Web 应用程序。如果您有一个轻松访问的站点,您很可能会期望整个应用程序启动,初始化其所有服务,初始化任何加载启动 servlet,执行请求,然后关闭所有内容。因此,在 GAE 上,您必须拥有非常快速的应用程序启动才能保持任何外观的性能。
So, simply, what you can count on is what the specification says. Individual containers may offer different run time experiences.
因此,简单地说,您可以指望的是规范所说的内容。单个容器可能提供不同的运行时体验。
回答by deamon
A Servlet lives as long as the application does.
Servlet 的生命周期与应用程序的生命周期一样长。
回答by leonbloy
A servlet is not bound to a session, it is a service object that is instantiated by the container when needed, and typically is kept alive for the full life of the webapp. It typically responds to requests from several clients (and sessions), even concurrent requests. That's precisely why your servlet code must be thread safe, and you never store in a servlet field some data associated to a request or a session.
servlet 不绑定到会话,它是一个服务对象,在需要时由容器实例化,并且通常在 web 应用程序的整个生命周期内保持活动状态。它通常响应来自多个客户端(和会话)的请求,甚至是并发请求。这就是为什么您的 servlet 代码必须是线程安全的,并且您永远不要在 servlet 字段中存储一些与请求或会话相关的数据。
回答by babu
A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet
servlet 生命周期可以定义为从创建到销毁的整个过程。以下是servlet后的路径
- The servlet is initialized by calling the init () method.
- The servlet calls service() method to process a client's request.
- The servlet is terminated by calling the destroy() method.
- Finally, servlet is garbage collected by the garbage collector of the JVM.
- servlet 通过调用 init() 方法进行初始化。
- servlet 调用 service() 方法来处理客户端的请求。
- servlet 通过调用 destroy() 方法终止。
- 最后,servlet 由 JVM 的垃圾收集器进行垃圾收集。
More here ..
更多在这里..
http://www.dzone.com/links/r/java_ee_servlets_life_cycle.html
http://www.dzone.com/links/r/java_ee_servlets_life_cycle.html
回答by Ajay Takur
The servlet (its one and only instance) will handle n number of request in the fashion of separate single thread for every client ie where CGI limitation is overcomed
servlet(它的唯一实例)将以单独的单线程方式为每个客户端处理 n 个请求,即克服 CGI 限制
A servlet object lives in heap of serverside machine as long as application is undeployed or servletConatiner is shutdown the servlet object will not die.
只要应用程序未部署或 servletConatiner 关闭,servlet 对象就存在于服务器端机器的堆中,servlet 对象不会死亡。
Technically : servletcontainer holds servletobject and servletobject holds servletConfig object
技术上:servletcontainer 持有 servletobject 和 servletobject 持有 servletConfig 对象
Servletcontainer can only call the 3 methods of its life cycle 1)init() 2)service() 3)destroy()
Servletcontainer 只能调用其生命周期的 3 个方法 1)init() 2)service() 3)destroy()
回答by fasseg
when i remember correctly servlets live as Singletonsin the Servlet Container (e.g. Tomcat). Im not sure if the first instantiation is lazy, meaning that the Servlet gets constructed only if needed, but im guessing one could check this in the corresponding Servlet Container's Classloader sources.
The Servlet's lifecycle ends and it's destroy()
method gets called when the Servlet Container is shut down.
You can check this easily by setting up breakpoints or logging in the appropriate init()
and destroy()
methods and Constructor then just check when the code gets executed in your debugger/logfile.
当我记得正确时,servlet在 Servlet 容器(例如 Tomcat)中作为单例存在。我不确定第一个实例化是否是惰性的,这意味着仅在需要时才构造 Servlet,但我猜可以在相应的 Servlet 容器的类加载器源中检查这一点。Servlet 的生命周期结束,它的destroy()
方法在 Servlet 容器关闭时被调用。您可以通过设置断点或在相应的日志记录轻松地检查这个init()
和destroy()
方法,当代码在调试器/日志文件被执行构造函数,然后只检查。
hope that helped.
希望有所帮助。
References: Tomcat's Classloader howto
回答by Bat0u89
Actually the Servlet may be destroyed and recreated at any time ! So the other answers kinda describe the whole lifecycle but miss this important detail. From the servlet specification:
实际上,Servlet 可能随时被销毁和重新创建!所以其他答案有点描述了整个生命周期,但错过了这个重要的细节。从 servlet 规范:
The servlet container is not required to keep a servlet loaded for any particular period of time. A servlet instance may be kept active in a servlet container for a period of milliseconds, for the lifetime of the servlet container (which could be a number of days, months, or years), or any amount of time in between.
servlet 容器不需要在任何特定时间段内保持 servlet 加载。一个 servlet 实例可以在一个 servlet 容器中保持活动状态数毫秒,在 servlet 容器的生命周期内(可能是数天、数月或数年),或者两者之间的任何时间量。
[...]
[...]
Once the destroy method is called on a servlet instance, the container may not route other requests to that instance of the servlet. If the container needs to enable the servlet again, it must do so with a new instance of the servlet's class.
一旦在 servlet 实例上调用 destroy 方法,容器可能不会将其他请求路由到该 servlet 实例。如果容器需要再次启用 servlet,它必须使用 servlet 类的新实例来执行此操作。
回答by Ritesh Kumar
The servlet's container is attached to a web server that listens for HTTP or HTTPS requests on a certain port number (port 8080 is usually used during development and port 80 in production). When a client (user with a web browser) sends an HTTP request, the servlet container creates new HttpServletRequest
and HttpServletResponse
objects (for every new request) and passes them through any defined Filter chain and, eventually, the Servlet instance.
servlet 的容器附加到 Web 服务器上,该服务器在特定端口号(通常在开发过程中使用端口 8080,在生产过程中使用端口 80)上侦听 HTTP 或 HTTPS 请求。当客户端(具有 Web 浏览器的用户)发送 HTTP 请求时,servlet 容器创建新的HttpServletRequest
和HttpServletResponse
对象(针对每个新请求)并将它们传递给任何定义的过滤器链,最终传递给 Servlet 实例。
In the case of filters, the doFilter()
method is invoked. When its code calls chain.doFilter(request, response)
, the request and response continue on to the next filter, or hit the servlet if there are no remaining filters.
在过滤器的情况下,doFilter()
调用该方法。当它的代码调用 时chain.doFilter(request, response)
,请求和响应继续到下一个过滤器,或者如果没有剩余的过滤器,则命中 servlet。
In the case of servlets, the service()
method is invoked(by multiple threads for different request). By default, this method determines which one of the doXxx()
methods to invoke based off of request.getMethod()
. If the determined method is absent from the servlet, then an HTTP 405 error is returned in the response.
在 servlet 的情况下,该service()
方法被调用(由多个线程针对不同的请求)。默认情况下,此方法根据 确定doXxx()
要调用的方法之一 request.getMethod()
。如果 servlet 中不存在确定的方法,则响应中将返回 HTTP 405 错误。
The request object provides access to all of the information about the HTTP request, such as its headers and body. The response object provides the ability to control and send the HTTP response the way you want by, for instance, allowing you to set the headers and the body (usually with generated HTML content from a JSP file). When the HTTP response is committed and finished, both the request and response objects are recycled and made for reuse.
request 对象提供对有关 HTTP 请求的所有信息的访问,例如其标头和正文。响应对象提供了以您想要的方式控制和发送 HTTP 响应的能力,例如,允许您设置标题和正文(通常使用从 JSP 文件生成的 HTML 内容)。当 HTTP 响应提交并完成时,请求和响应对象都会被回收并重新使用。
回答by 15412s
The lifecycle of a typical servlet running on Tomcat might look something like this:
在 Tomcat 上运行的典型 servlet 的生命周期可能如下所示:
1.Tomcat receives a request from a client through one of its connectors.
1.Tomcat 通过其连接器之一接收来自客户端的请求。
2.Tomcat maps this request to the appropriate Engine for processing. These Engines are contained within other elements, such as Hosts and Servers, which limit the scope of Tomcat's search for the correct Engine.
2.Tomcat将这个请求映射到合适的Engine进行处理。这些引擎包含在其他元素中,例如主机和服务器,它们限制了 Tomcat 搜索正确引擎的范围。
3.Once the request has been mapped to the appropriate servlet, Tomcat checks to see if that servlet class has been loaded. If it has not, Tomcat compiles the servlet into Java bytecode, which is executable by the JVM, and creates an instance of the servlet.
3. 一旦请求被映射到适当的 servlet,Tomcat 就会检查该 servlet 类是否已加载。如果没有,Tomcat 将 servlet 编译成可由 JVM 执行的 Java 字节码,并创建 servlet 的一个实例。
4.Tomcat initializes the servlet by calling its init method. The servlet includes code that is able to read Tomcat configuration files and act accordingly, as well as declare any resources it might need, so that Tomcat can create them in an orderly, managed fashion.
4.Tomcat通过调用它的init方法来初始化servlet。servlet 包含能够读取 Tomcat 配置文件并进行相应操作以及声明它可能需要的任何资源的代码,以便 Tomcat 能够以有序、受管的方式创建它们。
5.Once the servlet has been initialized, Tomcat can call the servlet's service method to process the request, which will be returned as a response.
5.一旦servlet被初始化,Tomcat就可以调用servlet的service方法来处理请求,该请求将作为响应返回。
6.During the servlet's lifecycle, Tomcat and the servlet can communicate through the use of listener classes, which monitor the servlet for a variety of state changes. Tomcat can retrieve and store these state changes in a variety of ways, and allow other servlets access to them, allowing state to be maintained and accessed by various components of a given context across the span of a single or multiple user sessions. An example of this functionality in action is an e-commerce application that remembers what the user has added to their cart and is able to pass this data to a checkout process.
6.在servlet的生命周期中,Tomcat和servlet之间可以通过监听类进行通信,监听类监听servlet的各种状态变化。Tomcat 可以通过多种方式检索和存储这些状态更改,并允许其他 servlet 访问它们,从而允许跨单个或多个用户会话的跨度给定上下文的各种组件维护和访问状态。此功能的一个示例是电子商务应用程序,它记住用户添加到购物车中的内容,并能够将此数据传递给结帐流程。
7.Tomcat calls the servlet's destroy method to smoothly remove the servlet. This action is triggered either by a state change that is being listened for, or by an external command delivered to Tomcat to undeploy the servlet's Context or shut down the server.
7.Tomcat调用servlet的destroy方法顺利删除servlet。此操作由正在侦听的状态更改触发,或者由传递给 Tomcat 以取消部署 servlet 的上下文或关闭服务器的外部命令触发。
Reference:
参考: