Spring boot doesn't map folder requests to `index.html` files

前端 未结 4 1137
一个人的身影
一个人的身影 2021-01-01 11:58

I\'ve got static folder with following structure:

index.html
docs/index.html

Spring Boot correctly maps reque

相关标签:
4条回答
  • 2021-01-01 12:19

    It's not Spring Boot mapping to index.html it's the servlet engine (it's a welcome page). There's only one welcome page (per the spec), and directory browsing is not a feature of the containers.

    0 讨论(0)
  • 2021-01-01 12:23

    Spring boot show index.html by default.

    but index.html should be in /resource/static or /public

    example:

    https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-static
    
    0 讨论(0)
  • 2021-01-01 12:30

    After Java 8 introduced Default Methods in Interfaces, WebMvcConfigurerAdapter has been deprecated in Spring 5 / Spring Boot 2.

    Using it will now raise the warning:

    The type WebMvcConfigurerAdapter is deprecated

    Hence, to make @hzpz's solution work again, we need to change it as follows:

    @Configuration
    public class CustomWebMvcConfigurer implements WebMvcConfigurer {
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/docs").setViewName("redirect:/docs/");
            registry.addViewController("/docs/").setViewName("forward:/docs/index.html");
        }
    }
    
    0 讨论(0)
  • 2021-01-01 12:33

    You can manually add a view controller mapping to make this work:

    @Configuration
    public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/docs").setViewName("redirect:/docs/");
            registry.addViewController("/docs/").setViewName("forward:/docs/index.html");
        super.addViewControllers(registry);
        }
    }
    

    The first mapping causes Spring MVC to send a redirect to the client if /docs (without trailing slash) gets requested. This is necessary if you have relative links in /docs/index.html. The second mapping forwards any request to /docs/ internally (without sending a redirect to the client) to the index.html in the docs subdirectory.

    0 讨论(0)
提交回复
热议问题