Spring MVC Tutorial
Core Spring MVC
Spring MVC - Annotation
Spring MVC - Form Handling
Spring MVC with JSTL
Spring MVC with REST API
Spring MVC with Database
In Spring (specifically, Spring MVC), you can handle HTTP DELETE requests using the @DeleteMapping
annotation. This is typically used for RESTful web services when you want to delete a resource.
Here's a step-by-step guide to making and handling a DELETE request in Spring:
First, you'll need a controller where you will handle the DELETE request:
@RestController @RequestMapping("/api/items") public class ItemController { // This could be a service that talks to a database or other data source @Autowired private ItemService itemService; @DeleteMapping("/{id}") public ResponseEntity<?> deleteItem(@PathVariable Long id) { boolean isRemoved = itemService.removeItem(id); if (!isRemoved) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return new ResponseEntity<>(HttpStatus.OK); } }
In this example:
@DeleteMapping("/{id}")
: Maps HTTP DELETE requests for /api/items/{id}
to the deleteItem
method. {id}
is a path variable that represents the ID of the item to be deleted.@PathVariable Long id
: Extracts the {id}
from the URL and passes it as a method parameter.Here's a simple ItemService
implementation to complement the controller. In a real-world application, this service would typically interact with a database or other data source.
@Service public class ItemService { // For simplicity, let's use a concurrent map to simulate a database. private Map<Long, String> items = new ConcurrentHashMap<>(); public boolean removeItem(Long id) { return items.remove(id) != null; } // Add other service methods if necessary... }
To make a DELETE request, you can use tools like curl
, Postman, or your web application's front-end code. Here's how you can make a DELETE request using curl
:
curl -X DELETE http://localhost:8080/api/items/1
This command attempts to delete the item with ID 1
.
If you're using JavaScript to make requests from the front-end, you can use the Fetch API, jQuery, Axios, or other libraries. Here's an example using the Fetch API:
fetch('http://localhost:8080/api/items/1', { method: 'DELETE', }) .then(response => { if (response.ok) { console.log("Item deleted successfully"); } else { console.error("Error deleting item", response.status); } }) .catch(error => console.error("Network error:", error));
Make sure you handle appropriate security and validation mechanisms before deleting data, especially if you're working with critical data or in a production environment.
Spring MVC DELETE request example:
Description: Handling a DELETE request in Spring MVC involves creating a controller method annotated with @DeleteMapping
and specifying the resource to delete.
Code snippet (Java):
@Controller @RequestMapping("/api") public class ApiController { @DeleteMapping("/delete/{id}") public ResponseEntity<String> deleteResource(@PathVariable Long id) { // Logic to delete the resource with the given id // ... return ResponseEntity.ok("Resource deleted successfully"); } }
RestTemplate DELETE request in Spring:
Description: Making a DELETE request using RestTemplate involves using the delete()
method and specifying the URL and any path variables.
Code snippet (Java):
RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/api/delete/{id}"; restTemplate.delete(url, 123L);
Spring WebClient DELETE example:
Description: Using WebClient for DELETE requests involves creating a WebClient instance and using the delete()
method.
Code snippet (Java):
WebClient webClient = WebClient.create("http://localhost:8080"); webClient .delete() .uri("/api/delete/{id}", 456L) .retrieve() .bodyToMono(String.class) .block();
Delete mapping in Spring Controller:
Description: Using @DeleteMapping
annotation in a Spring Controller provides a convenient way to handle DELETE requests for a specific mapping.
Code snippet (Java):
@Controller @RequestMapping("/resources") public class ResourceController { @DeleteMapping("/delete/{id}") public ResponseEntity<String> deleteResource(@PathVariable Long id) { // Logic to delete the resource with the given id // ... return ResponseEntity.ok("Resource deleted successfully"); } }
Spring Data JPA delete method:
Description: Spring Data JPA provides a convenient way to delete entities using the deleteById()
method.
Code snippet (Java):
public interface ResourceRepository extends JpaRepository<Resource, Long> { // Spring Data JPA automatically generates deleteById method }
Usage:
resourceRepository.deleteById(789L);
HTTP DELETE request in Spring Rest API:
Description: Handling a DELETE request in a Spring Rest API involves using @DeleteMapping
in a controller method.
Code snippet (Java):
@RestController @RequestMapping("/api") public class ApiController { @DeleteMapping("/delete/{id}") public ResponseEntity<String> deleteResource(@PathVariable Long id) { // Logic to delete the resource with the given id // ... return ResponseEntity.ok("Resource deleted successfully"); } }
Spring MVC delete request with PathVariable:
Description: Handling a DELETE request in Spring MVC with a PathVariable involves specifying the path variable in the @DeleteMapping
annotation.
Code snippet (Java):
@Controller @RequestMapping("/resources") public class ResourceController { @DeleteMapping("/delete/{id}") public ResponseEntity<String> deleteResource(@PathVariable Long id) { // Logic to delete the resource with the given id // ... return ResponseEntity.ok("Resource deleted successfully"); } }
RestAssured DELETE request in Spring Boot:
Description: Using RestAssured for DELETE requests in Spring Boot involves specifying the URL and path variables.
Code snippet (Java):
RestAssured.baseURI = "http://localhost:8080"; given() .pathParam("id", 987) .when() .delete("/api/delete/{id}") .then() .statusCode(200);
Spring DELETE request with RequestMapping:
Description: Handling a DELETE request in Spring with @RequestMapping
involves specifying the method as DELETE
and the path.
Code snippet (Java):
@Controller @RequestMapping("/api") public class ApiController { @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE) public ResponseEntity<String> deleteResource(@PathVariable Long id) { // Logic to delete the resource with the given id // ... return ResponseEntity.ok("Resource deleted successfully"); } }