You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring MVC中创建含未知数量@PathVariable的URL模式?

Universal URL Pattern for Variable-Length Asset Paths

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:

  1. 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 fullSubpath is just a convention—feel free to name it something that fits your workflow.

  2. Capture individual segments as a list
    If you need to access each path variable separately (even when the count is unknown), use a List<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 in req.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:48:37