Fork me on GitHub

嵌入式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());
        }
    }
    
    
}

 

posted @ 2014-11-21 20:51  何海洋  阅读(1853)  评论(1编辑  收藏  举报