Tuesday November 14, 2006

Embedding Jetty

If you have the requirement to run a web application within your application, you should check out Jetty 6.

I came across this requirement in my new part-time gig, where I support a small software development company in Stuttgart in creating a new release of their Servicemix-based product. While Servicemix provides a perfect solution to distribute the software components transparently, essential parts of the application runs within web applications.

Jetty 6 is a fully JEE 1.4 compliant servlet and JSP container and has been designed with embeddability in mind. Many software packages depend on Jetty and it is relatively easy to get it up and running, but the devil is in the details. So, I put together some of my code snippets.

1. We create the server and a connector, which listens for requests. We had some problems with the NIO connector, so we went with the BIO SocketConnector.

org.mortbay.jetty.Server server = new Server();
org.mortbay.jetty.bio.SocketConnector connector = new SocketConnector();
connector.setPort(8080);
server.setConnector(connector)
server.setStopAtShutdown(true);

2. After that we have to setup the handlers for the web applications.

HandlerCollection handlers = new HandlerCollection();
ContextHandlerCollection contexts = new ContextHandlerCollection();
handlers.setHandlers(new Handler[] { contexts });
server.setHandler(handlers);

3. Then we have to initialize our the web application (including a temporary work directory) and add it to the server’s context handlers:

String warName = "webappName";
WebAppContext wac = new WebAppContext();
wac.setContextPath("/" + warName);
wac.setExtractWAR(true);
File workDir = new File(new File("c:\tmp\workdir"), warName);
workDir.mkdirs();
wac.setPreserveExtractedWebAppDir(true);
wac.setTempDirectory(workDir);
wac.setWar(warFile.getCanonicalPath());
contexts.addHandler(wac);

4. What’s left? We have to start the server…

server.start();

This is taken from an actually working example. More information about the required JARs can be found here.

Posted on Nov 14, 2006 at 22:30 (MET) | Permalink | Add comment