Path variable with Spring Boot

In the last post "Query parameter handling with Spring Boot"  we have seen how to provide the query parameter . I will be using same project and extending HelloController for this.

For RESTful service to access specific resource via their Id/name we would also need path variable so that those can be accessed with specific path like "hello/{id}".

This can be achieved with @ PathVariable annotation. Replace the HelloController.java with below code.

package hello;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello/{id}")
    public String sayHello(@PathVariable("id") String id) {
        return  String.format("Hello world with Spring Boot !!! Id used here %s", id);
    }
}

Run the application and hit http://localhost:8080/hello/myId in your browser. You should get "Hello world with Spring Boot !!! Id used here myId" in return. 

No comments:

Post a Comment

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...