[Spring Boot] @PathVariable vs. @RequestParam ๋ญ ์จ์ผํ ๊น? (feat.@QueryParam)
ํ๋ก์ ํธ๋ฅผ ํ ๋ ๋งค๊ฐ๋ณ์ ๋ฐ์์ ํน์ ์์์ ์กฐํํ๊ณ ์ถ์ ๋
(ex. id๊ฐ 10์ธ ๊ฒ์๊ธ์ ๋ณด๊ณ ์ถ์ ๋)
์ฐ๋ ๋ฐฉ๋ฒ์ผ๋ก ๋ํ์ ์ผ๋ก
@PathVariable์ ๋ง์ด ์.
โ
๊ทผ๋ฐ @ReqeustParam๋ ์ด๋์ ๋ดค๋๋ฐ,
๋ ์ค ๋ญ์จ์ผํ ๊น!!
โ
์ด๋จ ๋ ๋ฌด์์ ์จ์ผํ ๊น..์ ๋ฆฌํด๋ณด๊ฒ ์
โ
@PathVariable
๊ฐ์ฅ ๋ง์ด ์ฐ์ด๋ ๋ฐฉ์์ธ๋ฐ,
@GetMapping("/api/articles/{id}")
public ResponseEntity<ArticleResponseDto> findArticle(@PathVariable("id") Long id) {
Article article = blogService.findById(id);
return ResponseEntity.ok().body(new ArticleResponseDto(article));
}
์ด๋ฐ์์ผ๋ก ํน์ ์์์ ์กฐํํ ๋ ์!!!
articles์์ id๊ฐ 10์ธ๊ฑธ ๋ณด๊ณ ์ถ์ผ๋ฉด
โ
URL์ด
GET api/artibles/10
์ด๋ฐ์์ผ๋ก ๋งค์ฐ RESTfulํ ๋ฐฉ์์ด ๋จ.
โ
๊ทธ๋ผ ์ ๋ถ ์ด๊ฑธ ์ฐ๋ฉด ๋๋๊ฑฐ ์๋๋
โ
๋ค๋ฅธ ๋ฐฉ์์ ์ ์๋๊ฑธ๊น??
@RequestParam
์ ์์ค์ฝ๋๋ฅผ ๊ทธ๋๋ก RequestParam์ผ๋ก ๋ฐ๊ฟ๋ณด๋ฉด
@GetMapping("/api/articles")
public ResponseEntity<ArticleResponseDto> findArticle(@RequestParam("id") Long id) {
Article article = blogService.findById(id);
return ResponseEntity.ok().body(new ArticleResponseDto(article));
}
์ด๋ ๊ฒ ๋จ.
โ
์๊ธด๊ฑด ๊ฑฐ์ ๋น์ทํ๋ฐ,
โ
RequestParam์ ์ด๋ด๋ ์ฐ๋๊ฒ ์๋@!!!!
@GetMapping("/api/articles")
public ResponseEntity<List<ArticleResponseDto>> findArticles(
@RequestParam(required = false) String title,
@RequestParam(required = false) String author,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size
) {
List<Article> articles = blogService.searchArticles(title, author, page, size);
List<ArticleResponseDto> response = articles.stream()
.map(ArticleResponseDto::new)
.toList();
return ResponseEntity.ok().body(response);
}
RequestParam์ ์ด๋ฐ์์ผ๋ก
์ฌ๋ฌ ๊ฒ์ ์กฐ๊ฑด, ํํฐ๋ง, ํ์ด์ง ๋ฑ์ ๊ฑธ๊ณ ์ถ์๋
๋น์ ๋ฐํ๋ ์ด๋ ธํ ์ด์ ์
โ
โ
์ด๋ ๊ฒ ๋๋ฉด ์์ฒญ URL์ด
GET /api/articles?title=JPA&author=ํ๊ธธ๋&page=0&size=5
์ด๋ฐ์์ผ๋ก ๋๋๊ฑฐ์.

์ฑ์งํผํฐ๊ฐ ์ด๋ฌ์ผ ์ ๋ฆฌํด์ค
์ถ๊ฐ)
@QueryParam ์ ๋ญ๊น?
@RequestParam์ด๋ ๋๊ฐ์ ์ ๋ผ๊ณ ๋ณด๋ฉด ๋จ
๋ค๋ง!!!!!!
โ
@RequestParam์ ์์์ด Spring MVC
@QueryParam์ ์์์ด JAX-RS
โ
์คํ๋ง์ ์์ฒด ํ๋ ์์ํฌ์ธ Spring MVC๋ฅผ ์ฐ๊ธฐ ๋๋ฌธ์
๋ด๊ฐ ์คํ๋ง๋ถํธ๋ก ํ์ ํ๊ณ ์๋ค ํ๋ฉด
@QueryParam์ ์ธ์ผ์ด ์์.