使用Spring Boot隐式服务index.html 摘要:

问题描述

我有一个简单的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();
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...