Search code examples
javaspringrestspring-mvcurl-mapping

how to get part of request URI into path variable in spring mvc rest services


my service code :

@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 {
} 

And my request will be

  • /projects/pro1/resources/web/src/main/webapp
  • /projects/pro1/resources/web/src/main/test/com/pro1...

and is it possible to get "src/main/webapp/../....." into "path" variable


Solution

  • Spring provide three patterns in the url handler mappings

    • ? - zero or one charecter
    • *- one charecter
    • ** - one or more charecters

    And below approach resolved my issue

    @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
        .....
    }
    

    Any other approaches are appreciated....