如何在spring mvc rest服务中将请求URI的一部分放入路径变量中

时间:2014-10-29 05:37:40

标签: java spring rest spring-mvc url-mapping

我的服务代码:

@RequestMapping(value = "/projects/{projectId}/resources/web/{path}", method = RequestMethod.GET)
@ResponseBody
public void getWebFileContent(@PathVariable("projectId") String projectId,@PathVariable("path") String path, HttpServletRequest httpServletRequest) throws Exception {
} 

我的请求将是

  • /项目/ PRO1 /资源/网络/ SRC /主/ web应用
  • /项目/ PRO1 /资源/网络/ src目录/主/测试/ COM / PRO1 ...

是否可以将“src / main / webapp / ../ .....”变为“路径”变量

1 个答案:

答案 0 :(得分:1)

Spring在url处理程序映射中提供了三种模式

  • ? - 零或一个字符
  • * - 一个字符
  • ** - 一个或多个字符

以下方法解决了我的问题

@RequestMapping(value = "/projects/{projectId}/resources/web/**", method = RequestMethod.GET)
@ResponseBody
public void getWebFileContent(@PathVariable("projectId") String projectIdHttpServletRequest httpServletRequest) throws Exception {
    String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); 
    // will get path = /projects/pro1/resources/web/src/main/webapp
    String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    // will get bestMatchPattern = /projects/pro1/resources/web/**
    AntPathMatcher apm = new AntPathMatcher();
    String exactPath = apm.extractPathWithinPattern(bestMatchPattern, path);
    // will get exactPath = src/main/webapp
    .....
}

赞赏任何其他方法......