Spring 请求将 uri 的一部分映射到 PathVariable

Spring request mapping catching part of uri to PathVariable

我需要类似于 enter link description here
的内容 所以我的路径是:/something/else/and/some/more 我想这样映射它:

@RequestMapping(value="/something/**", method=RequestMethod.GET)
public String handleRequest(String theRestOfPath){ /***/ }

@RequestMapping(value="/something/**", method=RequestMethod.GET)
public String handleRequest(String[] theRestOfPathArr){ /***/ }

事情是...我希望将 ** 匹配的所有内容都传递给该方法:
1. 作为字符串 (theRestOfPath = "/else/and/some/more"),
2. 或作为数组 (theRestOfPathArr = ["else","and","some","more"])。

路径变量的数量可能会有所不同,所以我做不到:

@RequestMapping(value="/something/{a}/{b}/{c}", method=RequestMethod.GET)
public String handleRequest(String a, String b, String c){ /***/ }

有办法吗?
谢谢 :)

---编辑---
我最终得到的解决方案:

@RequestMapping(value = "/something/**", method = RequestMethod.GET)
@ResponseBody
public TextStory getSomething(HttpServletRequest request) {
    final String URI_PATTERN = "^.*/something(/.+?)(\.json|\.xml)?$";
    String uri = request.getRequestURI().replaceAll(URI_PATTERN, "");
    return doSomethingWithStuff(uri);
}

如果您将 HttpServletRequest 作为参数包含在您的方法中,那么您可以访问正在使用的路径。即:

@RequestMapping(value="/something/**", method=RequestMethod.GET)
public String handleRequest(HttpServletRequest request){
    String pattern = (String) request.getAttribute(
                     HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    String path = new AntPathMatcher()
            .extractPathWithinPattern(pattern, request.getServletPath());

    path = path.replaceAll("%2F", "/");
    path = path.replaceAll("%2f", "/");

    StringTokenizer st = new StringTokenizer(path, "/");
    while (st.hasMoreElements()) {
        String token = st.nextToken();
        // ...
    }
}

spring MVC 中有一个功能可以为您进行解析。只需使用@PathVariable 注释。

参考:Spring mvc @PathVariable