How to add methods in controller to handle POST, GET, PUT, DELETE HTTP requests in Spring Boot
In this tutorial we are going to learn about creating methods in controller to handle POST, GET, PUT, DELETE HTTP requests in Spring Boot application.
So the first method that I want to define is to get user information. At this moment I will return a String value like “Hello” rather than proper user details.
We’ll need to work on it more because get user method needs to accept user ID which can be used to query database for user details and then we need to return a JSON payload with user details.
But at this moment we will return String to make this get user respond to HTTP GET request, we need to bind this method to HTTP GET request and for this we need to use this annotation called @GetMapping.
Now let’s handle HTTP POST request by creating a method called create user and annotate this method using @PostMapping.
In the similar fashion we are going to create methods to update and delete user i.e. update user and delete user and annotate these methods with @PutMapping and @DeleteMapping.
Sample Code Snippet:
package com.behindjava.tutorial.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("users")
public class UserController {
@PostMapping
public String createUser()
{
return "USER CREATED";
}
@PutMapping
public String updateUser()
{
return "USER UPDATED";
}
@GetMapping
public String getUser()
{
return "USER's FETCHED";
}
@DeleteMapping
public String deleteUser()
{
return "USER DELETED";
}
}
Now we have a very simple Restful web service which defines basic crud operations for creating, updating, fetching and deleting users and you can test this by running the application in spring tool suite, from the Postman you can select the type of request and send this HTTP request and the Restful web service will respond.