Static resource handling in Spring MVC is the mechanism that lets the framework serve non-dynamic files — CSS, JavaScript, images, fonts — directly from a configured location without routing them through a controller.
Key Points: • WebMvcConfigurer's addResourceHandlers method maps a URL pattern to one or more physical or classpath locations. • Common locations include classpath:/static/, classpath:/public/, or /resources/ under the webapp root. • Resource handlers can enable HTTP caching headers so browsers cache static assets and avoid re-fetching them on every request. • In plain Spring MVC (non-Boot), @EnableWebMvc is needed to activate the MVC configuration that resource handling relies on. • Spring Boot auto-configures sensible static resource handling out of the box, so manual setup is only needed to customize it.
Example: Requesting /css/site.css in the browser gets matched against a registered pattern like "/css/**" and served from classpath:/static/css/site.css, without ever invoking a controller method.
Code Example:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/", "classpath:/static/");
}
}Interview Tip: A concise interview answer is:
"I override addResourceHandlers in a WebMvcConfigurer to map a URL pattern like /resources/** to physical locations such as classpath:/static/. That tells Spring MVC to serve those requests directly as static files instead of routing them through a controller, and I can add cache headers there too."