When you work with Spring MVC and you have a RequestMapping to something likeĀ /elements/{id}, this binding will not work for elements having slash in their ids. This tutorial shows how to resolve resolve Spring MVC path variable with slash.
Let’s consider this example :
1 2 3 4 |
@GetMapping("/elements/{id}") public String getElementById(@PathVariable String id, HttpServletRequest request) { return elementService.getById(id); } |
The idĀ CATEGORY1/CATEGORY1_1/ID will not work. Below the solution.
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// /elements/CATEGORY1/CATEGORY1_1/ID @GetMapping("/elements/**") public String getElementById(HttpServletRequest request) { String id = extractId(request); return elementService.getById(id); } private String extractId(HttpServletRequest request) { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); // /elements/CATEGORY1/CATEGORY1_1/ID String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); // /elements/** return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path); // CATEGORY1/CATEGORY1_1/ID } |
References