반응형
Spring Boot에서 클라이언트로부터 데이터 전달받는 방법
Spring Boot에서 클라이언트가 서버로 데이터를 전달하는 방법은 여러 가지가 있습니다. 이번 글에서는 HTTP 메서드(GET, POST)와 함께 서버가 데이터를 받는 방법을 정리하고, 예제 코드와 함께 설명하겠습니다.
1. GET 요청에서 데이터 전달 방법
GET 요청에서는 데이터를 URL을 통해 전달합니다. 주로 두 가지 방식이 사용됩니다.
1.1 쿼리 파라미터 (?
사용)
쿼리 파라미터를 사용하면 URL의 ?key=value
형태로 데이터를 전달할 수 있습니다.
예제 코드
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class QueryParamController {
@GetMapping("/search")
public String search(@RequestParam String keyword) {
return "Searching for: " + keyword;
}
}
클라이언트 요청 예시:
GET /search?keyword=spring
응답:
Searching for: spring
1.2 경로 변수 (@PathVariable
사용)
경로 변수를 사용하면 URL 경로의 일부를 변수로 활용할 수 있습니다.
예제 코드
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PathVariableController {
@GetMapping("/users/{id}")
public String getUser(@PathVariable int id) {
return "User ID: " + id;
}
}
클라이언트 요청 예시:
GET /users/123
응답:
User ID: 123
2. POST 요청에서 데이터 전달 방법
POST 요청에서는 데이터를 HTTP 요청의 본문(body)에 JSON 형식으로 전달할 수 있습니다.
2.1 @RequestBody
를 사용하여 JSON 데이터 받기
POST 요청에서 데이터를 전달할 때는 @RequestBody
를 사용하여 DTO(Data Transfer Object) 형태로 매핑할 수 있습니다.
예제 코드
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@PostMapping("/users")
public String createUser(@RequestBody UserDTO userDTO) {
return "User created: " + userDTO.getName() + ", Age: " + userDTO.getAge();
}
}
class UserDTO {
private String name;
private int age;
// Getters and Setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
클라이언트 요청 예시:
POST /users
Content-Type: application/json
{
"name": "John",
"age": 30
}
응답:
User created: John, Age: 30
3. 요약
HTTP 메서드 | 클라이언트 데이터 전달 방식 | 서버 처리 방식 |
GET | ?key=value 사용 |
@RequestParam |
GET | URL 경로 (/값 ) 사용 |
@PathVariable |
POST | JSON Body | @RequestBody (DTO) |
4. 결론
Spring Boot에서 클라이언트가 서버로 데이터를 전달하는 방법에는 여러 가지가 있습니다. 상황에 맞게 @RequestParam
, @PathVariable
, @RequestBody
를 적절히 활용하면 효율적인 API를 설계할 수 있습니다.
반응형
'개발 부트캠프 > 백엔드' 카테고리의 다른 글
[Spring] JPA(Java Persistence API) (0) | 2025.02.15 |
---|---|
[Spring] 서버가 클라이언트한테 데이터를 전달 하는 방법 (0) | 2025.02.13 |
[Spring] @Controller와 @RestController의 차이 (0) | 2025.02.10 |
[Spring] IoC & DI (0) | 2025.02.04 |
[Java] DBCP (0) | 2025.01.16 |