by BehindJava
How to handle HTTP DELETE request to delete user details in Spring Boot
In this tutorial we are going to learn about deleting the user details stored in a Map using DELETE request.
Firstly, we will send a DELETE request from postman to delete user details based on user Id Now in the controller class we will specify @DeleteMapping as shown in the below code snippet.
Sample code Snippet:
import java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.behindjava.tutorial.model.UserModel;
@RestController
@RequestMapping("/users")
public class UserController {
HashMap<String, UserModel> user;
@PostMapping(produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }, consumes = {
MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public ResponseEntity<UserModel> createUser(@Valid @RequestBody UserModel us) {
UserModel um = new UserModel();
um.setEmail(us.getEmail());
um.setFirstname(us.getFirstname());
um.setLastname(us.getLastname());
um.setUserId(us.getUserId());
if (user == null)
user = new HashMap<>();
user.put(us.getUserId(), um);
return new ResponseEntity<UserModel>(um, HttpStatus.CREATED);
}
@GetMapping(path = "/{userId}", produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<UserModel> getUser(@PathVariable String userId) {
if (user.containsKey(userId)) {
return new ResponseEntity<UserModel>(user.get(userId), HttpStatus.CREATED);
} else {
return new ResponseEntity<UserModel>(HttpStatus.NO_CONTENT);
}
}
@PutMapping(path = "/{userId}", produces = { MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE }, consumes = { MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE })
public UserModel updateUser(@Valid @PathVariable String userId, @RequestBody UserModel us) {
UserModel usr = user.get(userId);
usr.setFirstname(us.getFirstname());
usr.setLastname(us.getLastname());
usr.setEmail(us.getEmail());
user.put(userId, usr);
return usr;
}
@DeleteMapping(path = "/{Id}")
public ResponseEntity<Void> deleteUser(@PathVariable String Id) {
user.remove(Id);
return ResponseEntity.noContent().build();
}
}
Once the controller is ready send DELETE request using postman and we get the below response shown in the image.