小编典典

SpringBoot中的@ PathVariable,URL中带有斜线

spring-boot

我必须在SpringBoot应用程序中使用@PathValiable从URL获取参数。这些参数通常带有 斜线
。我无法控制用户在URL中输入的内容,因此我想获取他输入的内容,然后我就可以对其进行处理。

我已经在这里浏览过材料和答案,我认为对我而言,好的解决方案不是要求用户以某种方式对输入的参数进行编码。

SpringBoot代码很简单:

@RequestMapping("/modules/{moduleName}")
@ResponseBody
public String moduleStrings (@PathVariable("moduleName") String moduleName) throws Exception {

  ...

}

因此,URL如下所示:

http://localhost:3000/modules/...

问题在于,参数 moduleName 通常带有斜杠。例如,

metadata-api\cb-metadata-services OR
app-customization-service-impl\\modules\\expand-link-schemes\\common\\app-customization-service-api

因此,用户可以输入:

http://localhost:3000/modules/metadata-api\cb-metadata-services

是否可以获取 / modules / 之后用户在URL中输入的所有内容?

如果有人告诉我什么是解决此类问题的好方法。


阅读 1050

收藏
2020-05-30

共1个答案

小编典典

此代码获取完整路径:

@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;
}
2020-05-30