SpringBoot Static Resource Access: Detailed Configuration for Images, JS, and CSS

This guide explains SpringBoot's default static resource locations, how to customize mappings for external file storage, configure access via application.yml, whitelist resources for Shiro or Spring Security, set browser caching, and implement a complete image upload and preview workflow.

Java Tech Workshop
Java Tech Workshop
Java Tech Workshop
SpringBoot Static Resource Access: Detailed Configuration for Images, JS, and CSS

Static resources

Images: jpg, png, gif, webp

Styles: css, less, scss

Scripts: js, ts

Static pages: html, ico, font

Uploaded files: Excel, PDF, video

SpringBoot automatically maps these resources and supports highly customizable mappings.

Default static resource locations (auto‑effective)

Five default locations, priority from high to low:

META-INF/resources
resources/
static/

(most common)

public/
webapp/

Default access rule: resource name can be accessed directly without a directory prefix.

Example file: src/main/resources/static/images/logo.png Access URL:

http://localhost:8080/images/logo.png

Custom static resource mapping

Store uploaded files on an external path to avoid loss after repackaging.

Configuration class

package com.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Static resource configuration
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // URL pattern
        registry.addResourceHandler("/uploads/**")
                // Local directory (must end with /)
                .addResourceLocations("file:D:/uploads/");

        // Optional relative path
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }
}

Access example

Local file: D:/uploads/avatar.jpg Access URL:

http://localhost:8080/uploads/avatar.jpg

application.yml static resource configuration

spring:
  web:
    resources:
      static-locations: classpath:/static/,classpath:/public/,file:./uploads/

Note: This overrides the default locations, so all required locations must be listed.

Static resource whitelist for security frameworks

When using Shiro or Spring Security, static resources must be excluded from authentication.

Shiro whitelist

filterMap.put("/static/**", "anon");
filterMap.put("/uploads/**", "anon");
filterMap.put("/**/*.js", "anon");
filterMap.put("/**/*.css", "anon");
filterMap.put("/**/*.png", "anon");
filterMap.put("/**/*.jpg", "anon");
filterMap.put("/**/*.ico", "anon");

Spring Security whitelist

http.authorizeRequests()
    .antMatchers("/static/**", "/uploads/**", "/**.js", "/**.css").permitAll()
    .anyRequest().authenticated();

Custom favicon.ico

Place favicon.ico under resources/static/. SpringBoot loads it automatically.

Static resource caching (production)

registry.addResourceHandler("/static/**")
        .addResourceLocations("classpath:/static/")
        // Browser cache for 10 days
        .setCachePeriod(864000);

Image upload and preview

Upload endpoint

@PostMapping("/upload")
public Result upload(MultipartFile file) throws IOException {
    String path = "D:/uploads/";
    File dir = new File(path);
    if (!dir.exists()) dir.mkdirs();

    String fileName = UUID.randomUUID() + file.getOriginalFilename()
            .substring(file.getOriginalFilename().lastIndexOf("."));
    file.transferTo(new File(path + fileName));

    String url = "http://localhost:8080/uploads/" + fileName;
    return Result.success(url);
}

Mapping configuration

registry.addResourceHandler("/uploads/**")
        .addResourceLocations("file:D:/uploads/");

Linux server deployment path

registry.addResourceHandler("/uploads/**")
        .addResourceLocations("file:/usr/local/uploads/");

Common causes of static resource 404

Missing trailing slash in URL pattern – use /uploads/** instead of /uploads.

Missing trailing slash in local path – use file:D:/uploads/ instead of file:D:/uploads.

Intercepted by security filter – whitelist the resources.

Path format mismatch between Windows and Linux – Windows uses D:/uploads/, Linux uses /usr/local/uploads/.

Insufficient directory permissions – ensure read/write permissions on Linux.

Summary of static resource handling in SpringBoot

Default location static can be accessed directly.

External files are served via addResourceHandler.

Image upload should use an external directory to survive packaging.

Static resources must be whitelisted when security frameworks are used.

Both URL pattern and local path must end with a trailing slash.

Configure caching in production to improve performance.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Cachingfile uploadstatic resourcesspring securityshiroapplication.ymlresource mapping
Java Tech Workshop
Written by

Java Tech Workshop

Focused on Java backend technologies, sharing fundamentals, multithreading, JVM, the Spring ecosystem, microservices, distributed systems, high concurrency, source‑code analysis, and practical experience. Continuously delivers high‑quality original content, interview guides, and learning roadmaps to help Java developers progress from beginner to advanced, enhancing technical skills and core competitiveness.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.