I need to write a Spring RestController that catches URLs made up by an arbitrary number of variables. Specifically, I need to map something like /{id1}/{id2}/some/dynamic/path/ alongside "normal" mappings such as /{someid} and/or /. /{id1}/{id2}/some/dynamic/path/ needs to be mapped to three parameters id1, id2, and some/dynamic/path, where the path can be anything from zero to 10 segments.

Maybe I got something wrong, but the catchAll() I implemented for this case always catches all - and ignores the other paths. How do I solve this?

Here is my code:

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

What I need is:

  • Map / to staticPath()
  • Map /42 to pathWithOneVar(): var someid = 42
  • Map /1/2 to catchAll(): var id1 = 1, var id2 = 2, var path = ""
  • Map /1/2/a to catchAll(): var id1 = 1, var id2 = 2, var path = "a"
  • Map /1/2/a/b/c/d/e/f/g/h/i/j/k to catchAll(): var id1 = 1, var id2 = 2, var path = "a/b/c/d/e/f/g/h/i/j/k"

0 Answers