java - 使用正则表达式的 Spring 请求映射,如 javax.ws.rs
问题描述
我正在尝试将此 Google App Engine maven 服务器存储库重写为 Spring。
我的 URL 映射有问题。Maven repo 服务器标准如下所示:
以斜线结尾的 URL,指向一个文件夹,例如:
http://127.0.0.1/testDir/ http://127.0.0.1/testDir/testDir2/
所有其他(末尾没有斜线)指向文件,例如:
http://127.0.0.1/testFile.jar http://127.0.0.1/testFile.jar.sha1 http://127.0.0.1/testDir/testFile2.pom http://127.0.0.1/testDir/testFile2.pom.md5
使用@javax.ws.rs.Path
了与 Spring 不同的支持正则表达式的注释。
我尝试了一堆组合,例如这样的:
@ResponseBody
@GetMapping("/{file: .*}")
public String test1(@PathVariable String file) {
return "test1 " + file;
}
@ResponseBody
@GetMapping("{dir: .*[/]{1}$}")
public String test2(@PathVariable String dir) {
return "test2 " + dir;
}
但我无法弄清楚如何在 Spring 应用程序中以正确的方式做到这一点。
我想避免编写自定义 servlet 调度程序。
解决方案
我曾经遇到过类似的问题,也是关于 Maven 端点的 Spring 实现。
对于文件端点,你可以做这样的事情
/**
* An example Maven endpoint for Jar files
*/
@GetMapping("/**/{artifactId}/{version}/{artifactId}-{version}.jar")
public ResponseEntity<String> getJar(@PathVariable("artifactId") String artifactId, @PathVariable("version") String version) {
...
}
这为您提供了artifactId
和version
,但对于 ,groupId
您需要进行一些字符串解析。您可以requestUri
在ServletUriComponentsBuilder
String requestUri = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri().toString();
// requestUri = /api/v1/com/my/groupId/an/artifact/v1/an-artifact-v1.jar
对于文件夹端点,我不确定这是否可行,但您可以尝试一下
@GetMapping("/**/{artifactId}/{version}")
public ResponseEntity<String> getJar(@PathVariable("artifactId") String artifactId, @PathVariable("version") String version) {
// groupId extracted as before from the requestUri
...
}