Spring Boot

[Spring Boot] @PathVariable vs. @RequestParam ๋ญ˜ ์จ์•ผํ• ๊นŒ? (feat.@QueryParam)

์šฐ์ฃผ๋ฌผ๊ณ ๊ธฐ 2025. 5. 3. 15:02
๋ฐ˜์‘ํ˜•

ํ”„๋กœ์ ํŠธ๋ฅผ ํ•  ๋•Œ ๋งค๊ฐœ๋ณ€์ˆ˜ ๋ฐ›์•„์„œ ํŠน์ • ์ž์›์„ ์กฐํšŒํ•˜๊ณ  ์‹ถ์„ ๋•Œ

(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์€ ์“ธ์ผ์ด ์—†์Œ.

๋ฐ˜์‘ํ˜•