- Primeiramente, é necessário que você tenha o tomcat em mãos, caso não tenha pode baixar aqui:
A versão utilizada para este exemplo foi a 6.0.18.
- Crie um projeto java com o nome “tomcat6-embedded”.
- Extraia o arquivo para a pasta raiz do projeto e renomeie para tomcat6, ficando assim: “tomcat6-embedded /tomcat6”.
- Pelo eclipse, entre na pasta lib dentro de tomcat6, e adicione todos os jars no classpath.
Alem das libs do tomcat ainda precisamos de mais algums jars:
commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-logging-1.0.4.jar
commons-modeler-2.0.1.jar
commons-net-1.4.1.jar
juli-6.0.13.jar
log4j-1.2.14.jar
- Crie uma pasta lib dentro da pasta raiz do projeto, e coloque estes jars dentro dela, ficando assim: “tomcat6-embedded /lib” e adicione todos no classpath.
Caso não encontre estas bibliotecas, elas estarão junto com o arquivo do projeto que será disponibilizado para download.
Agora crie os pacotes e as classes de acordo com a imagem abaixo:

Com essa parte configurada, vamos para o código:
Arquivo Tomcat6.java
package br.com.server.embedded.service;
import java.net.InetAddress;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.Session;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.realm.MemoryRealm;
import org.apache.catalina.startup.Embedded;
import org.apache.tomcat.util.IntrospectionUtils;
public class Tomcat6 {
private String path = null;
private Embedded embedded = null;
private Host host = null;
private Context rootcontext;
private String welcomeFile;
private String contextName;
private String contextPath;
public Tomcat6() {
org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);
}
/**
* Set Session scope variable
*
* @param name Session variable name
* @param obj Session variable value
*/
public void setRootContextSessionAttribute(String name, Object obj) {
try {
Session sessions[] = this.rootcontext.getManager().findSessions();
for (int i = 0, size = sessions.length; i < size; i++) {
sessions[i].getSession().setAttribute(name, obj);
}
} catch (Exception x) {
}
}
/**
* Get Application scope variable
*
* @param name Application variable name
* @return Application variable value
*/
public Object getRootContextAttribute(String name) {
return this.rootcontext.getServletContext().getAttribute(name);
}
/**
* Set Application scope variable
*
* @param name Application variable name
* @param obj Application variable value
*/
public void setRootContextAttribute(String name, Object obj) {
this.rootcontext.getServletContext().setAttribute(name, obj);
}
/**
* Remove Application scope variable
*
* @param name Application variable name
*/
public void removeRootContextAttribute(String name) {
this.rootcontext.getServletContext().removeAttribute(name);
}
/**
* Basic Accessor setting the value of the context path
*
* @param path - the path
*/
public void setPath(String path) {
this.path = path;
}
/**
* Basic Accessor returning the value of the context path
*
* @return - the context path
*/
public String getPath() {
return this.path;
}
@SuppressWarnings("unused")
/**
* This method Starts the Tomcat server.
*/
public void start() {
try {
Engine engine = null;
// Create an embedded server
this.embedded = new Embedded();
this.embedded.setCatalinaHome(getPath());
// set the memory realm
MemoryRealm memRealm = new MemoryRealm();
this.embedded.setRealm(memRealm);
// Create an engine
engine = this.embedded.createEngine();
engine.setDefaultHost("localhost");
// Create a default virtual host
this.host = this.embedded.createHost("localhost", getPath()+ "/webapps");
engine.addChild(this.host);
// Create the ROOT context
this.rootcontext = this.embedded.createContext("", getPath() + "/webapps/ROOT");
this.rootcontext.setReloadable(false);
this.rootcontext.addWelcomeFile(getWelcomeFile());
this.host.addChild(this.rootcontext);
// create another application Context
Context appCtx = this.embedded.createContext("/"+getContextName(), getContextPath());
appCtx.setPrivileged(true);
this.host.addChild(appCtx); // add context to host
// Install the assembled container hierarchy
this.embedded.addEngine(engine);
int port = 8080;
String addr = null;
Connector connector = null;// this.embedded.createConnector(addr, port,
// false);
/*
* embedded.createConnector(...) seems to be broken.. it always returns
* a null connector. see work around below
*/
InetAddress address = null;
try {
connector = new Connector();
// httpConnector.setScheme("http");
connector.setSecure(false);
address = InetAddress.getLocalHost();
if (address != null) {
IntrospectionUtils.setProperty(connector, "address", "" + address);
}
IntrospectionUtils.setProperty(connector, "port", "" + port);
} catch (Exception ex) {
ex.printStackTrace();
}
connector.setEnableLookups(false);
this.embedded.addConnector(connector);
// Start the embedded server
this.embedded.start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Refresh ROOT context
*
*/
public void reloadRoot() {
this.rootcontext.reload();
}
/**
* Remove ROOT context
*
*/
public void removeRoot() {
this.host.removeChild(this.rootcontext);
}
/**
* Add ROOT context
*
*/
public void addRoot() {
this.host.addChild(this.rootcontext);
}
/**
* This method Stops the Tomcat server.
*/
public void stop() throws Exception {
this.embedded.stop();
}
/**
* Registers a WAR with the container.
*
* @param contextPath - the context path under which the application will be registered
* @param warFile - the URL of the WAR to be registered.
*/
public void registerWAR(String contextPath, String absolutePath) throws Exception {
Context context = this.embedded.createContext(contextPath, absolutePath);
context.setReloadable(false);
this.host.addChild(context);
}
/**
* Unregisters a WAR from the web server.
*
* @param contextPath
* - the context path to be removed
*/
public void unregisterWAR(String contextPath) throws Exception {
Context context = this.host.map(contextPath);
if (context != null) {
this.embedded.removeContext(context);
} else {
throw new Exception("Context does not exist for named path : " + contextPath);
}
}
public String getWelcomeFile() {
return welcomeFile;
}
public void setWelcomeFile(String welcomeFile) {
this.welcomeFile = welcomeFile;
}
public String getContextName() {
return contextName;
}
public void setContextName(String contextName) {
this.contextName = contextName;
}
public String getContextPath() {
return contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
}
Arquivo Main.java
package br.com.server.embedded.main;
import java.io.File;
import br.com.server.embedded.service.Tomcat6;
public class Main {
@SuppressWarnings("static-access")
public static void main(String[] args) {
Tomcat6 service = new Tomcat6();
// Seta o WelcomeFile
service.setWelcomeFile("index.jsp");
// Seta o nome do contexto do projeto
service.setContextName("wap");
// Seta o caminho do projeto
service.setContextPath("C:/wap");
// Seta o caminho do container web
service.setPath(new File("tomcat6").getAbsolutePath());
// Chama o método para iniciar o servidor web
service.start();
// Mantem a thread rodando por 24 horas
try {
Thread.currentThread().sleep(60 * 1000 * 60 * 24);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Bom, é isso ai.. qualquer dúvida estou a disposição.
Até+!