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

杀马特。学长 韩版系。学妹 提交于 2019-12-05 04:55:39

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.

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!