0%

嵌入式Tomcat

文章字数:207,阅读全文大约需要1分钟

嵌入式调用

  • Tomcat7RunnerCli引导类
  • 嵌入式tomcat的启动依赖于Tomcat7Runner调用Tomcat api
  • org.apache.catalina.startup.Tomcatapi,用于嵌入式启动

手写嵌入式Tomcat

  • 新建Tomcat对象
  • 设置端口
  • 设置Context目录
  • 添加Servlet
  • 调用Tomcat.start()
  • 强制Tomcat等待
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args) {
String classpath = System.getProperty("user.dir");//目录绝对路径
Tomcat tomcat = new Tomcat();
tomcat.setPort(9090); // 端口绑定,也可以使用tomcat.getConnector().serPort(9091);
Host host = tomcat.getHost(); // 设置Host
host.setName("localhost"); // 和xml设置一样
host.setAppBase("webapps"); // 根据xml设置

// --- 基础配置完成
// 加载class,加入 启动工程
Context context = tomcat.addContext(host, "/", "classpath ");
if(context instanceof StandardContext) {
StandardContext standardContext = (StandardContext)context;
context .setDefaultContextXml("d:/tomcat/conf/web.xml");
// wrapper 是Servlet的基本单元
Wrapper wrapper = tomcat.addServlet("/", "DemoServler", new DemoServlet);
wrapper.addMapping("/demo.do");
}
// --- 启动
tomcat.start(); // 启动
tomcat.getServer().await(); // server等待,防止main运行完直接结束
}