Embedding Jetty

Jetty is a lightweight open source Java-based HTTP Server and Servlet container. Jetty’s small footprint makes it perfect for embedding into larger Java applications, in fact Jetty is used by the likes of Jboss Application Server and Apache Geronimo.

Embedding Jetty is extremely easy. For the most part you just create a new instance of a Jetty server, indicate where the server can find the resource files, such as HTML/PNG files, maybe add a Web Application Resource (WAR), and start the server. Here is the code step by step, of course the following code assumes you have added the required jars.

[source:java]
Server server = new Server(8080);
[/source]

The above creates an instance of the Jetty server (org.mortbay.jetty.Server) listening at port 8080, but does not start the server. At this point we would need to add a default resource handler with the location of the directory which contains the public HTML, JPG, JS, and additional files which will can be requested by clients.

[source:java]
ResourceHandler publicDocs = new ResourceHandler();
publicDocs.setResourceBase(“c:/path/to/public/docs”);
[/source]

I would also like to add support for a Java-based web application.

[source:java]
String webappPath = “c:/path/to/webapp.war”;
String contextPath = “/webapp”;
WebAppContext webapp = new WebAppContext(webappPath, contextPath);
[/source]

Now I need to add the public resource and web application handlers to the Jetty server.

[source:java]
HandlerList hl = new HandlerList();
hl.setHandlers(new Handler[]{publicDocs, webapp});
server.setHandler(hl);
[/source]

At this point, you can start the server simply by calling the start method.

[source:java]
sever.start();
[/source]

Once you have the above code up and running point your browser to http://localhost:8080 to connect to the Jetty server, of course you would need some index.html in the public docs directory. In this example, if where to connect to the web application described here you can do so by directing your browser to http://localhost:8080/wepapp.

Technorati Tags: , , , , , , , ,