Rest Controller Class in Spring

Spread the love

It is a class which handles the rest web service calls and returns the appropriate response.

Let’s design a simple crud controller class and see what are the different annotations used in it.

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") //http://localhost:8080/employees
public Class EmpController{

@GetMapping
public String getEmployee()
{
      return "Get Employee Was Called";
}

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

@PutMapping
public String UpdateEmployee()
{
      return "Update Employee Was Called";
}

@DeleteMapping
public String DeleteEmployee()
{
      return "Delete Employee Was Called";
}

}

As seen above, it is a simple crud class with 4 HTTP request types which are GET, POST, PUT and DELETE.

The methods are not taking any parameters as well as not returning any json. Just returning a simple string. So the example is just for an understanding point of view.

The below 2 annotations are used:

@RestController – It would register the class a REST controller and it would be able receive HTTP requests.

@RequestMapping – When the url is accessed, the RequestMapping reads the url and checks if it is delegated to handle the request. If you see the url which clients would use to send requests for example, it is http://localhost:8080/employees. @RequestMapping is configured to accept any path which has employees in the url.

So the requests with abobe URL would be serviced by the RestController class.