Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedded Tomcat directory listing for spring-boot application

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");
    }
}
like image 583
Sankar Avatar asked Jan 26 '16 00:01

Sankar


1 Answers

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);

    }
}
like image 121
Hobo Joe Avatar answered Nov 11 '22 03:11

Hobo Joe