从外部目录提供静态资源

Serving static resources from external directories

从应用程序外部存在的目录提供图像或任何其他静态资源(如 css 和 javascript)的正确方法应该是什么?

我曾经在 Spring MVC 应用程序中通过使用 xml 配置中的 mvc:resources 元素,或者通过扩展 WebMvcConfigurerAdapter 并添加相应的资源来轻松实现这一点Java 配置中的处理程序,然后指定存储资源的文件系统路径。

请记住,据我所知,jhipster 不使用 Spring MVC 我如何实现此功能?

我尝试在 jhipster 中配置 Spring MVC,但引入 dispatcherServlet 只会导致应用程序中断(正如预期的那样,对吗?),我仍然无法掌握 [=31] =] 所以我不确定解决方案是否是这样。

提前致谢。

更新:

在下面添加了我的解决方案。

对于开发人员,只需将文件放在 /src/main/webapp/yourdir/ 中即可(假设它是 public 静态资源)。对于生产,您需要将其添加到 config/WebConfigurer.java:

中的静态过滤器
/**
 * Initializes the static resources production Filter.
 */
private void initStaticResourcesProductionFilter(ServletContext servletContext,
                                                 EnumSet<DispatcherType> disps) {

    log.debug("Registering static resources production Filter");
    FilterRegistration.Dynamic staticResourcesProductionFilter =
            servletContext.addFilter("staticResourcesProductionFilter",
                    new StaticResourcesProductionFilter());

    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/index.html");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/images/*");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/fonts/*");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/scripts/*");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/styles/*");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/views/*");
    staticResourcesProductionFilter.setAsyncSupported(true);
} 

感谢 Spring Boot 的魔力,现在我知道您可以通过扩展 WebMvcConfigurerAdapter 配置 MVC 相关的东西。因此,我创建了自己的配置 class 来覆盖相应的方法,在本例中为 addResourceHandlers,它的工作原理非常棒。

请注意 @EnableWebMvc 不是必需的,否则你会弄乱 JHipster 前端。