0
votes

I'm using spring boot and storing my static content (html, css, etc.) as src/main/webapp. I understand that this is not recommended, because it won't be stored in jar file (should be in /META-INF/resources/, /resources/, /static/, /public/). But my question is not about storing static content in jar.

This is project structure:

App
 ├──src
 |   └───main
 |        ├── java
 |        |     └── ...
 |        ├── resources
 |        |     └── (everything here will be in jar)
 |        └── webapp <- this won't be in jar
 |               └── ...
 └ target
     └───App.jar

When I'm trying to run jar from App folder as java -jar target/App.jar, spring boot finds static content and works fine. However running it from target folder as java -jar App.jar won't find static content.

How to run App.jar from target folder and let spring boot find static content? Is it related to the classpath? I was trying to specify the classpath with -cp option, but it doesn't work.

2

2 Answers

1
votes

There's a point of view that this is a build problem. I don't mean a packaging problem (I know you don't want to put it into the jar). But you have another option: your build system (e.g. Maven) can copy static files into the target folder.

This answer demonstrates the use of maven-antrun-plugin to invoke Ant's copy command. This will put a copy of your static file into the target folder.

Obviously change the execution phase (test phase is too specific/late for your use-case). And maybe lookup whether there's a more Maveny way to do it (since delegating to Ant is not super-idiomatic).

0
votes

It's searching relative to the working directory of the executable at runtime. Since it's using a relative path to lookup the file (e.g. src/main/webapp/file.txt), your working directory needs to be /path/to/App.

You can change the working directory using -Duser.dir.

I recommend trying this:

java -Duser.dir=../ -jar App.jar

Or maybe it needs to be an absolute path. Tell me whether it works; I've not got the project to try it out.