SpringBoot中的@PathVariable,带有URL中的斜杠
我必须在SpringBoot应用程序中使用@PathValiable从URL获取params。 这些参数常常有斜线 。 我无法控制用户在URL中输入的内容,因此我希望获得他输入的内容然后我可以处理它。
我已经在这里查看了材料和答案,我不认为对我来说好的解决方案是要求用户以某种方式编码输入参数。
SpringBoot代码很简单:
@RequestMapping("/modules/{moduleName}") @ResponseBody public String moduleStrings (@PathVariable("moduleName") String moduleName) throws Exception { ... }
所以URL例如如下:
http://localhost:3000/modules/...
问题是param 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中输入的所有内容吗?
如果有人告诉我处理此类问题的好方法是什么。
此代码获取完整路径:
@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; }
基于PJMeisch的答案,我已经为我的案例找到了简单的解决方案。 它还允许考虑URL参数中的几个斜杠 。 它也不允许使用反斜杠,如上一个答案中所述。
@RequestMapping(value = "/modules/**", method = RequestMethod.GET) @ResponseBody public String moduleStrings(HttpServletRequest request) { String requestURL = request.getRequestURL().toString(); String moduleName = requestURL.split("/modules/")[1]; return "module name is: " + moduleName; }
@RequestMapping("/modules/**")