I just had to write some code for running a single servlet for testing and wrote this java program which uses Embedded tomcat.
The following code doesn't use web.xml to configure the context. Context configuration is done programmatically using the StandardContext class in catalina.jar. I have added a servlet and mapped it to the URL "/example".
System.setProperty("catalina.home", "./");
Embedded embedded = new Embedded();
Engine engine = null;
Host host = null;
// Create an embedded server
embedded = new Embedded();
// print all log statments to standard error
embedded.setDebug(0);
embedded.setLogger(new SystemOutLogger());
// Create an engine
engine = embedded.createEngine();
engine.setDefaultHost("localhost");
// Create a default virtual host
host = embedded.createHost("localhost", "./");
engine.addChild(host);
StandardContext context = (StandardContext) embedded.createContext("/ContextPath","/test");
context.setWorkDir("./test");
context.setConfigured(true);
Wrapper servlet = context.createWrapper();
servlet.setServletClass(ExampleServlet.class.getName());
servlet.setName("example");
context.addChild(servlet);
context.addServletMapping("/example", "example");
host.addChild(context);
host.setAutoDeploy(true);
// Install the assembled container hierarchy
embedded.addEngine(engine);
// Assemble and install a default HTTP connector
Connector connector = embedded.createConnector("127.0.0.1", 8080,
false);
embedded.addConnector(connector);
// Start the embedded server
embedded.start()
This may help while writing unit tests for servlets which cannot be tested with cactus or httpUnit.
Happy coding...