Friday 2 August 2019

Spring boot: Static content serving


This is continuation to my previous post. In this post, I am going to update previous application to serve static files like images, css style sheets, images.

Previous project structure looks like below.

You can download my previous project from this link.

How to serve static content?
By default, ‘spring boot’ serves static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext.

Follow below step-by-step procedure to develop complete working application.

Step 1: Navigate to the project ‘spring boot app’ in the file system.



Create ‘resources’ folder under src/main folder.

Under resources folder, create index.html file and css, images, js, lib, views folders.


Project structure change like below.

Step 2: Import maven project into eclipse.

Right click on the project -> Maven -> Update Project.

Step 3: Open index.html and update it like below.

index.html
<html>
<head>
<title>Welcome</title>
</head>

<body>
    <h1>Welcome to Spring Boot Application Development</h1>
</body>
</html>


Run App.java file, which is located in ‘com.sample.app’ package.


App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}


Open the url ‘http://localhost:8080/index.html’ in browser, you can see below kind of screen.


Step 4: Lets add home.css file to css folder.


home.css
body {
  background-color: lightblue;
}

h1 {
  color: navy;
  margin-left: 30px;
}

Open the url ‘http://localhost:8080/css/home.css’ in browser, you can able to see below screen.

Complete project structure looks like below.

Note
One thing to note here is that, I am not redeployed App.java application after adding home.css files. Changes take place automatically.

You can download complete working application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment