首页 > 代码库 > 嵌入式Tomcat Web服务器的使用
嵌入式Tomcat Web服务器的使用
在运行web工程时,常常要频繁启动tomcat,使用嵌入式tomcat可以减少部分重复操作。
1、下载tomcat5.0.28embed.zip 解压文件夹复制到工程下。
http://archive.apache.org/dist/tomcat/tomcat-5/v5.0.28/bin/jakarta-tomcat-5.0.28-embed.zip
2、源码实现
import java.io.File;import javax.servlet.ServletException;import org.apache.catalina.LifecycleException;import org.apache.catalina.core.AprLifecycleListener;import org.apache.catalina.core.StandardServer;import org.apache.catalina.startup.Tomcat;import org.apache.juli.logging.Log;import org.apache.juli.logging.LogFactory;public class WebStart { private final Log log = LogFactory.getLog(getClass()); private static String CONTEXT_PATH = ""; private static String PROJECT_PATH = System.getProperty("user.dir");// 工程物理的绝对路径 private static String WEB_APP_PATH = PROJECT_PATH + File.separatorChar + "WebRoot"; private static String CATALINA_HOME = PROJECT_PATH + "/Embedded/Tomcat"; private Tomcat tomcat = new Tomcat(); private int port; public WebStart(int port) { this.port = port; } public void start(){ tomcat.setPort(port); tomcat.setBaseDir(CATALINA_HOME); tomcat.getHost().setAppBase(WEB_APP_PATH); try { StandardServer server = (StandardServer) tomcat.getServer(); AprLifecycleListener listener = new AprLifecycleListener(); server.addLifecycleListener(listener); tomcat.addWebapp(CONTEXT_PATH, WEB_APP_PATH); } catch (ServletException e) { e.printStackTrace(); log.error(e.getMessage()); } try { tomcat.start(); log.info("Tomcat started success !"); tomcat.getServer().await(); } catch (LifecycleException e) { e.printStackTrace(); log.error(e.getMessage()); } } public void stop(){ try { tomcat.stop(); log.info("Tomcat has stoped !"); } catch (LifecycleException e) { e.printStackTrace(); log.error(e.getMessage()); } } public void setPort(int port) { this.port = port; } public int getPort() { return this.port; } public static void main(String[] args){ WebStart tomcat = new WebStart(8080); try { tomcat.start(); } catch (Exception e) { System.out.println("Tomcat Start error !"+"\n"+e.toString()); } } }
嵌入式Tomcat Web服务器的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。