There’s no law which states web servers and servlet containers must be large, separate pieces of software. If there were, Jetty would be a dangerous outlaw (possibly even public enemy number one). Jetty is an open-source embeddable web server and servlet container, written in Java. It’s small, fast, and easy to embed — perfect for self-contained applications.
Let’s use an example to discover just how easy embedding Jetty can be. Say we have two servlets, one should be mapped to /service/one and the other /service/two, served on port 8080.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Server server = new Server(); Connector connector = new SelectChannelConnector(); connector.setPort(8080); server.addConnector(connector); ContextHandlerCollection contexts = new ContextHandlerCollection(); server.setHandler(contexts); Context context = new Context(contexts, "/service"); context.addServlet(ServiceOne.class, "/one"); context.addServlet(ServiceTwo.class, "/two"); server.start(); server.join(); |
That’s it; easy. For information and more examples on embedding Jetty in your Java application, read Embedding Jetty.



Thanks for this little blogpost. I was just thinking about how it would be simpler to embed then server in my application instead of wasting time converting it to a war, etc. A quick download and 10 lines later I have a simple GUI via a servlet !
Awesome! Now I just have to figure out how to adapt this for jetty7.
C:
Best of luck to you, lunarcloud. I tried that myself a couple months ago and eventually gave up. Too much had changed with too little documentation. If you manage it, though, let us all know!
Mike, Do you have any code for dispatching a response from the handling servlet to a jsp page to render some html. I can get the servlet to work but running my app in eclipse, jetty cannot seem to find the jsp.
@fuzzer No, sorry, I’ve never had to do that.