ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring boot] @RequestParam / @RequestBody + @RequestPart 구분하기
    Spring Boot 2024. 7. 27. 20:03

     

    지금 하고 있는 프로젝트에서 API를 구현하는데

    갑자기 머리속에 엉망징창으로 넣어놨던 클라이언트 요청 파라미터 관련 어노테이션을 정리해보고자 게시글을 작성하려한다.

     

    @RequestParam
    사용법 : @RequestParam String name, @RequestParam int age
    요청 방법 : form-data 형식
    Key: username, Value: John
    Key: password, Value: secret

    @RequestBody
    사용법 : @RequestBody User user
    요청방법 : application/json raw 형식(json)
    {
      "name": "John",
      "age": 30
    }

    @RequestParam과 @RequestBody를 함께 사용도 가능하다.
    @RequestParam과 @RequestBody를 함께 사용하는 경우, 일반적으로 @RequestBody로는 JSON 형식의 객체를 전달하고, @RequestParam으로는 개별적인 파라미터를 전달한다 
    AdminManagersDTO를 JSON 형식으로 전달할 때는 @RequestBody를 사용해야 합니다.

    @RequestParam("petsMbtiInfoIdx") Integer petsMbtiInfoIdx,
                                            @RequestParam("title") String title,
                                            @RequestParam("feature") String feature,
                                            @RequestParam("careInfo") String careInfo,
                                            @RequestParam("imagePath") String imagePath,
                                            @RequestParam("imageName") String imageName,
                                            @RequestParam("adminManagerIdx") Integer adminManagerIdx,
                                            @RequestPart("multipartFile") MultipartFile multipartFile,
                                            @RequestPart("adminManagersDTO") @Valid AdminManagersDTO adminManagersDTO

    사용법 : 
    Headers: Content-Type을 multipart/form-data으로 설정
    Body: 아래와 같이 form-data 형식으로 설정합니다.
    Key: petsMbtiInfoIdx, Value: 1
    Key: title, Value: 전략가를 수정한다면?
    Key: feature, Value: 새로운 특징
    Key: careInfo, Value: 새로운 케어 정보
    Key: imagePath, Value: /images/new_path
    Key: imageName, Value: new_image.png
    Key: adminManagerIdx, Value: 1
    Key: multipartFile, Value: 파일을 선택합니다.
    Key: adminManagersDTO, Type: Text, Value: JSON 형식의 문자열
    {
      "adminManagerIdx": 1,
      "id": "admin",
      "password": "password",
      "name": "Admin Name",
      "phoneNumber": "010-1234-5678"
    }

    @RequestPart를 사용하여 multipartFile과 adminManagersDTO를 수신합니다.
    @RequestPart는 @RequestParam과 달리 JSON 형식의 데이터를 수신할 수 있습니다.
    이렇게 설정하면, 포스트맨을 통해 @RequestParam과 @RequestBody를 함께 사용하는 요청을 보낼 수 있습니다. adminManagersDTO는 JSON 형식의 문자열로 전달되며, 나머지 필드는 @RequestParam을 통해 쿼리 스트링으로 전달됩니다.

Designed by Tistory.