您现在的位置是:首页 > 文章详情

Java 手写Tomcat

日期:2018-06-05点击:564
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 
9). 运行tomcat.jar包
10). 控制台打印
img_a22ffa55ac129bf57c52d1a1c4461e1e.png
效果.png
原文链接:https://yq.aliyun.com/articles/663310
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章