Sunday, January 13, 2008

Embedding Jetty 6 in Spring

There’s not much info out there on embedding a Jetty server in Spring, and much of what does exist is for Jetty 5 (not Jetty 6) or uses helper classes that nobody wants to write. However, there is a decent example hidden in the Jetty Subversion repository (which requires an exploded WAR directory structure), and the Jetty documentation is pretty nice. The API docs are useful, as well.

I had two goals: embed Jetty 6 (not 5), and do so without having to rearrange my directories into an exploded WAR structure. After a bit of tinkering, this is the file I ended up with. It contains 5 servlets and their mappings, just so that you can get a feel for the file, but you can certainly use it with any number of servlets.

Note that I had to change the file extension from .xml to .txt in order to appease my blogging software… Note also that this setup does not require the exploded WAR directory structure. The parts you’ll probably want to customize are the servlets list, the servletMappings list, the resourceBase property, and possibly the contextPath property.

1 comment:

B.J. said...

Nice writeup, but your example suffers from the same issue I've found in other samples -- namely that your entire spring application must be defined in the context file you pass to the dispatcher servlet. There appears no way to have embedded Jetty 6 start with a web app context that has the application context in which the jetty server is loaded be the parent context of the web app contexts used by the servlets. I haven't been able to find any way of making this work, but my knowledge of Jetty and Spring are slim.