【问题标题】:Spring boot static resources mapping ant matchers with ResourceHandlerRegistry使用 ResourceHandlerRegistry 映射蚂蚁匹配器的 Spring Boot 静态资源
【发布时间】:2016-07-01 16:39:59
【问题描述】:

我使用的是 Spring Boot 1.3.3 我的应用程序资源存在于 src/main/resources/static 下 示例:src/main/resources/static/index.html 我正在尝试使用前缀映射我的静态资源 /*/资源/**
这样它就可以匹配像这样的网址 /main/resource/** 和 /app/resource/**

当我尝试使用以下代码时

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
        "classpath:/META-INF/resources/", "classpath:/resources/",
        "classpath:/static/", "classpath:/public/" };

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/*/resource/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}

当我请求 domain:8080/app/resource/index.html 时出现 404

但是当我执行 domain:8080/index.html 时返回请求的页面 (看起来一些默认匹配器覆盖了我尝试配置的匹配器。)

当我使用以下代码时

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/app/resource/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}

按预期返回页面域:8080/app/resource/index.html。

我上面使用的蚂蚁匹配器有问题吗? 我可以按自己的方式使用静态资源吗?

任何帮助表示赞赏..

【问题讨论】:

标签: java spring spring-mvc spring-boot


【解决方案1】:

我遇到了完全相同的问题并找到了解决方案。

根据“Spring Boot Cookbook”,ResourceHandlerRegistry 使用 ant 样式的模式。此外,我遇到了'Spring: Difference of /** and /* with regards to paths',Devabc 指出..

请注意 Springs 的 AntPathMatcher 包含错误:它并不完全 符合 Ant Pattern 样式。例子: **/*.css 不适用于以 / 开头的路径,但它应该根据 Ant Style 公约。 – Devabc 2015 年 6 月 12 日 9:52

为了匹配像 http://localhost:8080/frontend/13/style.css 这样的 url,其中 13 可以不同,试试这个:

/* This did NOT work */
registry.addResourceHandler("/frontend/{id:[0-9]+}/**").addResourceLocations("classpath:/web-app/dist/");

/* This DID work, when removing the preceeding / */
registry.addResourceHandler("frontend/{id:[0-9]+}/**").addResourceLocations("classpath:/web-app/dist/");

所以对你来说,这意味着:尝试删除 url 中前面的“/”,即

registry.addResourceHandler("*/resource/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);

【讨论】:

  • 问题是 ResourceHadler 将 * OR ** 之前的所有内容都视为前缀。因此,当一个模式以 * 前缀开头时为空。
猜你喜欢
  • 1970-01-01
  • 2020-07-21
  • 2014-04-13
  • 2013-11-26
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
相关资源
最近更新 更多