1). 创建Java项目Tomcat
2). 创建Servlet接口
public interface IServlet {
public void service();
}
3). 创建Tomcat核心主类
public class Core {
@SuppressWarnings("resource")
public static void main(String[] args) throws Exception {
// 打印初始化
System.out.println("Tomcat: Hello! I'm Tomcat, and I'm in the initialization...");
// 睡眠3秒
Thread.sleep(3000);
// 初始化完成
System.out.println("Tomcat: Now, I have finished the initializaion.");
// 睡眠1秒
Thread.sleep(1000);
// 启动
System.out.println("Tomcat: Now I will start the Servlet.");
// 读取配置文件,获取Servlet的项目路径名及类包名路径名
FileReader reader = new FileReader("./TomcatConf.txt");
// 创建缓冲读取
BufferedReader bReader = new BufferedReader(reader);
// 读取路径
String path = bReader.readLine();
// 读取类名
String className = bReader.readLine();
// 关闭Reader
bReader.close();
reader.close();
// 根据已读取的Servlet项目路径名及类包路径名通过URL加载器加载文件系统中的某个.class文件
File file = new File(path);
// 这里读取文件系统的URL地址
URL url = file.toURI().toURL();
// 创建持有我们所部署的Web项目路径的URL类加载器,以使Tomcat之外的Web纳入Tomcat的classpath之中
URLClassLoader loader = new URLClassLoader(new URL[]{url});
// 利用反射加载类
Class<?> clazz = loader.loadClass(className);
// 转换为Servlet接口执行Service操作
IServlet servlet = (IServlet) clazz.newInstance();
// 实际的Tomcat并不在这里调用Service,仅仅是在进入事件循环,在有浏览器请求时才调用Service
servlet.service();
}
}
4). 将Tomcat项目导出为Jar包
项目右键->Export...->Java->JAR file->Finish.
5). 再创建一个Java项目,并引入tomcat.jar
6). 创建DaoOperator
/**
* 模拟数据库操作
* @author mazaiting
*/
public class DaoOperator {
private String name;
public DaoOperator(String name) {
this.name = name;
}
public void operate() throws InterruptedException {
System.out.println("I will do much work...");
Thread.sleep(3000);
System.out.println(name + " DAOOperator exec succeed.");
}
}
7). 创建Servlet
public class MyServlet implements IServlet {
@Override
public void service() {
System.out.println("Hello, I'm the Servlet.");
System.out.println("Now let's start our web http travel.");
try {
Thread.sleep(3000);
DaoOperator dao = new DaoOperator("MySql");
dao.operate();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Now I will beleave the web world..");;
System.out.println("Bye-bye.");
}
}
8). 在项目的根目录下创建TomcatConf.txt配置文件
文件内容:
E:\Java\test\MyWeb\bin
com.mazaiting.MyServlet