如何在Spring MVC中匹配URL部分?

dan*_*els 3 spring spring-mvc spring-boot

有没有一种方法可以计算Spring控制器中其余的URL部分?

即如果我的路线是/user/{userId}/*我可以获取userId参数和其余的URL?那个部分?

例如对于/user/1/this/is/a/path.html?a=b我应该得到 userId = 1userUrl = /this/is/a/path.html?a=b

我已经看到了一些解决方案并做了一些谷歌搜索,但是它们似乎有些奇怪的方式(很可能是因为答案是针对较旧版本的Spring的),所以在较新的版本中,如何才能做到这一点呢? ?

Kyl*_*son 5

是的,这是根据答案改编而成的示例

@GetMapping("/user/{userId}/**")
    public void get(@PathVariable("userId") String userId, HttpServletRequest request){
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String  patternMatch = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        AntPathMatcher apm = new AntPathMatcher();
        String finalPath = apm.extractPathWithinPattern(patternMatch, path);
    }
Run Code Online (Sandbox Code Playgroud)

在这个例子中userId = 1finalPath = this/is/a/path.html