我需要编写一个Spring RestController来捕获由任意数量的变量组成的URL。具体来说,我需要将/{id1}/{id2}/some/dynamic/path/
之类的内容与/{someid}
和/或/
之类的“普通”映射一起进行映射。
/{id1}/{id2}/some/dynamic/path/
需要映射到三个参数id1
,id2
和some/dynamic/path
,其中路径可以是从0到10段的任何内容。
也许我做错了什么,但是我为这种情况实现的catchAll()
总是能抓住一切-却忽略了其他路径。我该如何解决?
这是我的代码:
@RestController
@RequestMapping("/")
public class MyController
{
@GetMapping("/")
@ResponseBody
public ResponseEntity staticPath()
{
return new ResponseEntity<String>("1", HttpStatus.OK);
}
@GetMapping("/{someid}")
@ResponseBody
public ResponseEntity pathWithOneVar(@PathVariable String someid)
{
return new ResponseEntity<String>("2", HttpStatus.OK);
}
@RequestMapping("{id1}/{id2}/**")
@ResponseBody
public ResponseEntity catchAll(@PathVariable String id1, @PathVariable String id2)
{
HttpServletRequest requestServlet = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
requestServlet.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
return new ResponseEntity<String>("3", HttpStatus.OK);
}
}
我需要的是
/
映射到staticPath()/42
映射到pathWithOneVar():var someid
= 42 /1/2
映射到catchAll():var id1
= 1,var id2
= 2,var path
=“” /1/2/a
映射到catchAll():var id1
= 1,var id2
= 2,var path
=“ a” /1/2/a/b/c/d/e/f/g/h/i/j/k
映射到catchAll():var id1
= 1,var id2
= 2,var path
=“ a / b / c / d / e / f / g / h / i / j / k”