spring-bootuberjar

While running as a jar application, Not able to access static files in springboot


I have a basic springboot application with the following folder structure. inside webapps i have some images and css.

enter image description here

If i run it using my Intellij IDE, I am able to access images and css

at localhost:8080/images/test.png

But if i create a fat jar and run it using java -jar demo.jar then i am not able to access these images or css folders

This is how i am building my jar using maven plugin

   <build>
        <resources>
            <resource>
                <directory>src/main/webapp</directory>
                <includes>
                    <include>css/default.css</include>
                    <include>images/*</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>build-info</goal>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

How can i make sure that these images and css files will be available when running as a jar file


Solution

  • The problem is that in the case of a JAR-file, src/main/webapp has no special meaning. It's not recommended to use it according to the documentation:

    Do not use the src/main/webapp directory if your application is packaged as a jar. Although this directory is a common standard, it works only with war packaging, and it is silently ignored by most build tools if you generate a jar.

    The way you can make this work is by treating src/main/webapp as a normal classpath directory. You did that by adding the <resources> tag.

    However, Spring boot only serves static content from certain folders (/public, /static or /META-INF/resources). Since you didn't put your files in such a folder, they aren't served by Spring boot.

    To solve this, you need to put your files within either src/main/resources/public (recommended) or src/main/webapp/public. If moving the files isn't an option, you can also change Maven to put it in that directory for you:

    <resources>
        <resource>
            <directory>src/main/webapp</directory>
            <targetPath>public/</targetPath> <!-- Add this -->
            <includes>
                <include>css/default.css</include>
                <include>images/*</include>
            </includes>
        </resource>
    </resources>