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.jpgandgoldenGate.pngrather 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/imagesfrom 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
imgelement should be:<img src="/images/cat1.jpg">Note: do not include the/src/main/resourcespart in yoursrcattribute value.
- if the file is
-
You must do
mvn compileeach time you make changes to the contents of/src/main/resources/public,
or for that matter, any file or directory under/src/main/resourcesif you want those changes to take effect, even if you make no changes to Java source code.The reason: the
mvn compilestep does more than just compile your java code; it also copies all of the contents of thesrc/main/resourcesdirectory into theCLASSPATH.`
More on SparkJava: Image Files
- 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