【问题标题】:How does Spring MVC @PathVariable receive parameters with multiple '/'?Spring MVC @PathVariable 如何接收带有多个'/'的参数?
【发布时间】:2018-11-06 10:07:09
【问题描述】:

我正在开发用于管理图像的文件上传小部件。

我希望Spring MVC中可以通过@PathVariable接收图片路径,比如http://localhost:8080/show/img/20181106/sample.jpg而不是http://localhost:8080/show?imagePath=/img/20181106/sample.jpg

但是/会被Spring MVC解析,访问时总是返回404。

有什么好的办法吗?

【问题讨论】:

  • 你应该使用这种格式RequestMappinghttp://localhost:8080/show/{imagePath:.+}
  • 如果imagePath中有多个/,这种格式仍然返回404。

标签: java spring spring-mvc path-variables


【解决方案1】:

你可以像下面这样使用。

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

这里.+ 是一个正则表达式匹配,它不会截断您路径中的.jpg。

【讨论】:

    【解决方案2】:

    很抱歉这么说,但我认为@Alien 的回答并不能回答问题:它只处理@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);
    
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-06
      • 2011-12-21
      • 1970-01-01
      • 2013-04-26
      • 2013-11-17
      • 2020-02-17
      • 2023-03-05
      相关资源
      最近更新 更多