Search code examples
javaspringmavenspring-mvcspring-restcontroller

Can't reach by link Spring


I am new with Spring framework and right now I'm trying to learn few things but facing a problem. (Learning from this tutorial https://spring.io/guides/gs/rest-service/). So by default, I can launch my program via localhost../greeting, but what if I want to change the name not like in the website with /greeting?name=xx, but for example /greeting/Tom.. (/greeting/{name})


Solution

  • In GreetingController:

    Instead of this:

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name)
    

    Implement this:

    @RequestMapping("/greeting/{name}") 
    public Greeting greeting(@PathVariable("name") String name)
    

    for optional path variable:

    @PathVariable Optional<String > name