What's the difference between a ServletHandler and a ServletContextHandler in Jetty?

16.8k views Asked by At

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");
2

There are 2 answers

2
Joakim Erdfelt On BEST ANSWER

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.

0
ceeleP On

For Example you can create VirtualHosts with ServletContextHandler and you can management context easily. That means different context handlers on different ports.

Server server = new Server();
ServerConnector pContext = new ServerConnector(server);
pContext.setPort(8080);
pContext.setName("Public");
ServerConnector localConn = new ServerConnector(server);
localConn.setPort(9090);
localConn.setName("Local");

ServletContextHandler publicContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
publicContext.setContextPath("/");
ServletHolder sh = new ServletHolder(new HttpServletDispatcher());  sh.setInitParameter("javax.ws.rs.Application", "ServiceListPublic");
publicContext.addServlet(sh, "/*");
publicContext.setVirtualHosts(new String[]{"@Public"});


ServletContextHandler localContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
localContext .setContextPath("/");
ServletHolder shl = new ServletHolder(new HttpServletDispatcher()); shl.setInitParameter("javax.ws.rs.Application", "ServiceListLocal");
localContext.addServlet(shl, "/*");
localContext.setVirtualHosts(new String[]{"@Local"}); //see localConn.SetName


HandlerCollection collection = new HandlerCollection();
collection.addHandler(publicContext);
collection.addHandler(localContext);
server.setHandler(collection);
server.addConnector(pContext);
server.addConnector(localContext);