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

末鹿安然 提交于 2019-12-07 02:21:46

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/30733910/whats-the-difference-between-a-servlethandler-and-a-servletcontexthandler-in-je

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