What is the difference between ServletHandler and ServletContextHandler in Jetty?

I am trying to get started with the Jetty Embedded Server. I just want to display requests to different servlets based on the request path.

What is the difference between creating a ServletHandler and adding servlets to it, as opposed to creating a ServletContextHandler and adding servlets to it?

For instance:

 //how is this different... ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(MyServlet.class, "/path"); //from this? ServletContextHandler contextHandler = new ServletContextHandler(); contextHandler.addServlet(MyServlet.class, "/path"); 
+6
source share
2 answers

Most Servlet require javax.servlet.ServletContext to work properly.

Using ServletContextHandler will create and process a common ServletContext for all servlets, filters, sessions, security, etc. inside this ServletContextHandler . This includes proper initialization, loading order, and destruction of components affected by ServletContext .

Also note that the ServletHandler is considered to be the inner class of the ServletContextHandler and is not intended to be used in raw ServletHandler like Jetty. Although technically possible, it is discouraged by all but the most naive and simplified servlet implementations.

+5
source

For example, you can create VirtualHosts with a ServletContextHandler, and you can easily control the context. This 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); 
+2
source

Source: https://habr.com/ru/post/988787/


All Articles