tomcat6.0的嵌入


import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Embedded;

public class TomcatServer {

	private String catalinaHome = "C:/Program Files/Apache Software Foundation/Tomcat 6.0";
	
	private static TomcatServer instance = new TomcatServer();
	
	public static TomcatServer getInstance()
	{
		return instance;
	}
	
	private Embedded tomcat;
	public void start()
	{
		tomcat = createEmbed();
		try {
			tomcat.start();
		} catch (LifecycleException e) {
			e.printStackTrace();
		}
	}
	
	public void stop()
	{
		try {
			tomcat.stop();
		} catch (LifecycleException e) {
			e.printStackTrace();
		}
	}
	
	private Embedded createEmbed()
	{
		/**
		 * Server
		 *    service
		 *       connector
		 *       Engine
		 *         Host
		 *           context
		 */
		Embedded embed = new Embedded();
		embed.setCatalinaHome(catalinaHome);
		Engine engine = embed.createEngine();
//		engine.
//		embed.se
		engine.setDefaultHost("localhost");
		System.out.println(embed.getCatalinaBase());
		System.out.println(embed.getCatalinaHome());
//		Host host = embed.createHost("localhost", embed.getCatalinaHome()+"/webapps");
		Host host = embed.createHost("localhost", catalinaHome+"/webapps");
		//添加虚拟主机
		engine.addChild(host);
		
		Context context = embed.createContext("/axis", catalinaHome+"/webapps/axis");
		host.addChild(context);
		embed.addEngine(engine);
		Connector conn = embed.createConnector("127.0.0.1", 8088, false);

		embed.addConnector(conn);
		
		return embed;
	}
	
	public static void main(String []args)
	{
		TomcatServer.getInstance().start();
		
		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				super.run();
				TomcatServer.getInstance().stop();
			}
		});
	}
}

你可能感兴趣的:(embed tomcat)