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

3
有没有一种方法可以在Spring控制器中匹配剩余的URL部分?
例如,如果我的路由是/user/{userId}/*,我能否获取userId参数和剩余的URL部分?* 部分?
例如,对于/user/1/this/is/a/path.html?a=b,我应该得到userId = 1userUrl = /this/is/a/path.html?a=b 我已经看过一些解决方案并做了一些Google搜索,但它们似乎是一种奇怪的方式(很可能是因为答案针对旧版Spring),那么在更近期的版本中如何以简洁的方式实现呢?
1个回答

6

是的,这里有一个例子,改编自这个答案

@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);
    }

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接