Kir*_* Ch 12 java rest url path-variables spring-boot
我必须在SpringBoot应用程序中使用@PathValiable从URL获取params.这些参数常常有斜线.我无法控制用户在URL中输入的内容,因此我希望获得他输入的内容然后我可以处理它.
我已经在这里查看了材料和答案,我不认为对我来说好的解决方案是要求用户以某种方式编码输入的参数.
SpringBoot代码很简单:
@RequestMapping("/modules/{moduleName}")
@ResponseBody
public String moduleStrings (@PathVariable("moduleName") String moduleName) throws Exception {
...
}
Run Code Online (Sandbox Code Playgroud)
所以URL例如如下:
http://localhost:3000/modules/...
Run Code Online (Sandbox Code Playgroud)
问题是param moduleName经常有斜杠.例如,
metadata-api\cb-metadata-services OR
app-customization-service-impl\\modules\\expand-link-schemes\\common\\app-customization-service-api
Run Code Online (Sandbox Code Playgroud)
因此用户可以定义输入:
http://localhost:3000/modules/metadata-api\cb-metadata-services
Run Code Online (Sandbox Code Playgroud)
这可能是在/ modules /之后获取用户在URL中输入的所有内容吗?
如果有人告诉我处理这个问题的好方法是什么.
P.J*_*sch 13
此代码获取完整路径:
@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;
}
Run Code Online (Sandbox Code Playgroud)
Kir*_* Ch 12
根据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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11079 次 |
| 最近记录: |