Причал: динамически удаляя зарегистрированный сервлет - PullRequest
5 голосов
/ 01 марта 2011

Я создал и запустил джет-сервер с WebAppContext. Я также могу добавить сервлет в WebAppContext с помощью метода addServlet. Но я хочу динамически удалить этот сервлет. Как я могу это сделать ? Что-то вроде removeServlet () не предусмотрено в WebAppContext.

1 Ответ

22 голосов
/ 03 марта 2011

Вам нужно сделать это вручную (вероятно, должен быть удобный метод, но его нет)

В Jetty 7 это будет что-то вроде ( не проверено ):

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

}
...