如何在Spring MVC中创建含未知数量@PathVariable的URL模式?
Alright, let's tackle this problem. You need a flexible URL pattern that can match all /asset/ paths with any number of nested path variables, right? Here's how to handle this across common frameworks and use cases:
For Spring MVC (since you mentioned @PathVariable)
If you're working in Spring MVC and need to handle these dynamic paths, you have two practical approaches:
Capture the full subpath as a single variable
Use the/**wildcard to grab everything after/asset/into one@PathVariable. This works great if you just need to process the complete path segment without splitting individual variables:@GetMapping("/asset/**") public String handleAssetPaths(@PathVariable("fullSubpath") String fullSubpath) { // fullSubpath will be the entire string after /asset/, e.g., "pathvariable10/pathvariable11/pathvariable12" return processAssetPath(fullSubpath); }The variable name
fullSubpathis just a convention—feel free to name it something that fits your workflow.Capture individual segments as a list
If you need to access each path variable separately (even when the count is unknown), use aList<String>with the/**pattern. Spring will automatically split the subpath into individual segments for you:@GetMapping("/asset/**") public String handleAssetPaths(@PathVariable List<String> pathSegments) { // pathSegments will be a list like ["pathvariable30", "pathvariable31", "pathvariable32", "pathvariable33", "pathvariable34"] return processAssetSegments(pathSegments); }
For General Routing Systems (Nginx, Express.js, Apache, etc.)
Most modern routing frameworks support the ** wildcard to match any number of nested path segments. Here's how to define the pattern for common tools:
- Nginx: Use
location ~ ^/asset/(.*)$ { ... }— the(.*)captures everything after/asset/for you to use in your handler - Express.js: Define your route as
app.get('/asset/**', (req, res) => { ... })— the full subpath will be available inreq.params[0] - Apache: Use a rewrite rule like
RewriteRule ^/asset/(.*)$ /your-handler?assetPath=$1 [L]to pass the subpath as a query parameter
Quick Tips
- The
**wildcard is the standard for matching any number of path segments (including zero, though you can add a quick check in your handler if you need to enforce a minimum number of segments) - If you ever need to restrict the pattern to only match paths with, say, 3+ segments, you can combine wildcards (e.g.,
/asset/*/*/**), but this is rarely necessary unless you have strict routing rules.
内容的提问来源于stack exchange,提问作者James Mwaiponya

