Spring Framework/Web on Servlet Stack

contextPath와 servletPath

헬로우월드 2023. 6. 23. 06:38

Spring Boot와 같이 내장 톰캣(embedded Tomcat) 을 사용하는 경우 대부분 contextPath와 servletPath를 사용하지 않습니다.

 

✅ 언제 contextPathservletPath가 사용되지 않을까?

1. contextPath가 없는 경우 (contextPath = "")

  • Spring Boot 기본 설정
    • 디폴트로 contextPath는 빈 문자열 ""입니다.
    • 즉, http://localhost:8080/이 루트 URL이 됩니다.
  • 설정하지 않으면 contextPath는 존재하지 않는 것으로 간주됨.
  • application.properties 또는 application.yml 에서 따로 설정하지 않으면 사용하지 않습니다.
# 예: contextPath 지정하지 않음
server:
  port: 8080
  servlet:
    context-path: ""

2. servletPath가 없는 경우 (servletPath = "/")

  • Spring MVC는 디폴트로 DispatcherServlet을 루트 경로 /에 매핑합니다.
  • registration.addMapping("/");
  • 즉, 모든 요청을 처리하기 위해 servletPath를 /로 설정하므로 사실상 생략된 효과가 있습니다.
  • web.xml 없이 Java Config 방식에서 이렇게 설정됩니다.

✅ 그럼 이 경우 lookupPath는 어떻게 되나요?

  • lookupPath = 전체 요청 경로 와 거의 동일해집니다.
  • 예: http://localhost:8080/users/123
    • contextPath: ""
    • servletPath: "/"
    • lookupPath: "/users/123" ← 이게 그대로 사용됨

 

✅ 정리

항목 전통적인 WAR 배포 방식 Spring Boot (내장 톰캣, 기본 설정)
contextPath 보통 /myapp 등 사용 없음 ("")
servletPath /app/* 등 사용 가능 보통 / (루트)로 고정
lookupPath contextPath + servletPath 제외 나머지 거의 전체 경로 그대로 사용됨

 

✅ 결론

Spring Boot 기반의 대부분의 웹 앱은 contextPathservletPath를 생략하거나 /로 고정합니다.
이 경우 DispatcherServlet은 Http request 전체 경로를 곧바로 lookupPath로 사용하여 핸들러 매핑을 수행합니다.