Dropwizard : New admin resource

前端 未结 2 715
后悔当初
后悔当初 2021-02-20 09:53

I\'m using Drowpizard 0.7.1, but perhaps I will upgrade to 0.8.4 very soon.

Does anyone know how to add a admin resource to dropwizard, that is shown in Operational Menu

2条回答
  •  别跟我提以往
    2021-02-20 10:12

    Using .addMapping("") with Dropwizard version 0.9.1 allows you to override the menu without conflicting with the default AdminServlet mapping at "/*".

    In the Application:

    public void run(final NetworkModelApplicationConfiguration configuration, final Environment environment) {
        environment.admin().addServlet("my-admin-menu", new MyAdminServlet()).addMapping("");
        environment.admin().addServlet("my-admin-feature", new MyAdminFeatureServlet()).addMapping("/myAdminFeature");
    }
    

    Extending AdminServlet isn't very useful since all the properties are private. I built an HTTPServlet that reads a resource as a template:

    public class MyAdminServlet extends HttpServlet {
      private String serviceName;
    
      @Override
      public void init(ServletConfig config) throws ServletException {
        super.init(config);
        this.serviceName = config.getInitParameter("service-name");
      }
    
      @Override
      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getContextPath() + req.getServletPath();
        resp.setStatus(200);
        resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();
    
        try {
          String template = getResourceAsString("/admin.html", "UTF-8");
          String serviceName = this.serviceName == null?"":" (" + this.serviceName + ")";
    
          writer.println(MessageFormat.format(template, new Object[] { path, serviceName }));
        } finally {
          writer.close();
        }
      }
    
      String getResourceAsString(String resource, String charSet) throws IOException {
        InputStream in = this.getClass().getResourceAsStream(resource);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
          out.write(buffer, 0, len);
        }
        return out.toString(charSet);
      }
    }
    

    My /admin.html resource looks like this:

    
    
      
        
        Operational Menu{1}
      
      
        

    Operational Menu{1}

提交回复
热议问题