配置简单的嵌入式tomcat

2019-07-12 20:36发布

  • http://tomcat.apache.org/download-80.cgi下载Binary Distributions的Embedded包
  • Eclipse创建Web项目,在src建立lib目录,将下载的embedded包里面的jar文件解压到lib目录
  • 设置项目属性,在Java Build Path选择Libraries标签页,将Web项目的Apache Tomcat Server包去掉,增加上面lib目录中的jar文件
  • 新建一个含有main方法的可执行类(此类的编写参考了Aleksa Vukotic James Goodwill写的<>CHAPTER9 Embedding Tomcat).
package com.sysware.testflex3.app; import java.io.File; import org.apache.catalina.LifecycleException; import org.apache.catalina.core.AprLifecycleListener; import org.apache.catalina.core.StandardServer; import org.apache.catalina.startup.ClassLoaderFactory; import org.apache.catalina.startup.Tomcat; import javax.servlet.ServletException; /** * Created by nil on 2014/8/1. */ public class EmbeddedTomcat { private Tomcat tomcat; private void startTomcat(int port, String contextPath, String baseDir) throws ServletException, LifecycleException { tomcat = new Tomcat(); tomcat.setPort(port); tomcat.setBaseDir("."); StandardServer server = (StandardServer) tomcat.getServer(); AprLifecycleListener listener = new AprLifecycleListener(); server.addLifecycleListener(listener); tomcat.addWebapp(contextPath, baseDir); tomcat.start(); } private void stopTomcat() throws LifecycleException { tomcat.stop(); } public static void main(String[] args) { try { int port = 8080; String contextPath = "/testflex3"; String baseDir = new File("WebContent").getAbsolutePath(); // 项目中web目录名称,以前版本为WebRoot、webapp、webapps,现在为WebContent EmbeddedTomcat tomcat = new EmbeddedTomcat(); tomcat.startTomcat(port, contextPath, baseDir); // 由于Tomcat的start方法为非阻塞方法,加一个线程睡眠模拟线程阻塞. Thread.sleep(10000000); } catch (Exception e) { e.printStackTrace(); } } }
  • 按照正常web项目完成相关内容。
  • 以Java Application方式运行EmbeddedTomcat类。
  • 如果提示No global web.xml found不用管。