简体   繁体   English

使用 Spring Boot 隐式提供 index.html

[英]Serve index.html implicitly with Spring Boot

I have a simple Spring Boot Starter Web application.我有一个简单的 Spring Boot Starter Web 应用程序。 I want to serve several static html files.我想提供几个静态 html 文件。

I know that I could serve static files with Spring Boot just simply putting then to /static subdirectory of my src/main/resources .我知道我可以使用 Spring Boot 提供静态文件,只需将其放入src/main/resources /static子目录即可。

When I create file (for example) /static/docs/index.html , then I could access it via http://localhost:8080/docs/index.html .当我创建文件(例如) /static/docs/index.html ,我可以通过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.我想要实现的是简单地使用http://localgost:8080/docs访问这个文件,其中index.html是由 Spring 隐式添加的。

Summary:概括:

I need to serve static files in /static/{path}/index.html in resources via localhost:8080/{path} path.我需要通过localhost:8080/{path}路径在资源中的/static/{path}/index.html中提供静态文件。


I know that I could manually create mappings in controllers, but when there is many files to serve it becomes annoying.我知道我可以在控制器中手动创建映射,但是当有很多文件要提供时它变得很烦人。

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM