SpringBoot 中的@PathVariable,URL 中带有斜杠 [英] @PathVariable in SpringBoot with slashes in URL
问题描述
我必须在 SpringBoot 应用程序中使用 @PathValiable 从 URL 获取参数.这些参数通常带有斜杠.我无法控制用户在 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 将如下所示:
So the URL for example would be the following:
http://localhost:3000/modules/...
问题是参数 moduleName 经常有斜线.例如,
The issue is that the param moduleName often has slashes. For example,
metadata-apicb-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-apicb-metadata-services
是否可以在 /modules/ 之后获取用户在 URL 中输入的所有内容?
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.
推荐答案
这段代码获取完整路径:
This code gets the complete 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;
}
这篇关于SpringBoot 中的@PathVariable,URL 中带有斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!