구현 환경 : InteliJ, Spring Boot
담당 파트 : 백엔드
소스 코드 역할 :
- REST API를 통해 좌표 데이터를 처리하는 컨트롤러. 클라이언트(예: 웹 브라우저 또는 모바일 앱)가 좌표 데이터를 요청하거나 저장할 때, 이 API를 통해 백엔드와 통신하게 된다.
- 좌표 데이터를 조회, 저장, 삭제하는 기능 제공
- HTTP 요청에 따라 적절한 서비스를 호출하여 결과를 반환
핸들러 메소드 : 각 메소드는 HTTP 요청에 따라 좌표 데이터를 처리하는 역할을 한다.
- @GetMapping: GET 요청을 처리. 좌표 목록을 조회하거나 특정 ID에 해당하는 좌표 데이터를 조회하는 기능을 수행.
- getAllCoordinates: 모든 좌표 데이터를 조회하여 반환 (HTTP 200 OK)
- getCoordinateById: 특정 ID에 해당하는 좌표 데이터를 반환 (HTTP 200 OK 또는 404 NOT FOUND)
- @PostMapping: POST 요청을 처리. 새로운 좌표 데이터를 저장하는 기능을 수행.
- createCoordinate: 새로운 좌표 데이터를 저장하고, 생성된 데이터를 반환 (HTTP 201 CREATED)
- @DeleteMapping: DELETE 요청을 처리. 특정 ID에 해당하는 좌표 데이터를 삭제하는 기능을 수행.
- deleteCoordinate: ID에 해당하는 좌표 데이터를 삭제 (HTTP 204 NO CONTENT 또는 404 NOT FOUND)
package com.example.coordapp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/coordinates")
public class CoordinateController {
private final CoordinateService coordinateService;
@Autowired
public CoordinateController(CoordinateService coordinateService) {
this.coordinateService = coordinateService;
}
// 모든 좌표 조회
@GetMapping
public ResponseEntity<List<Coordinate>> getAllCoordinates() {
List<Coordinate> coordinates = coordinateService.getAllCoordinates();
return new ResponseEntity<>(coordinates, HttpStatus.OK);
}
// 특정 ID로 좌표 조회
@GetMapping("/{id}")
public ResponseEntity<Coordinate> getCoordinateById(@PathVariable Long id) {
Optional<Coordinate> coordinate = coordinateService.getCoordinateById(id);
return coordinate.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
// 새로운 좌표 저장
@PostMapping
public ResponseEntity<Coordinate> createCoordinate(@RequestBody Coordinate coordinate) {
Coordinate savedCoordinate = coordinateService.saveCoordinate(coordinate);
return new ResponseEntity<>(savedCoordinate, HttpStatus.CREATED);
}
// 좌표 삭제
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteCoordinate(@PathVariable Long id) {
Optional<Coordinate> coordinate = coordinateService.getCoordinateById(id);
if (coordinate.isPresent()) {
coordinateService.deleteCoordinate(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
<코드 설명>
package com.example.coordapp;
com.example.coordapp라는 패키지에 속해 있으며. 패키지는 Java에서 관련된 클래스들을 그룹화하여 관리하는 방식.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
import: 다른 클래스나 패키지에서 제공하는 기능을 사용할 수 있도록 해당 클래스들을 가져옵니다.
- org.springframework.beans.factory.annotation.Autowired: 스프링 프레임워크에서 **의존성 주입(DI)**을 위해 사용. 필요한 객체를 자동으로 주입받을 때 사용.
- org.springframework.http.HttpStatus: HTTP 상태 코드를 나타내기 위한 클래스. 성공, 실패, 권한 문제 등을 나타낼 때 사용.
- org.springframework.http.ResponseEntity: HTTP 응답 데이터를 나타내는 객체. 데이터와 함께 HTTP 상태 코드를 포함할 수 있다.
- org.springframework.web.bind.annotation.*: 스프링에서 제공하는 여러 가지 웹 관련 애너테이션을 가져온다. 예를 들어, @RestController, @RequestMapping, @GetMapping, @PostMapping 등이 포함돼있다.
- java.util.List: 여러 개의 좌표 데이터를 저장하는 리스트 자료형을 사용하기 위해 가져온다.
- java.util.Optional: 존재할 수도 있고 존재하지 않을 수도 있는 객체를 처리하기 위해 사용. 특정 좌표가 존재하지 않을 경우 null 대신 안전하게 처리할 수 있다.
@RestController
@RequestMapping("/coordinates")
public class CoordinateController {
- @RestController: 이 클래스가 RESTful 웹 서비스의 컨트롤러임을 나타냅니다. 스프링은 이 애너테이션을 통해 HTTP 요청을 처리하고, 그 결과를 JSON 형식으로 응답한다.
- @RequestMapping("/coordinates"): 이 클래스에서 처리하는 요청의 기본 URL 경로가 **/coordinates**임을 나타낸다. 즉, 이 컨트롤러의 모든 엔드포인트는 /coordinates로 시작한다.
- public class CoordinateController: 이 클래스의 이름은 CoordinateController이며, 좌표 데이터를 처리하는 컨트롤러이다.
private final CoordinateService coordinateService;
- private final: coordinateService라는 변수를 선언하며, 이 변수는 클래스 내에서만 사용되고, 한 번 초기화되면 변경되지 않는 final 속성을 가진다.
- CoordinateService: 좌표와 관련된 비즈니스 로직을 처리하는 서비스 클래스입니다. 이 클래스는 서비스 계층에서 데이터를 가공하고, 리포지토리와 상호작용하여 데이터를 처리하는 역할을 한다.
@Autowired
public CoordinateController(CoordinateService coordinateService) {
this.coordinateService = coordinateService;
}
- @Autowired: 스프링 프레임워크의 **의존성 주입(DI)**을 위해 사용. 스프링이 CoordinateService 객체를 자동으로 생성하고 이 컨트롤러에 주입한다.
- public CoordinateController(CoordinateService coordinateService): 생성자를 통해 CoordinateService를 주입받아 이 컨트롤러가 해당 서비스를 사용할 수 있게 만든다.
- this.coordinateService = coordinateService: 주입받은 CoordinateService를 클래스의 coordinateService 필드에 할당하여 이 컨트롤러에서 사용할 수 있도록 한다.
@GetMapping
public ResponseEntity<List<Coordinate>> getAllCoordinates() {
List<Coordinate> coordinates = coordinateService.getAllCoordinates();
return new ResponseEntity<>(coordinates, HttpStatus.OK);
}
- @GetMapping: HTTP GET 요청을 처리하는 메소드. /coordinates로 오는 GET 요청은 이 메소드가 처리한다.
- public ResponseEntity<List<Coordinate>> getAllCoordinates(): 모든 좌표 데이터를 조회하는 메소드.
- ResponseEntity<List<Coordinate>>: 이 메소드는 HTTP 응답 객체인 ResponseEntity를 반환하며, 이는 좌표 데이터 리스트와 함께 상태 코드(200 OK)를 포함한다.
- List<Coordinate> coordinates = coordinateService.getAllCoordinates(): 서비스 계층의 getAllCoordinates 메소드를 호출하여 모든 좌표 데이터를 조회하고, 이를 coordinates 리스트에 저장.
- return new ResponseEntity<>(coordinates, HttpStatus.OK): 조회한 좌표 데이터를 HTTP 응답으로 반환하며, 상태 코드는 200(OK)이다.
@GetMapping("/{id}")
public ResponseEntity<Coordinate> getCoordinateById(@PathVariable Long id) {
Optional<Coordinate> coordinate = coordinateService.getCoordinateById(id);
return coordinate.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
- @GetMapping("/{id}"): /coordinates/{id} 경로로 들어오는 GET 요청을 처리. URL의 {id} 부분이 경로 변수로 사용된다.
- @PathVariable Long id: 경로에 있는 {id} 값을 추출하여 메소드의 매개변수 id에 전달. 이 id는 특정 좌표를 조회하는 데 사용.
- Optional<Coordinate> coordinate = coordinateService.getCoordinateById(id): 서비스 계층에서 특정 id에 해당하는 좌표 데이터를 조회하고, 그 결과를 Optional 객체로 받는다. 이 객체는 좌표가 존재할 수도 있고, 존재하지 않을 수도 있기 때문에 안전하게 처리된다.
- return coordinate.map(value -> new ResponseEntity<>(value, HttpStatus.OK)): 만약 좌표가 존재한다면, 좌표 데이터를 포함한 응답을 반환하며, 상태 코드는 200(OK)이다.
- .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND)): 좌표가 존재하지 않을 경우, 404(NOT FOUND) 응답을 반환한다.
@PostMapping
public ResponseEntity<Coordinate> createCoordinate(@RequestBody Coordinate coordinate) {
Coordinate savedCoordinate = coordinateService.saveCoordinate(coordinate);
return new ResponseEntity<>(savedCoordinate, HttpStatus.CREATED);
}
- @PostMapping: HTTP POST 요청을 처리하는 메소드. /coordinates 경로로 들어오는 POST 요청은 이 메소드가 처리한다.
- @RequestBody Coordinate coordinate: 클라이언트가 보낸 요청 본문에 있는 좌표 데이터를 Coordinate 객체로 변환하여 이 메소드의 매개변수로 전달.
- Coordinate savedCoordinate = coordinateService.saveCoordinate(coordinate): 서비스 계층에서 새로운 좌표 데이터를 저장하고, 저장된 좌표 데이터를 반환받는다.
- return new ResponseEntity<>(savedCoordinate, HttpStatus.CREATED): 저장된 좌표 데이터를 응답으로 반환하며, 상태 코드는 201(CREATED)이다.
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteCoordinate(@PathVariable Long id) {
Optional<Coordinate> coordinate = coordinateService.getCoordinateById(id);
if (coordinate.isPresent()) {
coordinateService.deleteCoordinate(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
- @DeleteMapping("/{id}"): /coordinates/{id} 경로로 들어오는 DELETE 요청을 처리한다. URL의 {id} 값이 경로 변수로 사용.
- public ResponseEntity<Void> deleteCoordinate(@PathVariable Long id): 특정 id에 해당하는 좌표 데이터를 삭제하는 메소드. 반환하는 응답은 데이터 없이 상태 코드만 포함한다.
- Optional<Coordinate> coordinate = coordinateService.getCoordinateById(id): 서비스 계층에서 특정 id에 해당하는 좌표를 조회하고, 그 결과를 Optional 객체로 받는다.
- if (coordinate.isPresent()): 좌표가 존재하는 경우.
- coordinateService.deleteCoordinate(id): 서비스 계층에서 해당 id에 해당하는 좌표 데이터를 삭제한다.
- return new ResponseEntity<>(HttpStatus.NO_CONTENT): 성공적으로 삭제된 경우, 204(NO CONTENT) 응답을 반환한다.
- else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); }: 좌표가 존재하지 않는 경우, 404(NOT FOUND) 응답을 반환한다.