Spring Content-type 별 파라미터 어노테이션 정리

형기브·2023년 7월 20일
1

SPRING

목록 보기
2/3

지금까지 배운 파라미터를 받는 방식들을 정리한다

Spring으로 백앤드를 공부할 때는 어노테이션 중심으로 생각을 했어서 content-type을 대충 보고 넘어 갔었다. 그런데 프론트와 협업을 하면서 데이타 타입을 맞추는 것이 엄청 중요하다는 것을 깨닫고 이참에 글로 정리해 본다.

content-type

1. URL Path의 값을 받아오는 방법

요청한 도메인/api/{id}/post 의 {id}값을 파라미터로 가져올 때 -> @PathVariable (생략 금지)

예시코드

@메소드메핑("도메인/api/{id}/post")
public String post(@PathVariable Long id)
{
return "return";
}

요청한 도메인이 query string 형식일 때 -> @RequestParam

도메인/api/post?id=1&title=john

@GetMapping("/api/post?id=1&title=john")
public String post(@RequestParam Long id, 
						@RequestParam String title)
{
return "return";
}

2. Content-type별 방법

잠깐 !

form-data는 텍스트형식 뿐 아니라 이진데이터 즉 파일 업로드 같은 복잡한 작업에 적합!
x-www-form-urlencoded는 form-data를 인코딩하여 url query string형식으로 전송.

Content-type : application/x-www-form-urlencoded -> @RequestParam , @ModelAttribute

Post요청이면서 body의 값이 아래 형태로 담겨져 올 경우

Body : id=1&title=john

@PostMapping("/api/post")
public String post(@RequestParam Long id, 
						@RequestParam String title)
{
return "return";
}
@PostMapping("/api/post")
public String post(@ModelAttribute Post post)
{
return "return";
}

쉽게말해 @RequestParam은 각각의 변수?를 전송할 때,
@ModelAttribute 그 변수들을 객체에 담아서 전송할 때 쓴다.


Content-type : application/json

json 형태의 데이터를 주고받을 때 -> @RequestBody (생략 금지)
{
"id":2,
"title":"john"
}

@PostMapping("/api/post")
public String post(@RequestBody Post post)
{
return "return";
}

가끔 헷갈릴 때마다 찾아와서 보려고 포스트를 남긴다.

그렇지만 역시 많이 사용해보면서 몸으로 익히는게 가장 빠른 길인 것 같다.

profile
Slow but Steady

0개의 댓글