I have a Spring Boot web application, and I would like to serve static content located in a shared Dropbox directory on my Linode VPS (~/Dropbox/images). I've read that Spring Boot will automatically serve static content from
"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/",
but of course my Dropbox directory is not on the classpath.
Although I could configure Apache to serve the images in my Dropbox folder, I would like to take advantage of Spring Security to restrict access of the static content to authenticated users.
Using Spring BootSpring Boot comes with a pre-configured implementation of ResourceHttpRequestHandler to facilitate serving static resources. By default, this handler serves static content from any of the /static, /public, /resources, and /META-INF/resources directories that are on the classpath.
ResourceHandlerRegistry stores registrations of resource handlers for serving static resources such as images, css files and others through Spring MVC. It allows setting cache headers optimized for efficient loading in a web browser.
You can add your own static resource handler (it overwrites the default), e.g.
@Configuration public class StaticResourceConfiguration extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("file:/path/to/my/dropbox/"); } }
There is some documentation about this in Spring Boot, but it's really just a vanilla Spring MVC feature.
Also since spring boot 1.2 (I think) you can simply set spring.resources.staticLocations
.
Springboot (via Spring) now makes adding to existing resource handlers easy. See Dave Syers answer. To add to the existing static resource handlers, simply be sure to use a resource handler path that doesn't override existing paths.
The two "also" notes below are still valid.
. . .
[Edit: The approach below is no longer valid]
If you want to extend the default static resource handlers, then something like this seems to work:
@Configuration @AutoConfigureAfter(DispatcherServletAutoConfiguration.class) public class CustomWebMvcAutoConfig extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { String myExternalFilePath = "file:///C:/Temp/whatever/m/"; registry.addResourceHandler("/m/**").addResourceLocations(myExternalFilePath); super.addResourceHandlers(registry); } }
The call to super.addResourceHandlers
sets up the default handlers.
Also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With