在spring中访问classpath上的所有模板

问题描述 投票:0回答:1

我试图获取我在spring资源/模板中保存在模板文件夹中的所有模板。下面是我正在尝试,我试图访问使用/ getTeamplateList,但它没有给任何东西

 @RequestMapping(value = "/getTemplateList", produces = "application/json")
public List getTemplates() throws IOException {

    List s = new ArrayList();
   File[] resourceFolderFiles = getResourceFolderFiles("classpath:/templates/");
    s.addAll(Arrays.asList(resourceFolderFiles));
    return s;
}

private static File[] getResourceFolderFiles (String folder) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL url = loader.getResource(folder);
    String path = url.getPath();
    return new File(path).listFiles();
}
spring thymeleaf
1个回答
0
投票

您可以通过以下方式执行此操作:

@Autowired
private ResourceLoader resourceLoader;

final List<String> result = Arrays.stream(loadResources()).map(resource -> resource.getFilename()).collect(Collectors.toList());


private Resource[] loadResources() throws IOException {
    return ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:/templates/*.html");
}

这将打印

[
  "template1.html",
  "template2.html"
...
]

在回应中。

© www.soinside.com 2019 - 2024. All rights reserved.