2016-11-21 18 views
2

有沒有辦法在Spring控制器中計算剩餘的URL部分?如何在Spring MVC中匹配URL部分?

即如果我的路線是/user/{userId}/*我可以得到userId參數和URL的其餘部分?那個部分?

例如,對於/user/1/this/is/a/path.html?a=b我應該得到 userId = 1userUrl = /this/is/a/path.html?a=b

我已經看到了一些解決方案,並做了一些谷歌搜索,但他們似乎有種奇怪的方式做到這一點(很可能是由於問題的答案是給老Spring的版本)所以在更新的版本中,這個e如何以乾淨的方式完成?

回答

3

是的,這裏是改編自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