Spring

@PathVariable, @RequestParam, @RequestBody에 대한 한가지 생각

kimc 2022. 2. 17. 01:21
반응형

 

이번 글을 통해 배워 갈 내용

  1. @PathVariable
  2. @RequestParam
  3. @RequestBody

먼저 정답은 없음을 밝힙니다.

다만 제가 느끼기에 효율적인 방법을 공유합니다.

 

 

 

1. @PathVariable

GET localhost:8080/cats/1

DELETE localhost:8080/cats/1

처럼 하나의 데이터, 객체를 GET 할 때 사용합니다.

AKA 경로를 지정할 때 사용

 

 

    @GetMapping("{cat-idx}")
    public Cat getCat(@PathVariable("cat-idx") int idx) {
        // 서비스에서 조회
        // 값 리턴
        return new Cat(idx, "puss", "fire");
    }

@PathVariable

 

 

2. @RequestParam

GET localhost:8080/cats? name=puss

GET에서 필터링 용도로 사용합니다.

@GetMapping("")
public List<Cat> getCatList(@RequestParam("type") String type) {
    // 서비스에서 조회
    // 값 리턴
    return Arrays.asList(new Cat(1, "puss", type), new Cat(2, "puss", type));
}

@RequestParam

 

3. @RequestBody

POST localhost:8080/cats

에 JSON 정보를 넣어서 많이 쓰며

{
	"name" : "puss",
    "home" : "my home"
}

데이터를 저장할 때 사용합니다

POST/PUT/PATCH를 사용할 때 활용합니다.

@PostMapping("")
public Cat createCat(@RequestBody Cat cat) {
    // 서비스에 등록
    // 필요시 값 리턴
    cat.setIdx(1);
    return cat;
}

@RequestBody

 

 

전체 코드 컨트롤러 예시

package com.example.exception01.controller;

import com.example.exception01.dto.Cat;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/api/cats")
public class CatController {

    @GetMapping("{cat-idx}")
    public Cat getCat(@PathVariable("cat-idx") int idx) {
        // 서비스에서 조회
        // 값 리턴
        return new Cat(idx, "puss", "fire");
    }

    @GetMapping("")
    public List<Cat> getCatList(@RequestParam("type") String type) {
        // 서비스에서 조회
        // 값 리턴
        return Arrays.asList(new Cat(1, "puss", type), new Cat(2, "puss", type));
    }

    @PostMapping("")
    public Cat createCat(@RequestBody Cat cat) {
        // 서비스에 등록
        // 필요시 값 리턴
        cat.setIdx(1);
        return cat;
    }
}

 

DTO 예시

package com.example.exception01.dto;

public class Cat {
    int idx;
    String name;
    String type;

    public Cat(int idx, String name, String type) {
        this.idx = idx;
        this.name = name;
        this.type = type;
    }

    public int getIdx() {
        return idx;
    }

    public void setIdx(int idx) {
        this.idx = idx;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

 

사용법에 맞게 사용해야겠다는 생각이 듭니다.

오늘도 즐거운 코딩 하시길 바랍니다~

 

 


참조 및 인용

https://stackoverflow.com/questions/67649464/difference-between-pathvariable-requestparam-and-requestbody

 

Difference between @PathVariable, @RequestParam, and @RequestBody

I understand what the @PathVariable, @RequestParam and @RequestBody does in Spring, but not clear on which scenarios we have to use them as they are used for extracting value from the URI. Why we h...

stackoverflow.com

 

 

 


블로그 추천 포스트

https://codemasterkimc.tistory.com/50

 

300년차 개발자의 좋은 코드 5계명 (Clean Code)

이번 글을 통해 배워갈 내용  좋은 코드(Clean Code)를 작성하기 위해 개발자로서 생각해볼 5가지 요소를 알아보겠습니다. 개요 좋은 코드란 무엇일까요? 저는 자원이 한정적인 컴퓨터 세상에서 좋

codemasterkimc.tistory.com

 

 

오늘도 즐거운 코딩 하시길 바랍니다 ~ :)

 


 

728x90
반응형