英文:
Serve index.html implicitly with Spring Boot
问题
我有一个简单的Spring Boot Starter Web应用程序。
我想要提供几个静态HTML文件。
我知道我可以使用Spring Boot来提供静态文件,只需将它们放在我的src/main/resources
目录下的/static
子目录中。
当我创建文件(例如)/static/docs/index.html
时,我可以通过http://localhost:8080/docs/index.html
访问它。
我想要实现的是通过http://localhost:8080/docs
来访问这个文件,其中index.html
会被Spring隐式添加。
摘要:
我需要通过localhost:8080/{path}
路径在资源中提供/static/{path}/index.html
中的静态文件。
我知道我可以在控制器中手动创建映射,但当有许多文件需要提供时,这变得很烦人。
英文:
I have a simple Spring Boot Starter Web application.
I want to serve several static html files.
I know that I could serve static files with Spring Boot just simply putting then to /static
subdirectory of my src/main/resources
.
When I create file (for example) /static/docs/index.html
, then I could access it via http://localhost:8080/docs/index.html
.
What I want to achieve is to access this file simply with http://localgost:8080/docs
where index.html
is implicitly added by Spring.
Summary:
I need to serve static files in /static/{path}/index.html
in resources via localhost:8080/{path}
path.
I know that I could manually create mappings in controllers, but when there is many files to serve it becomes annoying.
答案1
得分: 2
这将会起作用
@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: 处理错误
e.printStackTrace();
}
}
英文:
This will work
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/docs").setViewName("forward:/docs/index.html");
}
}
Or possible solution for all static subdirs (ugly version)
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();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论