I have a spring boot application with embedded Tomcat. I wanted to expose some images files & folders from a different location via tomcat directory listing. So I added the below in my configuration file called
public class AppConfig extends WebMvcConfigurerAdapter
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("file:///xxx/yyy/images/");
}
}
I can now access individual image(s), if I know the name.
Example: localhost:8080/images/file.jpg.
But since the directory listing is false by default, I can't access the images listing through "localhost:8080/images/" to know the all the available images.
I tried the below option to add the listings as well, but did not work.
public class MyApplication implements ServletContextInitializer{
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.setInitParameter("listings", "true");
}
}
Updated for Spring 2.1
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;
@Component
public class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
@Value("${tomcat.file.base}") // C:\\some\\parent\\child
String tomcatBaseDir;
@Override
public void customize(TomcatServletWebServerFactory factory) {
// customize the factory here
TomcatContextCustomizer tomcatContextCustomizer = new TomcatContextCustomizer() {
@Override
public void customize(Context context) {
String parentFolder = tomcatBaseDir.substring(0,tomcatBaseDir.lastIndexOf("\\"));
String childFolder = tomcatBaseDir.substring(tomcatBaseDir.lastIndexOf("\\") + 1);
context.setDocBase(parentFolder);
Wrapper defServlet = (Wrapper) context.findChild("default");
defServlet.addInitParameter("listings", "true");
defServlet.addInitParameter("readOnly", "false");
defServlet.addMapping("/"+ childFolder + "/*");
}
};
factory.addContextCustomizers(tomcatContextCustomizer);
}
}
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