Jetty makes for a very simple servlet container when testing or developing embedded web applications. It is quite capable and often satisfactory over alternatives such as JBoss or Tomcat. My favorite "feature" is that Jetty consists entirely of two JAR files, coming in at just under 700 KB.
The following code will set up a Jetty server with a basic HTTP connector open on port 8080. It prepares a single web application, located under the folder ./mywebapp, and exposes it on the context /mywebapp.
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;
public class ServerRunner {
public static void main(String[] arguments) throws Exception {
Server server = new Server();
Connector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
WebAppContext webappcontext = new WebAppContext();
webappcontext.setContextPath("/mywebapp");
webappcontext.setWar("mywebapp");
server.addHandler(webappcontext);
server.start();
server.join();
}
}
Other web applications can be added by calling server.addHandler() and passing more instances of WebAppContext.
When it is not convenient to load web application content from the file system, it can be loaded from the class path by replacing the setWar() call with:
This will load the web application from the com.earldouglas.web.mywebapp package, under which resides the usual WEB-INF/, web.xml, etc.