Spring Boot | Spring MVC의 간단한 사용법 | 쿼리 파라미터(@RequestParam)값 얻기
코드 작성
src/main/java/sample/springboot/web/HelloController.java
package sample.springboot.web;
import java.util.Map;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(method=RequestMethod.GET)
public void getMethod(
@RequestParam String id,
@RequestParam Map<String, String> queryParameters,
@RequestParam MultiValueMap<String, String> multiMap) {
System.out.println("id=" + id);
System.out.println(queryParameters);
System.out.println(multiMap);
}
}
실행 결과
curl으로 테스트하기
$ curl "http://localhost:8080/hello?id=100&name=hoge&name=fuga"
서버 콘솔 출력
id=100
{id=100, name=hoge}
{id=[100], name=[hoge, fuga]}
설명
- 메소드의 인수에 @RequestParam 어노테이션를 부여하면 쿼리 매개 변수를 얻을 수 있다.
- 인수의 형태가 Map이라면 쿼리 파라미터 정보를 Map 형태로 얻을 수 있다.
- 하나의 매개 변수에 여러 값이 설정되어있는 경우, Spring에서 제공하는 MultiValueMap로 받을 수 있다.