ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • API Controller
    Spring/Spring Framework 2021. 9. 8. 13:20
    💡
    @RestController = 해당 클래스는 REST API를 처리하는 Controller라는 것을 뜻함, 메소드의 리턴값이 View가 아닌 데이터 그 자체를 리턴하게 된다.

    1️⃣ GET Method

    • 리소스를 가져오는 것을 뜻한다
    • CRUD의 R(READ)
    • 호출할 때마다 같은 값을 얻을 수 있다 (멱등성)
    • 호출 전후, 서버 내 데이터 상태는 같다 (안정성)
    • Path Variable을 가질 수 있음.
    • Query Parameter를 사용한다
    • DataBody는 사용할 수 없다.

     

     

    기본 사용법

    💡
    @GetMapping = GET 메소드만을 위한 전용 애너테이션, RequestMapping의 method를 GET으로 지정한 것과 동일하다
    @GetMapping(path = "/hello")
    public String getHello() {
        return "get Hello";
    }
    
    @RequestMapping(method = RequestMethod.GET, path = "/hi")
    public String getHi() {
        return "hi";
    }

     

    Path Variable 사용

    💡
    @PathVariable = PathVariable로 받은 값을 표시할 때 사용합니다, path에서 지정한 변수명과 인자로 사용할 변수명이 같으면 name을 생략해도 됩니다. 다르다면 생략 불가능
    @GetMapping("/path-variable/{name}")
    public String pathVariable(@PathVariable(name = "name") String pathName) {
        System.out.println("PathVariable : " + pathName);
        return name;
    }

     

    Query Parameter 사용

    http://localhost:9090/api/get/query-param?user=ltk3934&email=ltk3934@daum.net&age=30

    ? 이후 부분이 Query Parameter입니다. <Key, Value> 형태의 데이터입니다.

    Map<String, String>형태로 입력

    💡
    @RequestParam = Query Parameter로 받을 때 붙여줘야 하는 애너테이션
    @GetMapping(path = "query-param1")
    public String queryParam(@RequestParam Map<String, String> queryParam) {
        StringBuilder sb = new StringBuilder();
        queryParam.entrySet().forEach(entry -> {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
            System.out.println("\n");
    
            sb.append(entry.getKey() + " = " + entry.getValue() + "\n");
        });
    
        return sb.toString();
    }

     

    변수 각각 매칭하기

    Query Parameter의 Key 이름을 알고 있을 때 사용할 수 있는 방법

    @GetMapping("query-param2")
    public String queryParam02(
            @RequestParam String name,
            @RequestParam String email,
            @RequestParam int age
    ) {
        System.out.println(name);
        System.out.println(email);
        System.out.println(age);
        return name + " " + email + " " + age;
    }

     

    DTO에 매칭하기 (추천 방법)

    미리 만들어 둔 DTO에 Query Parameter를 매칭시켜줍니다.

    @RequestParam 애너테이션을 사용하지 않아도 됩니다. ( ObjectMapper가 자동으로 매칭시켜준다 )

    // 변수와 이름을 spring boot가 매칭을 해준다
    @GetMapping("query-param03")
    public String queryParam03(UserRequest userRequest) {
        System.out.println(userRequest.getName());
        System.out.println(userRequest.getEmail());
        System.out.println(userRequest.getAge());
        return userRequest.toString();
    }

     

     


     

    2️⃣ POST Method

    • 리소스를 생성, 추가한다.
    • CRUD의 C(Create)
    • 멱등성 X
    • 안정성 X
    • Path Variable을 가질 수 있음.
    • Query Parameter를 사용할 수 있긴하지만 보통 사용하지 않는다
    • DataBody를 사용한다

     

    기본 사용법

    💡
    @RequestBody = DataBody를 사용할 때 붙여줘야 하는 애너테이션
    💡
    @PostMapping = POST 메소드만을 위한 전용 애너테이션, RequestMapping의 method를 POST로 지정한 것과 동일하다
    @PostMapping("/post")
    public void post(@RequestBody Map<String, Object> requestData) {
        requestData.forEach((key, value) -> {
            System.out.println("key : " + key);
            System.out.println("value : " + value);
        });
    }

     

     

    DTO에 매칭

    미리 만들어둔 DTO에 매칭해서 입력 받음.

    @PostMapping("/post")
    public void post(@RequestBody PostRequestDto requestData) {
        System.out.println(requestData);
    }

     

    DTO에 매칭시킬 때, 입력 받은 Json 데이터와 DTO의 속성의 이름을 맞춰주어야 합니다.

    public class PostRequestDto {
    
        private String account;
        private String email;
        private String address;
        private String password;
    
        @JsonProperty("phone_number") // 여기에 설정된 이름으로 json이 들어오면 여기로 매핑해준다
        private String phoneNumber;
    
        @JsonProperty("OTP") // 이걸 카멜 케이스나 스네이크 케이스가 아닌 걸 그냥 보내면 인식을 못하네... 저걸 붙여줘야 됨
        private String OTP;
    }
    💡
    @JsonProperty("name") = Json으로 들어오는 key값과 이 애너테이션이 붙은 속성을 매칭시켜줍니다. 카멜 케이스와 스네이크 케이스를 쓰지 않는 경우에는 반드시 매칭시켜주어야 합니다.

     

    Path Variable 사용법은 Get방식과 동일합니다.

     


    3️⃣ PUT Method

    • 리소스를 갱신, 생성
    • CRUD의 U(Update)
    • 멱등성 O
    • 안정성 X
    • Path Variable을 가질 수 있음.
    • Query Parameter를 사용 수 있지만 보통 사용하지 않는다
    • DataBody를 사용한다

     

    기본 사용법

    💡
    @PutMapping = PUT 메소드만을 위한 전용 애너테이션, RequestMapping의 method를 PUT으로 지정한 것과 동일하다
    @PutMapping("/put")
    public PutRequestDto put(@RequestBody PutRequestDto requestDto) {
        System.out.println(requestDto);
        return requestDto;
    }

     

    PathVariable과 DTO 함께 사용

    @PutMapping("/put/{userId}")
    public void putPathVariable(@RequestBody PutRequestDto requestDto,
                                @PathVariable Long userId) {
        System.out.println(requestDto);
        System.out.println(userId);
    }

     

     


    4️⃣ DELETE Method

    • 리소스를 삭제
    • CRUD의 D(Delete)
    • 멱등성 O
    • 안정성 X
    • Path Variable을 가질 수 있음.
    • Query Parameter를 사용한다
    • DataBody를 사용하지 않는다.

     

    기본 사용법

    💡
    @DeleteMapping = DELETE 메소드만을 위한 전용 애너테이션, RequestMapping의 method를 DELETE로 지정한 것과 동일하다
    @DeleteMapping("/delete/{userId}")
    public void delete(@PathVariable String userId, @RequestParam String account) {
        System.out.println(userId);
        System.out.println(account);
    }

     

     


    5️⃣ Response 만들기

    Text로 응답하기

    //TEXT
    @GetMapping("/text")
    public String text(@RequestParam String account) {
        return account;
    }

     

    Json으로 응답하기

    Object mapper가 Json을 Object로, Object를 Json으로 변환시켜 준다.

    //JSON
    @PostMapping("/json")
    public User json(@RequestBody User user) {
        return user;
    }

     

    💡
    @JsonNaming(value = PropertyNamingStrategies.SnakeCaseStrategy.class) 일괄적으로 이 클래스 안의 속성들을 스네이크 케이스와 매칭시켜주겠다는 의미 앞서 나온 @JsonProperty 와 같은 역할이지만 속성 한 개 적용이냐, 클래스 전체 적용이냐 차이

     

     

    ResponseEntity로 응답하기

    💡
    ResponseEntity = 상태 코드, 헤더, 바디 등 속성들을 함께 지정할 수 있음, body()에 Object를 넣으면 Object Mapper가 Json으로 변환시켜 준다.
    //ResponseEntity
    @PutMapping("/put1")
    public ResponseEntity<User> put(@RequestBody User user) {
        return ResponseEntity.status(HttpStatus.CREATED).body(user);
    }

     

    댓글

Designed by Tistory.