java/spring
[Spring] Controller에서 pathvariable로 path(/aaa/bbb) 값 받는 법
danuri
2022. 7. 15. 17:05
API에서 Pathvariable은 자주 쓰인다.
GET: /user/1 -> 여기서 '1'을 pathvariable로 가져올 수 있다.
하지만 만약, path 형태의 값을 pathvariable로 가져오고 싶다면?
GET: /user/home/server/list -> 여기서 'home/server/list'를 pathvariable로 가져오고 싶지만, spring에서는 /user/home/server/list 라는 경로에 해당하는 컨트롤러를 찾을 뿐이다.
따라서, 다른 방식을 사용할 필요가 있다.
@GetMapping("/user/**")
public String getPath(HttpServletRequest request) {
return request.getRequestURI().split(request.getContextPath() + "/user/")[1];
}
위와 같이, request URI를 split해서 필요한 부분을 꺼내는 방법이다.
여기서, request.getRequestURI()는 "/user/home/server/list" 이고, request.getContextPath()는 프로젝트 path이다. 따로 지정하지 않았다면 ""을 갖는다.
GET: /user/home/server/list을 호출해보면 'home/server/list'가 정상적으로 출력되는 것을 볼 수 있다.
참고자료