Spring MVC의 @RequestParam과 @PathVariable 사용법
2024. 5. 23. 10:00ㆍBack-End/Spring
Spring MVC는 웹 애플리케이션을 쉽게 만들 수 있는 다양한 어노테이션을 제공하는 프레임워크이다. 이 중 @RequestParam과 @PathVariable은 URL로부터 파라미터를 추출하는 데 사용된다. 이 글에서는 이 두 어노테이션의 차이점과 사용법을 자세히 살펴보겠다.
@RequestParam
@RequestParam 어노테이션은 HTTP 요청의 파라미터를 메서드의 파라미터로 바인딩하는 데 사용된다. GET 요청이나 POST 요청에서 쿼리 스트링 또는 폼 데이터를 쉽게 처리할 수 있다.
예제 1: 기본 사용법
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class RequestParamController {
@GetMapping("/greeting")
public String greeting(@RequestParam(name = "name", required = false, defaultValue = "World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
설명
- @RequestParam(name = "name", required = false, defaultValue = "World")는 URL 쿼리 파라미터 name을 메서드 파라미터 name에 바인딩하는 것이다.
- required가 false로 설정되어 있어 name 파라미터가 없어도 에러가 발생하지 않는다. defaultValue는 파라미터가 없을 때 사용할 기본값을 지정하는 것이다.
결과
- URL: http://localhost:8080/greeting?name=John
- URL: http://localhost:8080/greeting
@PathVariable
@PathVariable 어노테이션은 URL 경로에 있는 값을 메서드의 파라미터로 바인딩하는 데 사용된다. RESTful 웹 서비스에서 자주 사용된다.
예제 2: 기본 사용법
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class PathVariableController {
@GetMapping("/user/{userId}")
@ResponseBody
public String getUser(@PathVariable("userId") String userId) {
return "User ID: " + userId;
}
}
설명
- @PathVariable("userId")는 URL 경로에서 {userId} 부분을 메서드 파라미터 userId에 바인딩하는 것이다.
- @ResponseBody는 반환 값을 HTTP 응답 본문으로 직접 보내는 데 사용된다.
결과
- URL: http://localhost:8080/user/123
@RequestParam과 @PathVariable의 차이점
- 위치: @RequestParam은 쿼리 스트링 또는 폼 데이터에서 값을 가져오고, @PathVariable은 URL 경로에서 값을 가져오는 것이다.
- 용도: @RequestParam은 주로 필터링, 검색, 페이징 등에 사용되며, @PathVariable은 RESTful 서비스에서 리소스를 식별하는 데 사용된다.
두 어노테이션을 같이 사용하는 예제
두 어노테이션을 함께 사용하는 예제를 보겠다.
예제 3: 복합 사용
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class CombinedController {
@GetMapping("/products/{productId}")
public String getProduct(@PathVariable("productId") String productId, @RequestParam(name = "category", required = false) String category, Model model) {
model.addAttribute("productId", productId);
model.addAttribute("category", category);
return "product";
}
}
product.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Product</title>
</head>
<body>
<h1>Product Details</h1>
<p>Product ID: <span th:text="${productId}"></span></p>
<p>Category: <span th:text="${category}"></span></p>
</body>
</html>
설명
- @PathVariable("productId")는 URL 경로에서 {productId} 값을 추출하는 것이다.
- @RequestParam(name = "category", required = false)는 쿼리 스트링에서 category 값을 추출하는 것이다.
결과
- URL: http://localhost:8080/products/456?category=Electronics
- URL: http://localhost:8080/products/456
결론
Spring MVC의 @RequestParam과 @PathVariable 어노테이션은 웹 애플리케이션에서 URL로부터 파라미터를 추출하는 데 매우 유용하다. @RequestParam은 쿼리 스트링 또는 폼 데이터를 처리하는 데 사용되고, @PathVariable은 URL 경로의 변수를 처리하는 데 사용된다. 이 두 어노테이션을 적절히 활용하면 더욱 유연하고 강력한 웹 애플리케이션을 개발할 수 있다.
'Back-End > Spring' 카테고리의 다른 글
Hibernate Naming Strategies (0) | 2024.06.26 |
---|---|
JPA 기초 개념과 코드 예제 (Spring JPA 아님!!) (0) | 2024.05.28 |
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping (0) | 2024.05.23 |
쿠키(Cookie)와 세션(Session) (0) | 2024.05.23 |
Forward와 Redirect(스프링 MVC에서의 요청 흐름 제어) (0) | 2024.05.22 |