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

Viewed 239

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?

2 Answers

You can use like below.

@RequestMapping(value = "/show/{path:.+}", method = RequestMethod.GET)
public File getImage(@PathVariable String path) {
        // logic goes here
}

Here .+ is a regexp match, it will not truncate .jpg in your path.

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

    ...
}
Related