Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Serving Static Assets in Spring Boot Applications

Tech May 13 2
Spring Boot provides convenient ways to handle static resources such as images, JavaScript files, and CSS stylesheets. When packaging your application, Spring Boot automatically includes certain directories and excludes others.
Default included directories: public/**, resources/**, static/**, templates/**, META-INF/resources/**, * Default excluded directories: .*, repository/**, build/**, target/**, **/*.jar, **/*.groovy
1. By default, Spring Boot serves static resources from specific locations within your classpath:
classpath:/static classpath:/public classpath:/resources classpath:/META-INF/resources
2. You can configure view resolution in your application.properties file to map to specific directories, though this approach is not recommended:
spring.mvc.view.prefix=/templates/ spring.mvc.view.suffix=.html
3. For more control over static resource serving, you can create a configuration class:
/** * Custom configuration for static resource handling */ @Configuration public class WebAssetConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // Map all /assets/** requests to classpath:/assets/ registry.addResourceHandler("/assets/**") .addResourceLocations("classpath:/assets/"); } }
Example 1: Custom static resource mapping
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // Map /web-resources/** to classpath:/web-resources/js/ registry.addResourceHandler("/web-resources/**") .addResourceLocations("classpath:/web-resources/js/"); }
After creating your static resource files, you can access them at: http://localhost:8080/web-resources/sample.html Example 2: Controller-based mapping
@RequestMapping("/web-content") public String serveWebContent() { return "/web-resources/sample.html"; }
Access this at: http://localhost:8080/web-content

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.