Backend Development 3 min read

How to Use @PathVariable and Map Static Resources in Spring Boot

This guide explains how to use @PathVariable to capture URL segments, configure static resource mapping for local files, and centralize path values in Spring Boot applications, providing code examples for request mapping, resource handler registration, and property injection.

Java Captain
Java Captain
Java Captain
How to Use @PathVariable and Map Static Resources in Spring Boot

1. Scenario

Different paths trigger different methods. For example, in a video site, different modules are invoked based on the path.

2. Usage

@PathVariable indicates that the parameter should be obtained from the URL path.

<code>// Wrap the required parameter with curly braces
@RequestMapping("/video/{v}")
// The called method receives the parameter using @PathVariable
public void function(@PathVariable String v) {};
</code>

3. Static Resource Mapping

By default, Spring Boot serves static resources (images, videos, etc.) from the static folder. To serve files from a local directory, use a static resource mapping. Adding the following code to the main application class maps the URL path /img/** to a local folder. Note that the class implements WebMvcConfigurer .

<code>@SpringBootApplication
public class Application implements WebMvcConfigurer {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // URL path                Disk path
        registry.addResourceHandler("/img/**")
                .addResourceLocations("file:E:\\Java\\project1\\img\\");
    }
}
</code>

4. Global Configuration

If a value (e.g., a path) is used in multiple places, it can be maintained centrally in a configuration file.

<code>img-path = E:/Java/project1/img/
</code>

Inject the configured value in code:

<code>@Value("${img-path}") // Read the value from the configuration file
private String imgPath;
</code>
JavaSpring BootStatic ResourcesWebMvcConfigurerPathVariable
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login 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.