我有一個 spring 應用程式,它存盤物件和屬性,并提供訪問它們的路徑,格式為/application-root/{object}/{attribute}.
一個新的變化是允許物件在屬性中包含子物件。用戶應該能夠通過這樣的路徑訪問資料:
/application-root/{object1}/{attribute1}/{object2}/{attribute2}/{object3}/{attribute3}...
物件的嵌套深度沒有硬性限制,因此我需要能夠處理具有可變段數的路徑,并從物件和屬性中提取資訊。
我已經查看了 PathPattern 類中的正則運算式,但看起來正則運算式只會匹配單個段。
在 Spring 中處理可變數量路徑段的最佳方法是什么?
uj5u.com熱心網友回復:
選項:@see PathPattern
一個例子:
@RestController
class DemoController {
@GetMapping("/search/**")
public String search(HttpServletRequest request) {
return request.getRequestURI();
}
@GetMapping("/find/{*mapping}")
public String find(@PathVariable("mapping") String mapping ) {
return mapping;
}
}
curl "http://localhost:8080/search/1/2/3/4" 會輸出 /search/1/2/3/4
curl "http://localhost:8080/find/1/2/3/4" 會輸出 /1/2/3/4
從這里開始,您可以將字串決議/映射到您的物件/屬性
uj5u.com熱心網友回復:
如果使用像 Dirk 提到的 PathPattern 由于版本差異不是一個選項,您可以使用 aServletUriComponentsBuilder來檢索串列中的路徑段:
@RestController
public class SomeController {
@GetMapping("/application-root/**")
public void someEndpoint(HttpServletRequest request) {
List<String> pathSegments = ServletUriComponentsBuilder.fromRequest(request).build().getPathSegments();
// Remove "/application-root" by sublisting it as the returned list is immutable
pathSegments.subList(1, pathSegments.size())
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/361314.html
