I'm trying to get started with an embedded Jetty server. I just want to map requests to different servlets based on the request path.
What's the difference between creating a ServletHandler
and adding servlets to it as opposed to creating a ServletContextHandler
and adding servlets to that?
For example:
//how is this different...
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(MyServlet.class, "/path");
//from this?
ServletContextHandler contextHandler = new ServletContextHandler();
contextHandler.addServlet(MyServlet.class, "/path");
Most Servlet's require a javax.servlet.ServletContext
object to operate properly.
Using a ServletContextHandler
will create and manage the common ServletContext for all of the Servlets, Filters, Sessions, Security, etc within that ServletContextHandler
. This includes proper initialization, load order, and destruction of the components affected by a ServletContext
as well.
Also note, that ServletHandler
is considered an internal class of ServletContextHandler
and is not meant to be used "in the raw" like that with Jetty. While it is technically possible, it is discouraged for all but the most naive and simplistic implementations of a Servlet.