2

我正在尝试将 WebJars-Locator 与 Spring-Boot 应用程序一起使用来映射 JAR 资源。根据他们的网站,我创建了一个这样的 RequestMapping:

@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/webjars-locator/{webjar}/{partialPath:.+}")
public ResponseEntity<ClassPathResource> locateWebjarAsset(@PathVariable String webjar, @PathVariable String partialPath)
{

问题在于 partialPath 变量应该包含第三个斜杠之后的任何内容。然而,它最终会限制映射本身。此 URI 映射正确:

http://localhost/webjars-locator/angular-bootstrap-datetimepicker/datetimepicker.js

但是这个根本没有映射到处理程序,只是返回一个 404:

http://localhost/webjars-locator/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css

根本区别只是路径中应由正则表达式(“.+”)处理但当该部分有斜杠时似乎不起作用的组件数量。

如果它有帮助,这将在日志中提供:

2015-03-03 23:03:53.588 信息 15324 --- [main] swsmmaRequestMappingHandlerMapping:映射“{[/webjars-locator/{webjar}/{partialPath:.+}],methods=[GET],params=[ ],headers=[],consumes=[],produces=[],custom=[]}" 到公共 org.springframework.http.ResponseEntity app.controllers.WebJarsLocatorController.locateWebjarAsset(java.lang.String,java.lang.字符串)2

Spring-Boot 中是否有某种类型的隐藏设置可以在 RequestMappings 上启用正则表达式模式匹配?

4

2 回答 2

8

文档中的原始代码没有为额外的斜线做好准备,对此感到抱歉!

请改用此代码:

@ResponseBody
@RequestMapping(value="/webjarslocator/{webjar}/**", method=RequestMethod.GET)
public ResponseEntity<Resource> locateWebjarAsset(@PathVariable String webjar, 
        WebRequest request) {
    try {
        String mvcPrefix = "/webjarslocator/" + webjar + "/";
        String mvcPath = (String) request.getAttribute(
                HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
        String fullPath = assetLocator.getFullPath(webjar, 
                mvcPath.substring(mvcPrefix.length()));
        ClassPathResource res = new ClassPathResource(fullPath);
        long lastModified = res.lastModified();
        if ((lastModified > 0) && request.checkNotModified(lastModified)) {
            return null;
        }
        return new ResponseEntity<Resource>(res, HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

我还将很快提供 webjar 文档的更新。

2015/08/05 更新:添加了 If-Modified-Since 处理

于 2015-03-04T17:37:23.987 回答
1

看来您无法PathVariable匹配“网址的其余部分”。您必须使用 ant 风格的路径模式,即“**”,如下所述:

Spring 3 RequestMapping:获取路径值

然后您可以获取请求对象的整个 URL 并提取“剩余部分”。

于 2015-03-04T12:02:28.870 回答