5

I have a simple Spring Boot Starter Web application. I want to serve several static html files.

I know that I could serve static files with Spring Boot just simply putting then to /static subdirectory of my src/main/resources.

When I create file (for example) /static/docs/index.html, then I could access it via http://localhost:8080/docs/index.html.

What I want to achieve is to access this file simply with http://localgost:8080/docs where index.html is implicitly added by Spring.

Summary:

I need to serve static files in /static/{path}/index.html in resources via localhost:8080/{path} path.


I know that I could manually create mappings in controllers, but when there is many files to serve it becomes annoying.

3
  • 1
    Create one controller that automatically maps all of them? Commented Oct 1, 2020 at 11:43
  • Did you find a way to do it? Commented Jan 6, 2023 at 19:32
  • @geschema no, unfortunately not. Commented Jan 11, 2023 at 22:25

1 Answer 1

2

This will work

@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/docs").setViewName("forward:/docs/index.html");
    }
}

Or possible solution for all static subdirs (ugly version)

public void addViewControllers(ViewControllerRegistry registry) {
    File file;
    try {
        file = new ClassPathResource("static").getFile();
        String[] names = file.list();

        for(String name : names)
        {
            if (new File(file.getAbsolutePath() + "/" + name).isDirectory())
            {
                registry.addViewController("/" + name).setViewName("forward:/" + name +"/index.html");
            }
        }
    } catch (IOException e) {
        // TODO: handle error
        e.printStackTrace();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your answer, but it still requires to create mapping per path.
or you could get all directories from static folder and call this line dynamically for each directory if you want have permanent solution. It is not nice but effective.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.