Spring
@PathVariable, @RequestParam, @RequestBody에 대한 한가지 생각
kimc
2022. 2. 17. 01:21
반응형
이번 글을 통해 배워 갈 내용
- @PathVariable
- @RequestParam
- @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");
}
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));
}
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;
}
전체 코드 컨트롤러 예시
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://codemasterkimc.tistory.com/50
오늘도 즐거운 코딩 하시길 바랍니다 ~ :)
728x90
반응형