1. 创建一个LifeCycle的Web工程
2. 在WebContent下创建一个index.html
3. 编写index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Life Cycle</title>
</head>
<body>
<h1>Life Cycle</h1>
</body>
</html>
4. 创建LifeCycle.java
5. 编写LifeCycle.java
package com.lywgames.myservlet;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class LifeCycle implements Servlet {
public LifeCycle() {
System.out.println("LifeCycle");
}
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("init");
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("service");
}
@Override
public void destroy() {
System.out.println("destroy");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public String getServletInfo() {
return null;
}
}
6. 在web.xml里配置servlet
7. 在浏览器地址栏输入:http://localhost:8080/LifeCycle/LC.action运行几次
8. Servlet的生命周期: 从创建到销毁的一段时间。
9. Servlet生命周期方法: 从创建到销毁, 所调用的那些方法。主要有: 构造方法、init()、service()和destroy()。
10. init方法: 在创建该servlet的实例时, 就执行该方法。一个servlet只会初始化一次, init方法只会执行一次。默认情况下是: 初次访问该servlet, 才会创建实例。
11. service方法: 只要客户端来了一个请求, 那么就执行这个方法了。该方法可以被执行很多次。一次请求, 对应一次service方法的调用。
12. destroy方法: servlet销毁的时候, 就会执行该方法。
12.1. 该项目从tomcat的里面移除。
12.2. 正常关闭tomcat就会执行shutdown.bat。
12.3. Eclipse里面stop the server。