How to pack resources in a Maven Project?

前端 未结 3 1694
独厮守ぢ
独厮守ぢ 2020-12-15 13:54

I am looking for suggestion in putting image file maven web project. One of classes under src/main/java need to use an image file. My problem is, if i put image file under s

相关标签:
3条回答
  • 2020-12-15 13:58

    You can use maven-resources-plugin to copy things to desired location.

    something like this

    <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>2.5</version>
          <executions>
            <execution>
              <id>copy-resources</id>
                <!-- here the phase you need -->
                <phase>validate</phase>
                <goals>
                  <goal>copy-resources</goal>
                </goals>
                <configuration>
                  <outputDirectory><!--your path here--></outputDirectory>
                    <resources>          
                      <resource>
                        <directory><!--path-here--></directory>
                       </resource>
                  </resources>              
                </configuration>      
              </execution>
            </executions>
          </plugin>
    

    EDIT: based on your comment below, i think what you need is a properties file where you maintain path to the resources folder. That path will be an absolute path. Depending on your deployment you change that path in the properties file.

    0 讨论(0)
  • 2020-12-15 14:01

    The default resource directory for all Maven projects is src/main/resources which will end up in target/classes and in WEB-INF/classes in the WAR. The directory structure will be preserved in the process.

    .
     |-- pom.xml
     `-- src
         `-- main
             |-- java
             |   `-- com
             |       `-- example
             |           `-- projects
             |               `-- SampleAction.java
             |-- resources
             |   `-- images
             |       `-- sampleimage.jpg
             `-- webapp
                 |-- WEB-INF
                 |   `-- web.xml
                 |-- index.jsp
                 `-- jsp
                     `-- websource.jsp
    

    The suggested way to put your resources is in the src/main/resources

    Reference: Adding and Filtering External Web Resources

    0 讨论(0)
  • 2020-12-15 14:15

    It seems that your problem is the way you read the image. You can't (or shouldn't) read the image from a Path. The Path might change on every system.

    You need to read the image from the classpath like:

    MyClass.class.getResource("/images/image.jpg")
    

    or

    MyClass.class.getResourceAsStream("/images/image.jpg")
    

    For this to work, the image Folder needs to be on the classpath. Maven will put everything in the classpath, that is under main/resources. So thats where your image folder should be.

    0 讨论(0)
提交回复
热议问题