Jetty: servlets vs handlers

In Jetty, Handlers handle requests that are coming through Connectors. One of the Handlers, specifically ServletHandler, allows Jetty to (mostly) support servlets. Servlet is a portable Java EE concept, so you can design your application in a more portable way if you use servlets in Jetty. On the other hand, they are likely to bring some overhead, so you might want to implement a Handler directly that would handle requests coming via Connectors.

If you are using servlets in Jetty, you can rely on the servlet security model, on the session support, etc. If this is unnecessary for your application, you might be better off implementing a very simple handler.


One interesting observation I found when played with it. I had a jetty-based application(dropwizard.io) and here I was planning to add handler after actual(there was special use-case for it)

server.start()

using org.eclipse.jetty.servlet.ServletContextHandler.insertHandler(HandlerWrapper handler) it just throws illegalStateException: STARTED if the server already started. Because of:

public void setHandler(Handler handler) {
        if (isStarted())
            throw new IllegalStateException(STARTED);
        //..

But in case of org.eclipse.jetty.servlet.ServletContextHandler.addServlet(ServletHolder servlet,String pathSpec) it will add your servlet to existing servlet collection and everything will work.