How to resolve slashes in path variable in Spring MVC

Today I stumbled across a problem where a slash can occur in a path variable.

The contents of the path variable can look like this:
1/53879d5c-b07b-44f2-9a77-b99f67bb8481 or even 1/2/53879d5c-b07b-44f2-9a77-b99f67bb8481

At the backend, I need the full path in a variable because the path can contain several slashes but does not have to.

Let’s have a look at this as a code example to make it clear.

@GetMapping("/rest/{path}")
public @ResponseBody ResponseEntity<Container> getContainerByPath(@PathVariable String path) {

  return containerService.getByPath(path);

}

The path /1/53879d5c-b07b-44f2-9a77-b99f67bb8481 will not work.

The solution is HttpServletRequest.

// /rest/1/53879d5c-b07b-44f2-9a77-b99f67bb8481
@GetMapping("/rest/**")
public @ResponseBody ResponseEntity<Container> getContainerByPath(HttpServletRequest request) {

  String path = extractPath(request);

  return containerService.getByPath(path);

}
private String extractPath(HttpServletRequest request) {

  String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
  String matchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); // /rest/**

  return new AntPathMatcher().extractPathWithinPattern(matchPattern, path); // 1/53879d5c-b07b-44f2-9a77-b99f67bb8481
}

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *