@PutMapping and @DeleteMapping help your web app handle updates and deletions of data easily. They connect web requests to your code actions.
0
0
@PutMapping and @DeleteMapping in Spring Boot
Introduction
When you want to update existing information like changing a user's email.
When you need to delete a resource, such as removing a product from a list.
When building REST APIs that follow common web standards for update and delete actions.
Syntax
Spring Boot
@PutMapping("/path") public ResponseEntity<Type> updateMethod(@RequestBody Type data) { // update logic } @DeleteMapping("/path/{id}") public ResponseEntity<Void> deleteMethod(@PathVariable Long id) { // delete logic }
@PutMapping is for updating data, usually with a full new version of the resource.
@DeleteMapping is for removing data identified by a path variable like an ID.
Examples
Updates a user by ID with new user data sent in the request body.
Spring Boot
@PutMapping("/users/{id}") public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) { // update user with id }
Deletes a user identified by the ID in the URL path.
Spring Boot
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
// delete user by id
}
Sample Program
This simple controller stores users in memory. You can update a user's name or delete a user by their ID using @PutMapping and @DeleteMapping.
Spring Boot
import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class UserController { private Map<Long, String> users = new HashMap<>(); public UserController() { users.put(1L, "Alice"); users.put(2L, "Bob"); } @PutMapping("/users/{id}") public ResponseEntity<String> updateUser(@PathVariable Long id, @RequestBody String newName) { if (!users.containsKey(id)) { return ResponseEntity.notFound().build(); } users.put(id, newName); return ResponseEntity.ok("User updated to: " + newName); } @DeleteMapping("/users/{id}") public ResponseEntity<String> deleteUser(@PathVariable Long id) { if (!users.containsKey(id)) { return ResponseEntity.notFound().build(); } users.remove(id); return ResponseEntity.ok("User deleted with id: " + id); } }
OutputSuccess
Important Notes
Use @PutMapping for full updates; partial updates usually use @PatchMapping.
Always check if the resource exists before updating or deleting to avoid errors.
Return proper HTTP status codes like 404 if the resource is not found.
Summary
@PutMapping handles updating existing data via HTTP PUT requests.
@DeleteMapping handles deleting data via HTTP DELETE requests.
Both help build clear and standard REST APIs in Spring Boot.