码迷,mamicode.com
首页 > Web开发 > 详细

嵌入式Tomcat Web服务器的使用

时间:2014-11-21 21:42:45      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   使用   sp   

  在运行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服务器的使用

标签:style   blog   http   io   ar   color   os   使用   sp   

原文地址:http://www.cnblogs.com/hehaiyang/p/4113846.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!