Back to Java
2026-01-106 min read

Add Static Files (Java)

Learn Add Static Files (Java) step by step with clear examples and exercises.

Why This Matters

Adding static files to a Java web application is crucial for serving external resources such as CSS, JavaScript, images, and more. This tutorial will guide you through the process of adding static files using an example project, explaining its importance in improving user experience, SEO, and overall web application development.

Importance of Static Files

  • Improved User Experience: Serving static files can significantly reduce page load times by offloading non-dynamic content from the server, leading to a smoother and faster browsing experience for users.
  • Better Responsiveness: Static resources are typically smaller in size compared to dynamic content, allowing web pages to respond more quickly to user interactions.
  • SEO Benefits: Search engines favor websites with optimized load times, making it easier for them to crawl and index your site, ultimately improving its visibility and ranking.

Prerequisites

Before diving into adding static files to a Java web application, ensure you have the following prerequisites:

  • JDK (Java Development Kit) installed on your system
  • An IDE (Integrated Development Environment) like IntelliJ IDEA or Eclipse
  • A basic understanding of Java and Maven (for project setup)
  • Familiarity with a web framework such as Spring Boot

Why Use a Web Framework?

Using a web framework like Spring Boot simplifies the process of building web applications by providing pre-built components, reducing boilerplate code, and improving productivity.

Core Concept

In this example, we will use the popular Java web framework, Spring Boot, to create a simple web application that serves static files. To get started, follow these steps:

  1. Create a new Spring Boot project using Spring Initializr with the following dependencies:
  • Web
  • Thymeleaf (optional, for front-end templating)
  1. Extract the project and open it in your preferred IDE.
  1. Create a new folder named resources inside the src/main/resources directory. This folder will contain our static files.
  1. Inside the resources folder, create two subfolders: static for our static assets (CSS, JavaScript, images) and templates for Thymeleaf templates if you chose that option during project creation.
  1. Place your static files inside the appropriate folders. For example, place an image named example.jpg in the static folder.
  1. Create a new controller class (e.g., StaticResourceController) to handle requests for our static files:
package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResourceHandlerRegistry;
import org.springframework.context.annotation.Configuration;

@Controller
@RequestMapping("/static")
public class StaticResourceController {

@GetMapping("**")
public String serveStaticFiles() {
return "forward:/";
}
}
  1. Add the following configuration to your WebMvcConfigurer class (usually located in com.example.demo.config) if you have one:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
  1. Run your application and navigate to http://localhost:8080/static/example.jpg in your browser to see the static file being served by our Java web application.

Serving Multiple Static Files

To serve multiple static files, simply create additional folders within the src/main/resources/static directory, and place the corresponding files inside them. For example, if you want to serve JavaScript files, create a new folder named js under src/main/resources/static.

Worked Example

Let's walk through an example of adding a simple CSS file, styles.css, inside the src/main/resources/static/css folder:

  1. Create a new file named styles.css in the specified location and add some basic styling:
body {
background-color: #f0f8ff;
}

h1 {
color: #32a852;
}
  1. Create an HTML file (e.g., index.html) inside the src/main/resources/templates folder and include a link to our CSS file:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Static File Example</title>
<link th:href="@{/static/css/styles.css}" rel="stylesheet" />
</head>
<body>
<h1>Welcome to our static file example!</h1>
</body>
</html>
  1. Update the StaticResourceController class to handle requests for the index.html file:
@GetMapping("/")
public String serveIndex() {
return "index";
}
  1. Run your application and navigate to http://localhost:8080/ in your browser to see the HTML page with our CSS styling applied.

Serving Multiple Static Files (Continued)

To serve multiple static files, create additional folders within the src/main/resources/static directory, and place the corresponding files inside them. For example, if you want to serve JavaScript files alongside CSS and HTML:

  • Create a new folder named js under src/main/resources/static.
  • Place your JavaScript files inside it (e.g., script.js).
  • Update your HTML template to include the correct paths for both CSS and JavaScript files:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Static File Example</title>
<link th:href="@{/static/css/styles.css}" rel="stylesheet" />
<script th:src="@{/static/js/script.js}"></script>
</head>
<body>
<h1>Welcome to our static file example!</h1>
</body>
</html>

Common Mistakes

  • Forgetting to configure the resource handlers: Make sure you've added the necessary configuration to handle requests for static resources.
  • Incorrect file paths: Ensure that your static files are placed in the correct folders and that the paths in your HTML templates match those of the actual files.
  • Missing or incorrect CSS selectors: Verify that your CSS selectors correctly target the elements you want to style, and check for typos or syntax errors.

Common Mistakes (Continued)

  • Incorrect MIME types: If your server is not serving static files with the correct MIME type, it may cause issues with rendering or displaying the file in the browser. You can configure Spring Boot to serve specific MIME types for different file extensions by adding a ResourceHandlerRegistry configuration similar to the one provided earlier but with custom MIME types.
  • Caching issues: Browsers often cache static files, which may cause outdated versions of the files to be displayed. To resolve this issue, you can add a version number or query string parameter to your static file URLs, ensuring that the browser fetches the latest version each time.

Practice Questions

  1. How can you serve an image named logo.png using a Spring Boot web application?
  • Place the image in the src/main/resources/static folder and update your HTML template to include the correct path.
  1. What should be the structure of the folder containing static files in a Spring Boot project?
  • Create a new folder named resources inside the src/main/resources directory, then create two subfolders: static for our static assets and templates for Thymeleaf templates if you chose that option during project creation.
  1. Why is it important to configure resource handlers when serving static files in a Java web application?
  • Configuring resource handlers allows you to control how requests are handled, improve performance by caching static resources, and customize MIME types for different file extensions if needed.
  1. How would you modify the example provided to serve JavaScript files alongside CSS and HTML?
  • Create a new folder named js under src/main/resources/static, place your JavaScript files inside it, and update your HTML template to include the correct paths for both CSS and JavaScript files.

FAQ

Q: Can I serve static files without using a dedicated controller or configuration?

A: Yes, Spring Boot automatically serves static resources from the src/main/resources/static directory by default. However, configuring resource handlers gives you more control over how requests are handled and can improve performance in some cases.

Q: How do I serve files outside of the src/main/resources directory?

A: To serve files from a custom location, you'll need to configure the ResourceHandlerRegistry with the appropriate path. For example, if your static files are located in src/main/webapp, update the configuration as follows:

registry.addResourceHandler("/static/**").addResourceLocations("classpath:/WEB-INF/webapp/static/");

Q: Can I use a different templating engine instead of Thymeleaf?

A: Yes, you can use other templating engines like Freemarker or Mustache with Spring Boot. However, the configuration and setup process may vary depending on the chosen engine.

Add Static Files (Java) | Java | XQA Learn