javaspringcontrollerdynamic-url

Use @RequestMapping with Dynamic URL at Controller Level


I've been doing my fair amount of research through Stack Overflow and Google and the closest I found was something like this post but still it does not answer my question. The documentation for @RequestMapping doesn't say anything about the possibilities of using dynamic URLs at the controller level so I was wondering if something like the code below is possible:

@RequestMapping("/something/{somethingsId}")
public class ExampleController{
    //Some methods mapping to some endpoints that start with /something/{somethingsId}
    @GetMapping("/getOtherThing")
    public ResponseEntity<> getOtherThing(@PathVariable("somethingsId")String somethingsId){
        //Do something with somethingsId
    }
}

This is just an example code of what I intend to achieve. I want to do this to separate some functionalities into different controllers that need this somethingsId to be able to work but I don't know if what I want is possible or if I will have to content myself with repeating the same thing in every method of the controller to get that "somethingsId" path variable.

Thank you in advance for your answers.


Solution

  • Yes you can achive it, follow the same way as I mentioned

    @Controller
    @RequestMapping("/owners/{ownerId}")
    public class Test {
    
        @RequestMapping("/pets/{petId}")
        public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
            System.out.println("ownerId "+ownerId+" petId "+petId);
        }
    }