@DeleteMapping

Yuno·2024년 8월 18일

Spring Framework 에서 HTTP DELETE 요청을 처리하기 위해 사용되는 어노테이션.
주로 리소스를 삭제하는 작업에 사용되며, @RequestMapping(method = RequestMethod.DELETE) 의 축약형


👉 기본 사용

@RestController
@RequestMapping("/api")
public class MyController {
	
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> deleteResource(@PathVariable Long id) {
    	// id에 해당하는 리소스 삭제
        // 삭제 로직 구현
        return ResourceEntity.ok("Resource with ID " + id + " has been deleted.");
    }
}
  • @RestController 는 이 클래스가 RESTful 웹 서비스의 컨트롤러임을 나타냄
  • @RequestMapping("/api") 는 클래스 수준의 URL 패턴을 설정함
  • @DeleteMapping("/delete/{id}")/api/delete/{id} 로 들어오는 DELETE 요청을 처리함
  • @PathVariable 은 URL 경로 변수인 id 를 메서드의 매개변수로 바인딩함

👉 경로 변수 사용

특정 리소스를 식별하여 삭제하는 경우, 경로 변수를 사용할 수 있음

@RestController
@RequestMapping("/api")
public class UserController {

	@DeleteMapping("/users/{userId}")
    public ResponseEntity<String> deleteUser(@PathVariable Long userId) {
    	// userId에 해당하는 사용자 삭제
        return ResponseEntity.ok("User with ID " + userId + " has been deleted.");
    }
}
  • @PathVariable 을 사용하여 URL 경로에 포함된 userId 를 메서드 매개변수로 가져옴
  • 메서드 내부에서 userId 에 해당하는 리소스를 찾아 삭제하는 로직을 구현함

👉 응답 처리

삭제 요청 후, 다양한 응답을 반환할 수 있음. 성공적으로 삭제한 경우 200 OK 또는 204 No Content 상태를 반환할 수 있으며, 삭제할 리소스를 찾지 못한 경우 404 Not Found를 반환할 수 있음.

@RestController
@RequestMapping("/api")
public class ProdectController {
	
    @DeleteMapping("/products/{productId}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long productId) {
    	boolean deleted = productService.deleteProductById(productId);
        if (deleted) {
        	return ResponseEntity.noContent().build(); // 204 No Content
        } else {
        	return ResponseEntity.notFound().build(); // 404 Not Found
        }
    }
}
  • deleteProductById 메서드는 제품을 삭제하고, 성공 여부를 반환
  • 삭제가 성공하면 204 No Content 응답을, 실패하면 404 Not Found 응답을 반환

👉 복수의 리소스 삭제

한번에 여러 리소스를 삭제해야 하는 경우도 있음. 이때 @RequestParam 을 사용하여 쿼리 파라미터로 여러 ID를 받아 처리할 수 있음.

@RestController
@RequestMapping("/api")
public class BulkDeleteController {
	
    @DeleteMapping("/bulk-delete")
    public ResponseEntity<String> deleteMultipleResource(@RequestParam List<Long> ids) {
    	// 전달받은 ids 목록에 있는 리소스들 삭제
        return ResponseEntity.ok("Resources with IDs " +ids + " have been deleted");
    }
}
  • @RequestParam 을 사용해 쿼리 파라미터로 전달된 ID 리스트를 받아옴
  • 해당 ID 목록에 포함된 모든 리소스를 삭제하는 로직을 구현함
profile
Hello World

0개의 댓글