Jetty: dynamically deleting a registered servlet

I created and started the console server using WebAppContext. I can also add a servlet to WebAppContext using the addServlet method. But I want to dynamically delete this servlet. How can i do this? Something like removeServlet () is not provided in WebAppContext.

+4
source share
1 answer

You need to do this manually (there probably should be a convenience method, but it doesn't exist)

In Jetty 7, it will be something like (untested):

public void removeServlets(WebAppContext webAppContext, Class<?> servlet) { ServletHandler handler = webAppContext.getServletHandler(); /* A list of all the servlets that don't implement the class 'servlet', (ie They should be kept in the context */ List<ServletHolder> servlets = new ArrayList<ServletHolder>(); /* The names all the servlets that we remove so we can drop the mappings too */ Set<String> names = new HashSet<String>(); for( ServletHolder holder : handler.getServlets() ) { /* If it is the class we want to remove, then just keep track of its name */ if(servlet.isInstance(holder.getServlet())) { names.add(holder.getName()); } else /* We keep it */ { servlets.add(holder); } } List<ServletMapping> mappings = new ArrayList<ServletMapping>(); for( ServletMapping mapping : handler.getServletMappings() ) { /* Only keep the mappings that didn't point to one of the servlets we removed */ if(!names.contains(mapping.getServletName())) { mappings.add(mapping); } } /* Set the new configuration for the mappings and the servlets */ handler.setServletMappings( mappings.toArray(new ServletMapping[0]) ); handler.setServlets( servlets.toArray(new ServletHolder[0]) ); } 
+19
source

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


All Articles