Serve Static Resources With Spring
Last Updated :
24 Apr, 2025
It's essential to know about static resources, which are the resources that do not change frequently on a web page. To serve these static resources, Spring Boot comes with an inbuilt class called ResourceHttpRequestHandler in conjunction with the ResourceHandlerRegistry class. You can keep these static resources under specific paths like '/public', '/static', 'resources', and 'META-INF/resources/'. To change the default locations that serve the static resources, define them in the resources folder with
spring.resources.static-locations=/html, /css, /js
Sample Folder Structure:
sample folder structureGuide to Serving Static Pages
We can customize the resource handling by configuring it with ResourceHandlerRegistry. We typically configure how our Spring Boot app deals with web stuff in a special class. This class can either be an old-style one called WebMvcConfigurerAdapter (which is a bit outdated but still commonly used) or directly implement WebMvcConfigurer. Here is the sample code
Java
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void
addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/")
.setCachePeriod(3900)//mention in seconds
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
}
Lets get to know what the ResourceHandlerRegistry does,
- It is responsible for configuring how static resources are handled by Spring MVC Appl.
- Mapping URLs to Resources
- Setting Cache Periods
- Enabling Resource Chains : You can add a special code in the resource's web address, making sure that browsers know when it changes. This helps in controlling how long the browser keeps a copy and ensures users always see the latest version of the resource. Lets see how we do this,
Java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.VersionResourceResolver;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
}
}
Sample Output:
sample outputHere we are using Thymeleaf here, you can use any other
<!-- Thymeleaf example -->
<link rel="stylesheet" th:href="@{/static/css/style.css}" />
Let's get to know what the PathResourceResolver does,
- Resource Resolution : helps find the actual resource on the server that corresponds to the requested URL.
- Support for Versioned Resources
- Fallback Mechanism : If the requested file is not found, the PathResourceResolver tries to be helpful by looking for a similar file with a different type or in another location.
You may also have a question what will happen after the cache period? Let me tell you,
- Conditional GET Request :
- The client browser sends a conditional GET request to the server, including an If-Modified-Since header with the timestamp of when it originally cached the resource.
- Server Response :
- If the resource has not been modified since the provided timestamp, the server responds with a 304 Not Modified status code and an empty body. This indicates to the browser that the cached version is still valid.
- Using Cached Resource :
- If the server indicates that the resource hasn't been modified, the browser continues to use the cached version. This helps in reducing unnecessary data transfer and improves performance.
- If Resource is Modified :
- If the server determines that the resource has been modified since the provided timestamp, it sends the updated resource with a 200 OK status code. The browser then replaces the old cached version with the new one.
Guide to serving dynamic pages
Let's get into a step-by-step guide on this demo for generating dynamic content using Thymeleaf where data are processed from the server.
Java
@Controller
public class studentController {
@Autowired
studentService service;
// handler method to handle studnts
@GetMapping("/students")
public String listStudents(Model model)
{
model.addAttribute("index",
service.getAllStudents());
return "index";
}
@GetMapping("/students/new")
public String addStudents(Model model)
{
// object to hold the data of new student
Student student = new Student();
model.addAttribute("student", student);
return "add_students";
}
@PostMapping("/students")
public String
saveStudent(@ModelAttribute("student") Student student)
{
service.saveStudent(student);
return "redirect:/students";
}
@GetMapping("students/edit/{id}")
public String editStudent(@PathVariable("id") Long id,
Model model)
{
model.addAttribute("student",
service.getStudentById(id));
return "edit_student";
}
}
In this piece of code that I've written you should know about Model Interface which is present in the package of org.springframework.ui.Model and Controller annotation and not RestController.
Model interface is used in controllers to pass data to views. It holds attributes that need to be displayed in the user interface. Controllers add data to the model, and views access and display that data. It's a way to share information between the backend and frontend components of a web application.
Genrally the @RestController annotation is used to create a webservice that returns JSON/XML data, @Controller annotation that is used to create web controllers that returns views. You may have a question what views are, simply we could say the user interface output to the user request. To work completely with the dynamic content, just write the HTML pages using Thymeleaf and serve it through the controller, where the server sends the data to the view.
Similar Reads
Spring - ResourceLoaderAware with Example
Prerequisite: Introduction to Spring Framework In this article, we will discuss the various ways through which we can load resources or files (e.g. text files, XML files, properties files, etc.) into the Spring application context. These resources or files may be present at different locations like
4 min read
Spring Boot Without A Web Server
Spring Boot is a widely used framework used for building Java applications. It comes with lots of features that make a developer's life easy. Out of those features, spring boot applications come with an embedded server in it. The default server being used in spring boot applications is Apache Tomcat
3 min read
Spring MVC with JSP View
Spring MVC architecture uses the "FrontController" design pattern which is fundamental to any MVC design implementation. The DispatcherServlet is at the heart of this design whereby HTTP requests are delegated to the controller, views are resolved to the underlying view technology, in addition to pr
4 min read
Static Content in Spring WebFlux
Spring WebFlux is a framework for building responsive web applications. It supports reactive programming. One of the most important features of a web application is to serve static content such as HTML, CSS, and JavaScript files. In this article, we will discuss how to create static content in Sprin
3 min read
Securing REST APIs with Spring Security
In Spring Boot applications, securing the REST APIs is a critical aspect of developing secure and robust applications. REST APIs are commonly used to expose functionalities to external systems, mobile applications, and web applications. Without proper security measures, these APIs can become targets
8 min read
Control the Session with Spring Security
Spring Security is a scalable authentication control system, the de facto standard for protecting Spring-based applications. One of the main features is its consistency management capability which is important for the state between HTTP client and HTTP server. Proper session management is essential
4 min read
What is Dispatcher Servlet in Spring?
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made
6 min read
Spring Security with Maven
Spring Security is a powerful and highly customizable authentication access management system. This is standard for protecting Spring-based applications. Spring Security is a framework that focuses on authentication and authorization for Java applications. Spring Security is a robust framework with
5 min read
Spring MVC â Using @RestController for RESTful Web Services
Spring MVC (Model-View-Controller) is a powerful framework for developing web applications in Java. A core component of Spring MVC is the @RestController annotation, which simplifies the creation of RESTful web services by handling HTTP requests and responses with minimal configuration.Overview of S
4 min read
Spring Boot - Introduction to RESTful Web Services
RESTful Web Services REST stands for REpresentational State Transfer. It was developed by Roy Thomas Fielding, one of the principal authors of the web protocol HTTP. Consequently, REST was an architectural approach designed to make the optimum use of the HTTP protocol. It uses the concepts and verbs
5 min read