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

时间:2016-11-21 19:44:44

标签: spring spring-mvc spring-boot

有没有办法在Spring控制器中计算剩余的URL部分?

即。如果我的路由是/user/{userId}/*,我可以获得userId参数和其余网址吗?那个部分?

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

我已经看过一些解决方案并做了一些谷歌搜索,但它们似乎有点奇怪的方式(很可能是因为答案是针对较旧版本的Spring)所以在更新的版本中,这个怎么样?以干净的方式完成?

1 个答案:

答案 0 :(得分:4)

是的,这是一个改编自this回答

的例子
@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 = 1finalPath = this/is/a/path.html