问题描述
我有一个简单的Spring Boot Starter Web应用程序。 我想提供几个静态html文件。
我知道我可以使用Spring Boot提供静态文件,只需将其放到/static
的{{1}}子目录中即可。
例如,当我创建文件src/main/resources
时,可以通过/static/docs/index.html
访问它。
我想要实现的是简单地使用http://localhost:8080/docs/index.html
访问该文件,其中http://localgost:8080/docs
是Spring隐式添加的。
摘要:
我需要通过index.html
路径在资源/static/{path}/index.html
中提供静态文件。
我知道我可以在控制器中手动创建映射,但是当要处理的文件很多时,这会很烦人。
解决方法
这将起作用
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/docs").setViewName("forward:/docs/index.html");
}
}
或所有静态子目录(丑陋的版本)的可能解决方案
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();
}
}