Spring Boot
Static HTML
Web Development
Java
Application Deployment

How can I serve static html from spring boot?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Serving static HTML content from a Spring Boot application is a common requirement for many web developers. Spring Boot, with its embedded container and minimal configuration, simplifies the process of deploying a standalone application. This article provides a comprehensive guide on how to serve static HTML files using Spring Boot, delving into configurations and practical examples.

Basic Setup

Before diving into serving static HTML, ensure that you have a Spring Boot project set up. If not, you can create a new project using the Spring Initializr website or through an IDE like IntelliJ IDEA or Eclipse.

Creating a Spring Boot Project

To create a Spring Boot project using Spring Initializr, follow these steps:

  1. Visit Spring Initializr: Go to start.spring.io.
  2. Project Settings:
    • Choose a project type (Maven or Gradle).
    • Select the language (Java, Kotlin, or Groovy).
    • Pick a Spring Boot version.
  3. Project Metadata:
    • Group: com.example
    • Artifact: static-content-server
    • Packaging: Jar
    • Java version: 11 or higher
  4. Add Dependencies: Include Spring Web.
  5. Generate and Download: Click on "Generate" to download the project.

Directory Structure for Static Content

Spring Boot looks for static content in specific locations within the src/main/resources folder by default. These locations include:

  • static
  • public
  • resources
  • META-INF/resources

Directory Example

For this instance, consider creating a static folder. Your project structure should look like this:

 
1src
2└── main
3    ├── java
4    │   └── com
5    │       └── example
6    │           └── staticContentServer
7    │               └── StaticContentServerApplication.java
8    └── resources
9        ├── static
10        │   └── index.html
11        ├── application.properties

Serving HTML Files

Any HTML file placed in the static directory will be available at http://localhost:8080/<filename>. For instance, an index.html file will be served when accessing http://localhost:8080/.

Customizing the Path

If you need to serve static content from a different directory or customize URL paths, adjust the application.properties file.

Example Configuration

properties
spring.web.resources.static-locations=classpath:/custom-static-folder/

After changing this configuration, ensure your HTML files are placed in the custom-static-folder.

Advanced Customization

Serving at the Root Path

If you want to set a different file to be served at the root path, e.g., a homepage, create a WebMvcConfigurer to customize the paths:

java
1import org.springframework.context.annotation.Configuration;
2import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
3import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
4
5@Configuration
6public class WebConfig implements WebMvcConfigurer {
7
8    @Override
9    public void addViewControllers(ViewControllerRegistry registry) {
10        registry.addViewController("/").setViewName("forward:/index.html");
11    }
12}

Setting Cache Control

It's often useful to define cache control headers for static resources to improve performance.

java
1import org.springframework.context.annotation.Configuration;
2import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
3import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
4import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
5import org.springframework.http.CacheControl;
6
7import java.util.concurrent.TimeUnit;
8
9@Configuration
10public class CacheWebConfiguration implements WebMvcConfigurer {
11
12    @Override
13    public void addResourceHandlers(ResourceHandlerRegistry registry) {
14        ResourceHandlerRegistration resourceHandlerRegistration = 
15            registry.addResourceHandler("/**");
16        resourceHandlerRegistration.addResourceLocations("classpath:/static/");
17        resourceHandlerRegistration.setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS));
18    }
19}

Summary Table

FeatureDescriptionDefault Path/Setting
Default Static LocationsDirectory paths for serving static content.static, public, resources, META-INF/resources
Custom Static LocationSpecify a custom directory for static resources.spring.web.resources.static-locations
Root URL ConfigurationServe specific HTML at root path.Forwarding via WebMvcConfigurer
Cache ControlImprove performance with caching.Define using ResourceHandlerRegistry

Conclusion

Serving static HTML in Spring Boot is straightforward due to its predefined configurations and conventions. By understanding the default setup and knowing how to customize paths and caching, you can effectively manage and serve static content within your applications. Remember to leverage Spring Boot's flexibility for optimizing performance and organizing your resources efficiently.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.