3

Is there a way to math the remaining URL part in a Spring controller?

i.e. if my route is /user/{userId}/* can I get the userId param and the rest of the url? The * part?

For example for /user/1/this/is/a/path.html?a=b I should get userId = 1 and userUrl = /this/is/a/path.html?a=b

I've seen some solutions and did some Googling but they seem kind of strange way to do it (most likely due to the answers being for an older version of Spring) So in a more recent version how can this e done in a clean way?

daniels
  • 18,416
  • 31
  • 103
  • 173

1 Answers1

6

Yes, here is an example adapted from this answer

@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);
    }

In this example userId = 1 and finalPath = this/is/a/path.html

Community
  • 1
  • 1
Kyle Anderson
  • 6,801
  • 1
  • 29
  • 41