스프링Spring

@RequestParam, @PathVariable, @RequestBody, @RequestPart 차이 한눈에 정리

개린이9999 2025. 5. 16. 08:22
728x90

상세 예제 비교

1. @RequestParam

@GetMapping("/search")
public String search(@RequestParam String keyword) {
    return "검색어: " + keyword;
}

 

요청 예시:

GET /search?keyword=건축

 

2. @PathVariable

@GetMapping("/user/{id}")
public String getUser(@PathVariable Long id) {
    return "ID: " + id;
}

 

요청 예시:

GET /user/123

 

3. @RequestBody

@PostMapping("/user")
public String createUser(@RequestBody UserVO user) {
    return "이름: " + user.getName();
}

 

요청 예시:

POST /user
Content-Type: application/json

{
  "name": "홍길동",
  "age": 30
}

 

4. @RequestPart

@PostMapping("/upload")
public String upload(
    @RequestPart("file") MultipartFile file,
    @RequestPart("meta") UploadMeta meta) {
    return "파일명: " + file.getOriginalFilename();
}

 

요청 예시:

multipart/form-data로 JSON + 파일 같이 보낼 때

보통 파일 업로드 + 폼 데이터 같이 처리할 때 사용

 

728x90