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

2022-08-31 07:06:57

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

我的应用结构是:

dirs

我的样子是这样的:config\WebConfig.java

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

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

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


答案 1

如果您没有使用注释,它将开箱即用。当您这样做时,您将关闭Spring Boot在中为您做的所有事情。您可以删除该注释,也可以重新添加已关闭的视图控制器:@EnableWebMvcWebMvcAutoConfiguration

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

答案 2

Dave Syer的回答举个例子:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyWebMvcConfig {

    @Bean
    public WebMvcConfigurerAdapter forwardToIndex() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                // forward requests to /admin and /user to their index.html
                registry.addViewController("/admin").setViewName(
                        "forward:/admin/index.html");
                registry.addViewController("/user").setViewName(
                        "forward:/user/index.html");
            }
        };
    }

}

推荐