SparkJava: Image Files
and any other static files your application needs
If:
- you want to includes background images (e.g.
.jpg
,.png
,.gif
, etc) files on the pages of your web app, and - those are static files (i.e. you have files like
cat1.jpg
andgoldenGate.png
rather than images you are uploading to the app (that you might, for example, store in a MongoDB or other database)
then, this page describes a solution for you. (Note: this solution is partially documented on the SparkJava documentation but that version leaves out a few crucial details.)
- Make a directory
src/main/resources/public/images
- You can use the command
mkdir -p src/main/resources/public/images
from your top level directory.
- You can use the command
- Put the image files in the directory:
src/main/resources/public/images
- Add this line to your code: staticFiles.location(“/public”); // Static files
- In your HTML code:
- if the file is
/src/main/resources/public/images/cat1.jpg
, - your
img
element should be:<img src="/images/cat1.jpg">
Note: do not include the/src/main/resources
part in yoursrc
attribute value.
- if the file is
-
You must do
mvn compile
each time you make changes to the contents of/src/main/resources/public
,
or for that matter, any file or directory under/src/main/resources
if you want those changes to take effect, even if you make no changes to Java source code.The reason: the
mvn compile
step does more than just compile your java code; it also copies all of the contents of thesrc/main/resources
directory into theCLASSPATH
.`
Related topics:
- SparkJava: —A micro framework for creating web applications in Java 8 with minimal effort
- SparkJava: Authentication—login/logout, and securing various pages in your app
- SparkJava: Bootstrap—Adding a nicer looking UI, with common navigation, drop down menus, etc.
- SparkJava: Facebook API—Authenticate with Facebook, then access the Facebook API
- SparkJava: Getting Started—A more clear tutorial
- SparkJava: Github API—Authenticate with Github, then access the Github API
- SparkJava: Image Files—and any other static files your application needs
- SparkJava: MongoDB—Using the NoSQL database MongoDB with SparkJava
- SparkJava: pac4j—Securing a SparkJava webapp, with options for OAuth or LDAP
- SparkJava: RESTful APIs—Creating RESTful APIs with SparkJava
- SparkJava: SLF4J—What is the Simple Logging Framework For Java, and how to configure it
- SparkJava: Templates—The various template engines you can use with SparkJava