Jetty : Dynamically removing the registered servlet

ε祈祈猫儿з 提交于 2019-12-30 06:45:10

问题


I created and started jetty server with WebAppContext. I can also add servlet to the WebAppContext with addServlet method. But I want to dynamically remove this servlet. How can I do this ? Something like removeServlet() is not provided in the WebAppContext.


回答1:


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

In Jetty 7 it would 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',
      (i.e. 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]) );

}


来源:https://stackoverflow.com/questions/5150730/jetty-dynamically-removing-the-registered-servlet

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