可以考慮將 webroot 目錄放到 項目jar的同級
@Configuration
@Slf4j
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
ApplicationHome home = new ApplicationHome(getClass());
String jarParentPath = home.getSource().getParentFile().getAbsolutePath();
String webrootPath = jarParentPath + "/webroot/";
log.info("webrootPath:{}", webrootPath);
registry.addResourceHandler("/**")
.addResourceLocations("file:" + webrootPath);
}
//設定 默認訪問 index.html
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}
}
POM 配置
需要將 webroot 在編譯的時候 ,放到 target中 方便在調試的時候 可以訪問到
<!-- 其他插件配置保持不變 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.1</version>
<executions>
<execution>
<id>copy-webroot</id>
<phase>process-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/webroot</outputDirectory>
<resources>
<resource>
<directory>./webroot</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>