bfchengnuo / MyRecord

平时充电做的笔记,一个程序猿的自我修养.
https://bfchengnuo.com/MyRecord/
33 stars 8 forks source link

SpringMVC中使用PathVariable遇到特殊字符问题 #74

Open bfchengnuo opened 2 years ago

bfchengnuo commented 2 years ago

包括、不限于 『/』『=』『.』『#』

bfchengnuo commented 2 years ago

一般情况下的快捷解决办法,使用通配符例如 @GetMapping("/m3u8/{path:.+}")

特殊情况,需要匹配 / 字符的时候就比较麻烦,示例:

@RequestMapping(value = "/modules/{moduleBaseName}/**", method = RequestMethod.GET) 
@ResponseBody 
public String moduleStrings(@PathVariable String moduleBaseName, HttpServletRequest request) { 
    final String path = 
      request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString(); 
    final String bestMatchingPattern = 
      request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString(); 

    String arguments = new AntPathMatcher().extractPathWithinPattern(bestMatchingPattern, path); 

    String moduleName; 
    if (null != arguments && !arguments.isEmpty()) { 
     moduleName = moduleBaseName + '/' + arguments; 
    } else { 
     moduleName = moduleBaseName; 
    } 

    return "module name is: " + moduleName; 
} 

https://www.cnblogs.com/xiaoyii/p/10685349.html