Reading @Path Variables – Spring Rest

While making a call to Spring REST service, suppose in the URL we need to pass some parameters.

Like below. If you see a parameter 100 is passed to the REST path http://localhost:8080/employees

It is a GET request.

Now let’s look at the controller which handles this kind of path parameter.

com.techfinanceworld.restapp.controller;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("employees")
public Class EmpController{

@GetMapping(path="/{empId}")
public String getEmployee(@PathVariable String empId)
{
      return "Get Employee Was Called with the EmpId";
}

@PostMapping
public String CreateEmployee()
{
      return "Create Employee Was Called";
}

}

If you see the above controller class since it is get request, the method annotated with @GetMapping handles the request.

path=”/{empId}” signifies that the method should read a path value after /employees/.

@PathVariable reads that value to a String variable empId and that variable is used for further processing in the method.