Can DropWizard serve assets from outside the jar file?

后端 未结 6 613
猫巷女王i
猫巷女王i 2020-12-31 05:52

In looking at the documentation, it appears that DropWizard is only able to serve static content living in src/main/resources. I\'d like to keep my static files in a separat

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-31 06:52

    Working off of Marcello Nuccio's answer, it still took me the better part of my day to get it right, so here is what I did in a bit more detail.

    Let's say I have this directory structure:

    • my-dropwizard-server.jar
    • staticdocs
      • assets
        • image.png

    Then this is what you have to do to make it work:

    1) In your dropwizard Application class, add a new AssetsBundle. If you want your assets to be served from a different URL, change the second parameter.

    @Override
    public void initialize(Bootstrap bootstrap) {
        bootstrap.addBundle(new AssetsBundle("/assets/", "/assets/"));       
    }
    

    2) Add the document root to your classpath by configuring the maven-jar-plugin like this. (Getting the "./staticdocs/" in the correct form took me a while. Classpaths are unforgiving.)

    
      org.apache.maven.plugins
      maven-jar-plugin
      2.4
      
        
          
            true
            true
          
          
            ./staticdocs/
          
        
      
    
    

    3) This step is entirely optional. If you want to serve your Jersey REST Resources from a different root path (e.g. "app"), add the following to your configuration YML:

    server:
      rootPath: /app/*
    

    Now you can access your static content like this, for example:

    localhost:8080/assets/image.png
    

提交回复
热议问题