SpringBoot中的@PathVariable,带有URL中的斜杠 [英] @PathVariable in SpringBoot with slashes in URL

查看:7572
本文介绍了SpringBoot中的@PathVariable,带有URL中的斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在SpringBoot应用程序中使用@PathValiable从URL获取params。这些参数通常有斜杠。我无法控制用户在URL中输入的内容,因此我希望得到他输入的内容然后我可以处理它。

I have to get params from URL using @PathValiable in SpringBoot application. These params often have slashes. I don't have a control about what a user would enter in URL so I would like to get what he has entered and then I can handle with it.

我已经在这里查看了材料和答案,我不认为对我来说好的解决方案是让用户以某种方式编码输入参数。

SpringBoot代码很简单:

The SpringBoot code is simple:

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

  ...

}

所以URL例如如下:

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

问题在于param moduleName 经常有斜杠。
例如,

The issue is that the param moduleName often has slashes. For example,

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

因此用户可以定义输入:

So a user definetely can enter:

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

这是否可以获得所有内容用户在 / modules / 之后输入了网址?

Is this possible to get everything what a user has entered in URL after /modules/?

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

If anyone tell me what are the good ways to handle such issue.

推荐答案

此代码获取完整路径:

@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;
}

这篇关于SpringBoot中的@PathVariable,带有URL中的斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆