How does Spring MVC @PathVariable receive parameters with multiple '/'?

Jimmy Wang :

I was working on a file upload widget for managing images.

I wish that image paths can be received via @PathVariable in Spring MVC, such as http://localhost:8080/show/img/20181106/sample.jpg instead of http://localhost:8080/show?imagePath=/img/20181106/sample.jpg.

But / will be resolved Spring MVC, and it will always return 404 when accessing.

Is there any good way around this?

Romain Warnan :

Sorry to say that, but I think the answer of @Alien does not the answer the question : it only handle the case of a dot . in the @PathVariable but not the case of slashes /.

I had the problem once and here is how I solved it, it's not very elegant but stil ok I think :

private AntPathMatcher antPathMatcher = new AntPathMatcher();

@GetMapping("/show/**")
public ... image(HttpServletRequest request) {
    String uri = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    String path = antPathMatcher.extractPathWithinPattern(pattern, uri);

    ...
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92527&siteId=1