Java Spring Boot:如何将我的应用程序根目录(“/")映射到 index.html?

问题描述:

我是 Java 和 Spring 的新手.如何将我的应用根目录 http://localhost:8080/ 映射到静态 index.html?如果我导航到 http://localhost:8080/index.html 它工作正常.

I'm new to Java and to Spring. How can I map my app root http://localhost:8080/ to a static index.html? If I navigate to http://localhost:8080/index.html its works fine.

我的应用程序结构是:

我的 configWebConfig.java 看起来像这样:

My configWebConfig.java looks like this:

@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/");
        }
}

我尝试添加 registry.addResourceHandler("/").addResourceLocations("/index.html"); 但它失败了.

I tried to add registry.addResourceHandler("/").addResourceLocations("/index.html"); but it fails.

如果您没有使用 @EnableWebMvc 注释,它本来可以开箱即用.当你这样做时,你会关闭 Spring Boot 在 WebMvcAutoConfiguration 中为你做的所有事情.您可以删除该注释,或者您可以重新添加您关闭的视图控制器:

It would have worked out of the box if you hadn't used @EnableWebMvc annotation. When you do that you switch off all the things that Spring Boot does for you in WebMvcAutoConfiguration. You could remove that annotation, or you could add back the view controller that you switched off:

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