Spring MVC @PathVariable 如何接收带多个'/'的参数?
How does Spring MVC @PathVariable receive parameters with multiple '/'?
我正在开发一个用于管理图像的文件上传小部件。
我希望可以通过 Spring MVC 中的 @PathVariable
接收图像路径,例如 http://localhost:8080/show/img/20181106/sample.jpg
而不是 http://localhost:8080/show?imagePath=/img/20181106/sample.jpg
。
但是/
会解析SpringMVC,访问的时候总是return404。
有什么好的解决方法吗?
您可以像下面这样使用。
@RequestMapping(value = "/show/{path:.+}", method = RequestMethod.GET)
public File getImage(@PathVariable String path) {
// logic goes here
}
这里 .+
是正则表达式匹配,它不会截断您路径中的 .jpg。
抱歉这么说,但我认为@Alien 的回答没有回答问题:它只处理 @PathVariable
中的点 .
的情况,而不处理 @PathVariable
中的点的情况斜线 /
.
我曾经遇到过这个问题,这是我解决它的方法,它不是很优雅,但我认为还可以:
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);
...
}
我正在开发一个用于管理图像的文件上传小部件。
我希望可以通过 Spring MVC 中的 @PathVariable
接收图像路径,例如 http://localhost:8080/show/img/20181106/sample.jpg
而不是 http://localhost:8080/show?imagePath=/img/20181106/sample.jpg
。
但是/
会解析SpringMVC,访问的时候总是return404。
有什么好的解决方法吗?
您可以像下面这样使用。
@RequestMapping(value = "/show/{path:.+}", method = RequestMethod.GET)
public File getImage(@PathVariable String path) {
// logic goes here
}
这里 .+
是正则表达式匹配,它不会截断您路径中的 .jpg。
抱歉这么说,但我认为@Alien 的回答没有回答问题:它只处理 @PathVariable
中的点 .
的情况,而不处理 @PathVariable
中的点的情况斜线 /
.
我曾经遇到过这个问题,这是我解决它的方法,它不是很优雅,但我认为还可以:
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);
...
}