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

请您参考如下方法:

您需要手动执行(可能应该有一个方便的方法,但没有)

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


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!