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 thatServletContextHandler
. This includes proper initialization, load order, and destruction of the components affected by aServletContext
as well.Also note, that
ServletHandler
is considered an internal class ofServletContextHandler
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.For Example you can create VirtualHosts with ServletContextHandler and you can management context easily. That means different context handlers on different ports.