Servlet Life Cycle

A servlet follows a certain life cycle. The servlet life cycle is managed by the servlet container. The life cycle contains the following steps:

  • Load Servlet Class.
  • Create Instance of 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, when the servlet is initially loaded. By default the servlet is not loaded until the first request is received for it. You can force the container to load the servlet when the container starts up though.

Step 4 is executed multiple times - once for every HTTP request to the servlet.
Step 5 is executed when the servlet container unloads the servlet.
Each step is described in more detail below:
The Java Servlet life cycle

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.

Call the Servlets service() Method

For every request received to the servlet, the servlets service() method is called. For HttpServlet subclasses, one of the doGet(), doPost() etc. methods are typically called.

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值