文章来源:http://tutorials.jenkov.com/java-servlets/overview.html
1、一个 java servlet 是一个java 对象,这个对象响应HTTP多个请求,它运行在一个Servlet 容器里,这是一个例子.
Servlets inside a Java Servlet Container
2、一个servlet 是 一个java web 应用的一部分。一个servlet 容器可以在同时运行多个web 应用。
Web applications with multiple servlets inside a Java Servlet container
一个java web 应用除了servlets,能包含其它的组件,如jsp,jsf和web Services。
HTTP Request and Response
3、servlet 生命周期
servlet 容器管理 servlet 生命周期,生命周期包含下面步骤:
- Load Servlet Class
- Create Instance of Servlet:建立servlet 实例,应该已经初始化类的数据。
- Call the servlets
init()
method. //有什么用? - Call the servlets
service()
method. //应该处理浏览器请求。 - Call the servlets
destroy()
method.
Step 1, 2 and 3 are executed only once:
You can force the container to load the servlet when the container starts up . See web.xml Servlet Configuration for more details about that.
Step 4 is executed multiple times - 每一个http对servlet请求一次。
Step 5 is executed when the servlet container unloads the servlet.
Load Servlet Class
Before a servlet can be invoked the servlet container must first load its class definition. This is done just like any other class is loaded.
Create Instance of Servlet:仅仅建立,未初始化数据
When the servlet class is loaded, the servlet container creates an instance of the servlet.
Typically, only a single isntance of the servlet is created, and concurrent requests to the servlet are executed on the same servlet instance. This is really up to the servlet container to decide, though. But typically, there is just one instance.
Call the Servlets init() Method:允许初始化对象。
When a servlet instance is created, its init()
method is invoked. The init()
method allows a servlet to initialize itself before the first request is processed.
You can specify init parameters to the servlet in the web.xml file. See web.xml Servlet Configuration for more details.
Call the Servlets service() Method
As long as the servlet is active in the servlet container, the service()
method can be called. Thus, this step in the life cycle can be executed multiple times.
Call the Servlets destroy() Method
When a servlet is unloaded by the servlet container, its destroy()
method is called. This step is only executed once, since a servlet is only unloaded once.
A servlet is unloaded by the container if the container shuts down, or if the container reloads the whole web application at runtime.
总结:浏览器一个http请求----------到达tomact,tomcat 一看是servlet----去配置文件找对应servlet---然后把servlet对象装入内存-