Spring Boot | Spring MVC의 간단한 사용법 | 경로 변수(@PathVariable)값 얻기
코드 작성
src/main/java/sample/springboot/web/HelloController.java
package sample.springboot.web;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(value="/{id}/{name}", method=RequestMethod.GET)
public void getMethod(@PathVariable int id, @PathVariable String name) {
System.out.println("id=" + id + ", name=" + name);
}
}
실행 결과
curl으로 테스트하기
$ curl http://localhost:8080/hello/100/hoge
서버 콘솔 출력
id=100, name=hoge
설명
- 경로의 정의에 중괄호 ({})로 묶은 매개 변수를 정의한다.
- 메소드의 매개 변수로 같은 이름의 인수를 정의한다.
- @PathVariable 어노테이션이 부여한다.