Jetty:动态删除已注册的servlet

nat*_*ttu 5 jetty embedded-jetty

我使用WebAppContext创建并启动了jetty服务器.我还可以使用addServlet方法将servlet添加到WebAppContext.但是我想动态删除这个servlet.我怎样才能做到这一点 ?WebAppContext中未提供类似removeServlet()的内容.

Tim*_*Tim 22

你需要手动完成(可能应该有一个方便的方法,但没有)

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

}
Run Code Online (Sandbox Code Playgroud)

  • 没问题 - 但如果你喜欢这个答案,你应该点击答案(在答案的右上角),将其标记为你接受的答案.这是对堆栈溢出说"谢谢"的最佳方式. (3认同)
  • 嘿蒂姆.虽然这个解决方案有效,但我想知道这里正在进行的servlet的重新映射.这个代码是否碰巧在每次调用时都重新设置所有servlet?如果服务器将所有servlet向下移动只是为了移除其中一个并将其余部分备份,这似乎很麻烦.如果我是正确的话,这可能会导致竞争条件. (2认同)